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.4.24;
pragma solidity ^0.4.19; //for Ethereum Classic
import "./dependencies/SafeMath.sol";
import "./dependencies/Ownable.sol";
import "./dependencies/RLP.sol";
import "./dependencies/BytesLib.sol";
import "./dependencies/ERC721Basic.sol";
import "./dependencies/ERC721BasicToken.sol";
import "./dependencies/AddressUtils.sol";
contract TokenContract is ERC721BasicToken {
using SafeMath for uint256;
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
using RLP for bytes;
using BytesLib for bytes;
address depositContract;
address custodian;
address custodianHome;
uint256 mintedAmount;
uint256 public mintNonce = 0;
mapping (uint256 => uint256) public transferNonce;
mapping (bytes32 => address) public custodianApproval;
constructor (address _custodian) {
custodian = _custodian;
}
modifier onlyCustodian() {
require(custodian == msg.sender);
_;
}
event Mint(uint256 amount,
address indexed depositedTo,
uint256 mintNonce,
uint256 tokenId);
event Withdraw(uint256 tokenId);
event TransferRequest(address indexed from,
address indexed to,
uint256 indexed tokenId,
uint256 declaredNonce,
bytes32 approvalHash);
function setDepositContract(address _depositContract) onlyCustodian public {
depositContract = _depositContract;
}
function mint(uint256 _value, address _to) public {
//might have to log the value, to, Z details
bytes memory value = uint256ToBytes(_value);
bytes memory to = addressToBytes(_to);
bytes memory Z = uint256ToBytes(mintNonce);
uint256 tokenId = bytes32ToUint256(keccak256(value.concat(to).concat(Z)));
_mint(_to, tokenId);
emit Mint(_value, _to, mintNonce, tokenId);
mintNonce += 1;
}
function withdraw(uint256 _tokenId) public {
emit Withdraw(_tokenId);
//USED TO ANNOUNCE A WITHDRAWL (DOESNT NECESSISTATE SUBMISSION)
}
/* ERC721 Related Functions --------------------------------------------------*/
// Mapping from token ID to approved address
/**
* @dev Requests transfer of 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
* @param _declaredNonce uint256 nonce, depth of transaction
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId,
uint256 _declaredNonce
)
public
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
require(_declaredNonce == transferNonce[_tokenId]);
clearApproval(_from, _tokenId);
//TODO: Double check if hash is secure, no chance of collision
bytes32 approvalHash = keccak256(uint256ToBytes(_tokenId)
.concat(uint256ToBytes(_declaredNonce)));
custodianApproval[approvalHash] = _to;
transferNonce[_tokenId] += 1;
emit TransferRequest(_from, _to, _tokenId, _declaredNonce, approvalHash);
}
function custodianApprove(uint256 _tokenId, uint256 _declaredNonce)
onlyCustodian public {
require(exists(_tokenId));
bytes32 approvalHash = keccak256(uint256ToBytes(_tokenId)
.concat(uint256ToBytes(_declaredNonce)));
address _to = custodianApproval[approvalHash];
address _from = ownerOf(_tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
clearCustodianApproval(approvalHash);
}
function revertTransfer(uint256 _tokenId, uint256 _declaredNonce) public {
require(isApprovedOrOwner(msg.sender, _tokenId), "no approval/ not owner");
clearCustodianApproval(keccak256(uint256ToBytes(_tokenId)
.concat(uint256ToBytes(_declaredNonce))));
}
/* View functions --------------------------------------------------*/
function viewTransferRequest(bytes32 _approvalHash) public view
returns(address) {
return custodianApproval[_approvalHash];
}
/* Util functions --------------------------------------------------*/
/**
* @dev Internal function to clear current custodian approval of a given token ID
* @param _approvalHash bytes32 ID of the token to be transferred
*/
function clearCustodianApproval(bytes32 _approvalHash) internal {
if (custodianApproval[_approvalHash] != address(0)) {
custodianApproval[_approvalHash] = address(0);
}
}
function bytesToBytes32(bytes b, uint offset) private pure returns (bytes32) {
bytes32 out;
for (uint i = 0; i < 32; i++) {
out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
function stringToBytes( string s) internal returns (bytes memory b3){
b3 = bytes(s);
return b3;
}
// Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity
function uint256ToBytes(uint256 x) internal returns (bytes b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
// Tjaden Hess https://ethereum.stackexchange.com/questions/884/how-to-convert-an-address-to-bytes-in-solidity
function addressToBytes(address a) internal returns (bytes b) {
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
// https://ethereum.stackexchange.com/questions/6498/how-to-convert-a-uint256-type-integer-into-a-bytes32
function bytes32ToUint256(bytes32 n) internal returns (uint256) {
return uint256(n);
}
}
| https:ethereum.stackexchange.com/questions/6498/how-to-convert-a-uint256-type-integer-into-a-bytes32 | function bytes32ToUint256(bytes32 n) internal returns (uint256) {
return uint256(n);
}
| 7,283,682 |
./full_match/1/0x49a3caab781f711aD74C9d2F34c3cbD835d6A608/sources/contracts/distribution/TokenDistributor.sol | @inheritdoc ITokenDistributor | function getRemainingMemberSupply(
Party party,
uint256 distributionId
) external view returns (uint128) {
return _distributionStates[party][distributionId].remainingMemberSupply;
}
| 2,946,116 |
pragma solidity ^0.4.23;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/IdentityProtocol.sol";
import "./helpers/ThrowProxy.sol";
contract TestIdentityProtocol {
IdentityProtocol protocol = IdentityProtocol(DeployedAddresses.IdentityProtocol());
ThrowProxy throwProxy = new ThrowProxy(address(protocol));
IdentityProtocol throwableProtocol = IdentityProtocol(address(throwProxy));
address personalIdentity;
address multiSigIdentity;
address[] owners;
// Testing the createPersonalIdentity() function
function testUserCanCreatePersonalIdentity() public {
personalIdentity = protocol.createPersonalIdentity(
"PersonalTest",
"QmeHy1gq8QHVchad7ndEsdAnaBWGu1CAVmYCb4aTJW2Pwa"
);
}
// Testing the createMultiSigIdentity() function
function testUserCanCreateMultiSigIdentity() public {
owners.push(address(this));
multiSigIdentity = protocol.createMultiSigIdentity(
"MultiSigTest",
"QmeHy1gq8QHVchad7ndEsdAnaBWGu1CAVmYCb4aTJW2Pwa",
owners,
uint256(1)
);
}
// Testing the createMultiSigIdentity() function
function testUserCannotCreateIdentityWithDuplicatedId() public {
address(throwableProtocol).call(abi.encodeWithSignature("createMultiSigIdentity(bytes,bytes,address[],uint256)",
"MultiSigTest",
"QmeHy1gq8QHVchad7ndEsdAnaBWGu1CAVmYCb4aTJW2Pwa",
owners,
uint256(1)
));
throwProxy.shouldThrow();
}
// Testing the createPersonalIdentity() function
function testUserCanGetIdentity() public {
address storedIdentity;
storedIdentity = protocol.getIdentity("PersonalTest");
Assert.equal(storedIdentity, personalIdentity, "The retrieved identity must be the personal identity");
}
// Testing the createPersonalIdentity() function
function testUserCannotGetInvalidIdentity() public {
address(throwableProtocol).call(abi.encodeWithSignature("getIdentity(bytes)","InvalidIdentity"));
throwProxy.shouldThrow();
}
}
| Testing the createPersonalIdentity() function | function testUserCannotGetInvalidIdentity() public {
address(throwableProtocol).call(abi.encodeWithSignature("getIdentity(bytes)","InvalidIdentity"));
throwProxy.shouldThrow();
}
| 5,508,215 |
./partial_match/4/0xfDcF6aA1715253aC31675Ce16cDF10E01729Cf93/sources/Liquidity_v3.sol | uint256 num = amount.mul(userInterestRate); uint256 denom = 10000; uint256 reward = num.div(denom); | function _withdrawAfterClose(
address from,
uint256 amount,
uint256 _userIndex
) private returns (bool) {
deposits[from].paid = true;
uint256 i;
uint256 initialRate = rates[_userIndex].newInterestRate;
uint256 initialTime = deposits[from].depositTime;
uint256 time;
for (i = _userIndex; i <= index; i++) {
if (initialTime >= endTime) {
break;
if (initialTime <= rates[i].timeStamp) {
if (endTime <= rates[i].timeStamp) {
time = rates[i].timeStamp.sub(endTime);
time = rates[i].timeStamp.sub(initialTime);
uint256 initialAmount = deposits[from].depositAmount;
uint256 interest;
{
uint256 num =
time.mul(initialAmount.mul(initialRate));
uint256 denom = period.mul(10000);
interest = num.div(denom);
}
deposits[from].depositAmount = initialAmount.add(
interest
);
deposits[from].depositTime = rates[i].timeStamp;
initialRate = rates[i].newInterestRate;
initialTime = rates[i].timeStamp;
}
}
}
}
uint256 interestRate = rates[deposits[from].userIndex].newInterestRate;
if (deposits[from].depositTime < endTime) {
uint256 time1 = endTime.sub(deposits[from].depositTime);
uint256 finalInterest;
{
uint256 num = time1.mul(deposits[from].depositAmount);
finalInterest = num.div(denom).mul(interestRate);
}
deposits[from].depositAmount += finalInterest;
}
uint256 reward = deposits[from].depositAmount.sub(amount);
require(reward <= rewardBalance, "Not enough rewards");
bool principalPaid = _payDirect(from, amount, tokenAddress);
bool rewardPaid = _payDirect(from, reward, rewardTokenAddress);
require(principalPaid && rewardPaid, "Error paying");
emit PaidOut(tokenAddress, rewardTokenAddress, from, amount, reward);
stakedBalance = stakedBalance.sub(amount);
rewardBalance = rewardBalance.sub(reward);
hasStaked[from] = false;
return true;
}
| 8,756,439 |
./full_match/80001/0x85C1929cC1794dd7c25d16d095a09318Cc57d174/sources/contracts/WorkerAuthManagerImpl.sol | XXX: we can't do this because the worker need to accept the job before receiving an authorization | function hireAndAuthorize(
address payable _workerAddress,
address _dappAddress
) public override payable {
workerManager.hire(_workerAddress);
authorize(_workerAddress, _dappAddress);
}
| 872,982 |
pragma solidity ^0.5.0;
interface ICustodian {
function users(uint) external returns(address);
function totalUsers() external returns (uint);
function totalSupplyA() external returns (uint);
function totalSupplyB() external returns (uint);
function balanceOf(uint, address) external returns (uint);
function allowance(uint, address, address) external returns (uint);
function transfer(uint, address, address, uint) external returns (bool);
function transferFrom(uint, address, address, address, uint) external returns (bool);
function approve(uint, address, address, uint) external returns (bool);
}
/// @title Esplanade - coordinate multiple custodians, oracles and other contracts.
/// @author duo.network
contract Esplanade {
/*
* Constants
*/
uint constant WEI_DENOMINATOR = 1000000000000000000;
uint constant BP_DENOMINATOR = 10000;
uint constant MIN_POOL_SIZE = 5;
uint constant VOTE_TIME_OUT = 2 hours;
uint constant COLD_POOL_IDX = 0;
uint constant HOT_POOL_IDX = 1;
uint constant NEW_STATUS = 0;
uint constant IN_COLD_POOL_STATUS = 1;
uint constant IN_HOT_POOL_STATUS = 2;
uint constant USED_STATUS = 3;
enum VotingStage {
NotStarted,
Moderator,
Contract
}
/*
* Storage
*/
VotingStage public votingStage;
address public moderator;
// 0 is cold
// 1 is hot
address [][] public addrPool =[
[
0xAc31E7Bc5F730E460C6B2b50617F421050265ece,
0x39426997B2B5f0c8cad0C6e571a2c02A6510d67b,
0x292B0E0060adBa58cCA9148029a79D5496950c9D,
0x835B8D6b7b62240000491f7f0B319204BD5dDB25,
0x8E0E4DE505ee21ECA63fAF762B48D774E8BB8f51,
0x8750A35A4FB67EE5dE3c02ec35d5eA59193034f5,
0x8849eD77E94B075D89bB67D8ef98D80A8761d913,
0x2454Da2d95FBA41C3a901D8ce69D0fdC8dA8274e,
0x56F08EE15a4CBB8d35F82a44d288D08F8b924c8b
],
[
0x709494F5766a7e280A24cF15e7feBA9fbadBe7F5,
0xF7029296a1dA0388b0b637127F241DD11901f2af,
0xE266581CDe8468915D9c9F42Be3DcEd51db000E0,
0x37c521F852dbeFf9eC93991fFcE91b2b836Ad549,
0x2fEF2469937EeA7B126bC888D8e02d762D8c7e16,
0x249c1daD9c31475739fBF08C95C2DCB137135957,
0x8442Dda926BFb4Aeba526D4d1e8448c762cf4A0c,
0xe71DA90BC3cb2dBa52bacfBbA7b973260AAAFc05,
0xd3FA38302b0458Bf4E1405D209F30db891eBE038
]
];
// 0 is new address
// 1 in cold pool
// 2 in hot pool
// 3 is used
mapping(address => uint) public addrStatus;
address[] public custodianPool;
mapping(address => bool) public existingCustodians;
address[] public otherContractPool;
mapping(address => bool) public existingOtherContracts;
uint public operatorCoolDown = 1 hours;
uint public lastOperationTime;
bool public started;
address public candidate;
mapping(address => bool) public passedContract;
mapping(address => bool) public voted;
uint public votedFor;
uint public votedAgainst;
uint public voteStartTimestamp;
/*
* Modifiers
*/
modifier only(address addr) {
require(msg.sender == addr);
_;
}
modifier inColdAddrPool() {
require(addrStatus[msg.sender] == IN_COLD_POOL_STATUS);
_;
}
modifier inHotAddrPool() {
require(addrStatus[msg.sender] == IN_HOT_POOL_STATUS);
_;
}
modifier isValidRequestor(address origin) {
address requestorAddr = msg.sender;
require((existingCustodians[requestorAddr]
|| existingOtherContracts[requestorAddr])
&& addrStatus[origin] == IN_COLD_POOL_STATUS);
_;
}
modifier inUpdateWindow() {
uint currentTime = getNowTimestamp();
if (started)
require(currentTime - lastOperationTime >= operatorCoolDown);
_;
lastOperationTime = currentTime;
}
modifier inVotingStage(VotingStage _stage) {
require(votingStage == _stage);
_;
}
modifier allowedToVote() {
address voterAddr = msg.sender;
require(!voted[voterAddr] && addrStatus[voterAddr] == 1);
_;
}
/*
* Events
*/
event AddAddress(uint poolIndex, address added1, address added2);
event RemoveAddress(uint poolIndex, address addr);
event ProvideAddress(uint poolIndex, address requestor, address origin, address addr);
event AddCustodian(address newCustodianAddr);
event AddOtherContract(address newContractAddr);
event StartContractVoting(address proposer, address newContractAddr);
event TerminateContractVoting(address terminator, address currentCandidate);
event StartModeratorVoting(address proposer);
event TerminateByTimeOut(address candidate);
event Vote(address voter, address candidate, bool voteFor, uint votedFor, uint votedAgainst);
event CompleteVoting(bool isContractVoting, address newAddress);
event ReplaceModerator(address oldModerator, address newModerator);
/*
* Constructor
*/
/// @dev Contract constructor sets operation cool down and set address pool status.
/// @param optCoolDown operation cool down time.
constructor(uint optCoolDown) public
{
votingStage = VotingStage.NotStarted;
moderator = msg.sender;
addrStatus[moderator] = USED_STATUS;
for (uint i = 0; i < addrPool[COLD_POOL_IDX].length; i++)
addrStatus[addrPool[COLD_POOL_IDX][i]] = IN_COLD_POOL_STATUS;
for (uint j = 0; j < addrPool[HOT_POOL_IDX].length; j++)
addrStatus[addrPool[HOT_POOL_IDX][j]] = IN_HOT_POOL_STATUS;
operatorCoolDown = optCoolDown;
}
/*
* MultiSig Management
*/
/// @dev proposeNewManagerContract function.
/// @param addr new manager contract address proposed.
function startContractVoting(address addr)
public
only(moderator)
inVotingStage(VotingStage.NotStarted)
returns (bool) {
require(addrStatus[addr] == NEW_STATUS);
candidate = addr;
addrStatus[addr] = USED_STATUS;
votingStage = VotingStage.Contract;
replaceModerator();
startVoting();
emit StartContractVoting(moderator, addr);
return true;
}
/// @dev terminateVoting function.
function terminateContractVoting()
public
only(moderator)
inVotingStage(VotingStage.Contract)
returns (bool) {
votingStage = VotingStage.NotStarted;
emit TerminateContractVoting(moderator, candidate);
replaceModerator();
return true;
}
/// @dev terminateVoting voting if timeout
function terminateByTimeout() public returns (bool) {
require(votingStage != VotingStage.NotStarted);
uint nowTimestamp = getNowTimestamp();
if (nowTimestamp > voteStartTimestamp && nowTimestamp - voteStartTimestamp > VOTE_TIME_OUT) {
votingStage = VotingStage.NotStarted;
emit TerminateByTimeOut(candidate);
return true;
} else
return false;
}
/// @dev proposeNewModerator function.
function startModeratorVoting() public inColdAddrPool() returns (bool) {
candidate = msg.sender;
votingStage = VotingStage.Moderator;
removeFromPoolByAddr(COLD_POOL_IDX, candidate);
startVoting();
emit StartModeratorVoting(candidate);
return true;
}
/// @dev proposeNewModerator function.
function vote(bool voteFor)
public
allowedToVote()
returns (bool) {
address voter = msg.sender;
if (voteFor)
votedFor = votedFor + 1;
else
votedAgainst += 1;
voted[voter] = true;
uint threshold = addrPool[COLD_POOL_IDX].length / 2;
emit Vote(voter, candidate, voteFor, votedFor, votedAgainst);
if (votedFor > threshold || votedAgainst > threshold) {
if (votingStage == VotingStage.Contract) {
passedContract[candidate] = true;
emit CompleteVoting(true, candidate);
}
else {
emit CompleteVoting(false, candidate);
moderator = candidate;
}
votingStage = VotingStage.NotStarted;
}
return true;
}
/*
* Moderator Public functions
*/
/// @dev start roleManagerContract.
function startManager() public only(moderator) returns (bool) {
require(!started && custodianPool.length > 0);
started = true;
return true;
}
/// @dev addCustodian function.
/// @param custodianAddr custodian address to add.
function addCustodian(address custodianAddr)
public
only(moderator)
inUpdateWindow()
returns (bool success) {
require(!existingCustodians[custodianAddr] && !existingOtherContracts[custodianAddr]);
ICustodian custodian = ICustodian(custodianAddr);
require(custodian.totalUsers() >= 0);
// custodian.users(0);
uint custodianLength = custodianPool.length;
if (custodianLength > 0)
replaceModerator();
else if (!started) {
uint index = getNextAddrIndex(COLD_POOL_IDX, custodianAddr);
address oldModerator = moderator;
moderator = addrPool[COLD_POOL_IDX][index];
emit ReplaceModerator(oldModerator, moderator);
removeFromPool(COLD_POOL_IDX, index);
}
existingCustodians[custodianAddr] = true;
custodianPool.push(custodianAddr);
addrStatus[custodianAddr] = USED_STATUS;
emit AddCustodian(custodianAddr);
return true;
}
/// @dev addOtherContracts function.
/// @param contractAddr other contract address to add.
function addOtherContracts(address contractAddr)
public
only(moderator)
inUpdateWindow()
returns (bool success) {
require(!existingCustodians[contractAddr] && !existingOtherContracts[contractAddr]);
existingOtherContracts[contractAddr] = true;
otherContractPool.push(contractAddr);
addrStatus[contractAddr] = USED_STATUS;
replaceModerator();
emit AddOtherContract(contractAddr);
return true;
}
/// @dev add two addreess into pool function.
/// @param addr1 the first address
/// @param addr2 the second address.
/// @param poolIndex indicate adding to hot or cold.
function addAddress(address addr1, address addr2, uint poolIndex)
public
only(moderator)
inUpdateWindow()
returns (bool success) {
require(addrStatus[addr1] == NEW_STATUS
&& addrStatus[addr2] == NEW_STATUS
&& addr1 != addr2
&& poolIndex < 2);
replaceModerator();
addrPool[poolIndex].push(addr1);
addrStatus[addr1] = poolIndex + 1;
addrPool[poolIndex].push(addr2);
addrStatus[addr2] = poolIndex + 1;
emit AddAddress(poolIndex, addr1, addr2);
return true;
}
/// @dev removeAddress function.
/// @param addr the address to remove from
/// @param poolIndex the pool to remove from.
function removeAddress(address addr, uint poolIndex)
public
only(moderator)
inUpdateWindow()
returns (bool success) {
require(addrPool[poolIndex].length > MIN_POOL_SIZE
&& addrStatus[addr] == poolIndex + 1
&& poolIndex < 2);
removeFromPoolByAddr(poolIndex, addr);
replaceModerator();
emit RemoveAddress(poolIndex, addr);
return true;
}
/// @dev provide address to other contracts, such as custodian, oracle and others.
/// @param origin the origin who makes request
/// @param poolIndex the pool to request address from.
function provideAddress(address origin, uint poolIndex)
public
isValidRequestor(origin)
inUpdateWindow()
returns (address) {
require(addrPool[poolIndex].length > MIN_POOL_SIZE
&& poolIndex < 2
&& custodianPool.length > 0);
removeFromPoolByAddr(COLD_POOL_IDX, origin);
address requestor = msg.sender;
uint index = 0;
// is custodian
if (existingCustodians[requestor])
index = getNextAddrIndex(poolIndex, requestor);
else // is other contract;
index = getNextAddrIndex(poolIndex, custodianPool[custodianPool.length - 1]);
address addr = addrPool[poolIndex][index];
removeFromPool(poolIndex, index);
emit ProvideAddress(poolIndex, requestor, origin, addr);
return addr;
}
/*
* Internal functions
*/
function startVoting() internal {
address[] memory coldPool = addrPool[COLD_POOL_IDX];
for (uint i = 0; i < coldPool.length; i++)
voted[coldPool[i]] = false;
votedFor = 0;
votedAgainst = 0;
voteStartTimestamp = getNowTimestamp();
}
function replaceModerator() internal {
require(custodianPool.length > 0);
uint index = getNextAddrIndex(COLD_POOL_IDX, custodianPool[custodianPool.length - 1]);
address oldModerator = moderator;
moderator = addrPool[COLD_POOL_IDX][index];
emit ReplaceModerator(oldModerator, moderator);
removeFromPool(COLD_POOL_IDX, index);
}
/// @dev removeFromPool Function.
/// @param poolIndex the pool to request from removal.
/// @param addr the address to remove
function removeFromPoolByAddr(uint poolIndex, address addr) internal {
address[] memory subPool = addrPool[poolIndex];
for (uint i = 0; i < subPool.length; i++) {
if (subPool[i] == addr) {
removeFromPool(poolIndex, i);
break;
}
}
}
/// @dev removeFromPool Function.
/// @param poolIndex the pool to request from removal.
/// @param idx the index of address to remove
function removeFromPool(uint poolIndex, uint idx) internal {
address[] memory subPool = addrPool[poolIndex];
addrStatus[subPool[idx]] = USED_STATUS;
if (idx < subPool.length - 1)
addrPool[poolIndex][idx] = addrPool[poolIndex][subPool.length-1];
delete addrPool[poolIndex][subPool.length - 1];
// emit RemoveFromPool(poolIndex, addrPool[poolIndex][idx]);
addrPool[poolIndex].length--;
}
/// @dev getNextAddrIndex Function.
/// @param poolIndex the pool to request address from.
/// @param custodianAddr the index of custodian contract address for randomeness generation
function getNextAddrIndex(uint poolIndex, address custodianAddr) internal returns (uint) {
uint prevHashNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1))));
ICustodian custodian = ICustodian(custodianAddr);
uint userLength = custodian.totalUsers();
if(userLength > 255) {
address randomUserAddress = custodian.users(prevHashNumber % userLength);
return uint256(keccak256(abi.encodePacked(randomUserAddress))) % addrPool[poolIndex].length;
} else
return prevHashNumber % addrPool[poolIndex].length;
}
/// @dev get Ethereum blockchain current timestamp
function getNowTimestamp() internal view returns (uint) {
return now;
}
/// @dev get addressPool size
function getAddressPoolSizes() public view returns (uint, uint) {
return (addrPool[COLD_POOL_IDX].length, addrPool[HOT_POOL_IDX].length);
}
/// @dev get contract pool size
function getContractPoolSizes() public view returns (uint, uint) {
return (custodianPool.length, otherContractPool.length);
}
} | terminateVoting voting if timeout | function terminateByTimeout() public returns (bool) {
require(votingStage != VotingStage.NotStarted);
uint nowTimestamp = getNowTimestamp();
if (nowTimestamp > voteStartTimestamp && nowTimestamp - voteStartTimestamp > VOTE_TIME_OUT) {
votingStage = VotingStage.NotStarted;
emit TerminateByTimeOut(candidate);
return true;
} else
return false;
}
| 12,803,776 |
./full_match/5/0x25427ba3411054899A181b473e6a1584f9D23341/sources/project_/contracts/superfluid/Superfluid.sol | check if whitelisting required | function registerApp(
uint256 configWord
)
external override
{
if (APP_WHITE_LISTING_ENABLED) {
revert HOST_NO_APP_REGISTRATION_PERMISSIONS();
}
_registerApp(configWord, ISuperApp(msg.sender), true);
}
| 1,898,336 |
pragma solidity ^0.4.20;
contract Poker {
address public owner;
uint256 public minimumBet;
uint256 public totalBet;
uint256 public numberOfBets;
uint256 public maxAmountOfBets = 100;
address[] public players;
struct Player {
uint256 amountBet;
uint256 numberSelected;
}
// The address of the player and => the user info
mapping(address => Player) public playerInfo;
function() public payable {}
constructor(uint256 _minimumBet) public {
owner = msg.sender;
if(_minimumBet != 0 ) minimumBet = _minimumBet;
}
function kill() public {
if(msg.sender == owner) selfdestruct(owner);
}
function checkPlayerExists(address player) public constant returns(bool){
for(uint256 i = 0; i < players.length; i++){
if(players[i] == player) return true;
}
return false;
}
// To bet for a number between 1 and 10 both inclusive
function bet(uint256 numberSelected) public payable {
require(!checkPlayerExists(msg.sender));
require(numberSelected >= 1 && numberSelected <= 10);
require(msg.value >= minimumBet);
playerInfo[msg.sender].amountBet = msg.value;
playerInfo[msg.sender].numberSelected = numberSelected;
numberOfBets++;
players.push(msg.sender);
totalBet += msg.value;
}
// Generates a number between 1 and 10 that will be the winner
function generateNumberWinner() public {
uint256 numberGenerated = block.number % 10 + 1; // This isn't secure
distributePrizes(numberGenerated);
}
// Sends the corresponding ether to each winner depending on the total bets
function distributePrizes(uint256 numberWinner) public {
address[100] memory winners; // We have to create a temporary in memory array with fixed size
uint256 count = 0; // This is the count for the array of winners
for(uint256 i = 0; i < players.length; i++){
address playerAddress = players[i];
if(playerInfo[playerAddress].numberSelected == numberWinner){
winners[count] = playerAddress;
count++;
}
delete playerInfo[playerAddress]; // Delete all the players
}
players.length = 0; // Delete all the players array
uint256 winnerEtherAmount = totalBet / winners.length; // How much each winner gets
for(uint256 j = 0; j < count; j++){
if(winners[j] != address(0)) // Check that the address in this fixed array is not empty
winners[j].transfer(winnerEtherAmount);
}
}
} | Generates a number between 1 and 10 that will be the winner | function generateNumberWinner() public {
distributePrizes(numberGenerated);
}
| 5,472,472 |
pragma solidity ^0.5.12;
pragma experimental ABIEncoderV2;
/*-
* Copyright (c) 2019 @secondphonejune
* All rights reserved.
*
* This code is derived by @secondphonejune (Telegram ID)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* This project is originally created to implement an election for 2019 Hong Kong local elections.
* Ofcause the Hong Kong government is not going to use it, but we have a chance to show that how an election can be done completely anonymously with blockchain
* Everyone can use the code provided in this project, but they must keep this statement here unchanged.
* Fight for freedom, Stand with Hong Kong
* Five Demands, Not One Less
*/
/*
* Expected workflow, voter get his/her voter ID from contract, this makes sure no one has access to his/her personal data
* Second, the voter registers their voter ID and email (not phone as no money to do SMS) via a vote box and make a vote.
* Email is checked by the voter box to prevent double voting and robot voting, but there should be a better way to do it.
* Now registration will make old registration and votes from the same voter ID invalid
* The vote will then encrypted using a public key and submitted to this contract for record
* After the election, the private key will be made public and people can decrypt the votes and knows who wins
* Currently we let the vote box decides if a new vote should replace the old vote, but there should be a better way to do it
* Also if people can read the private variable voteListByVoter from blockchain, they will know who a person votes after election.
* The variable is needed for replacing old votes.
* This variable should be removed when there is a proper way to authenticate a person and replacing vote is not needed.
*/
contract electionList{
string public hashHead;
//This one keeps the council list for easy checking by public
string[] public councilList;
uint256 public councilNumber;
}
contract localElection{
address payable public owner;
string public encryptionPublicKey; //Just keep record on the vote encryption key
bool public isRunningElection = false;
//vote box exists only because most people do not own a crypto account.
//vote box are needed to encrypt and submit votes for people and do email validations
//Once the election is over, vote box also need to get votes from the contract and decrypt the votes
mapping(address => bool) public approvedVoteBox;
//This one is dummy list as the voter list is hidden from public
//Even in real case, this one only keeps the hash of the voter information, so no private data is leaked
//With the same name and HKID (voter), a person can only vote in one council
//The following information is created and verified by government before the election,
//but in this 2019 election even voter list is hidden from people.
//We setup register function for people to register just before they vote
mapping(uint256 => bool) public voterList;
mapping(uint256 => uint256) public usedPhoneNumber;
mapping(uint256 => mapping(string => bool)) public councilVoterList;
mapping(string => uint) public councilVoterNumber;
//This one keeps the votes, but arranged by voter so it is easy to check if someone has voted
//This file must be kept private as it links a person to a vote,
//people can find back who a person voted after the election
//If there is an electronic way for public to really verify a person to do the voting,
//there will be no need to setup replaceVote function.
//We can safely remove the link between vote and voter
mapping(uint256 => string) private voteListByVoter;
mapping(string => string[]) private votes; //Votes grouped by council
mapping(address => string[]) private voteByVotebox; //Votes grouped by votebox
mapping(string => bool) private voteDictionary; //Makre sure votes are unique
mapping(string => address) public invalidVotes;
address public dbAddress;
constructor(address electionDBaddr,string memory pKey) public{
owner = msg.sender;
dbAddress = electionDBaddr;
encryptionPublicKey = pKey;
}
function() external payable {
//Thank you for donation, it will be sent to the owner.
//The owner will send it to ζη« after deducting the cost (if they have ETH account)
if(address(this).balance >= msg.value && msg.value >0)
owner.transfer(msg.value);
}
//Just in case someone manage to give ETH to this contract
function withdrawAll() public payable{
if(address(this).balance >0) owner.transfer(address(this).balance);
}
function addVoteBox(address box) public {
if(msg.sender != owner) revert();
approvedVoteBox[box] = true;
}
function removeVoteBox(address box) public {
if(msg.sender != owner) revert();
approvedVoteBox[box] = false;
//Also remove all votes in that votebox from the election result
electionList db = electionList(dbAddress);
for(uint i=0;i<db.councilNumber();i++){
for(uint a=0;a<voteByVotebox[box].length;a++){
if(bytes(voteByVotebox[box][a]).length >0){
invalidVotes[voteByVotebox[box][a]] = msg.sender;
}
}
}
}
function getVoteboxVoteCount(address box) public view returns(uint256){
return voteByVotebox[box].length;
}
function getCouncilVoteCount(string memory council) public view returns(uint256){
return votes[council].length;
}
function startElection() public {
if(msg.sender != owner) revert();
isRunningElection = true;
}
function stopElection() public {
if(msg.sender != owner) revert();
isRunningElection = false;
}
//This function allows people to generate a voterID to register and vote.
//Supposingly this ID should be random so that people do not know who it belongs to,
//and each person has only one unique ID so they cannot double vote.
//It means a public key pair binding with identity / hash of identity.
//As most people do not have a wallet, we can only make sure each person has one ID only
function getVoterID(string memory name, string memory HKID)
public view returns(uint256){
electionList db = electionList(dbAddress);
if(!checkHKID(HKID)) return 0;
return uint256(sha256(joinStrToBytes(db.hashHead(),name,HKID)));
}
//function getphoneHash(uint number)
function getEmailHash(string memory email)
public view returns(uint256){
//return uint256(sha256(joinStrToBytes(hashHead,uint2str(number),"")));
electionList db = electionList(dbAddress);
return uint256(sha256(joinStrToBytes(db.hashHead(),email,"")));
}
//function register(uint256 voterID, uint256 hashedPhone, string memory council)
function register(uint256 voterID, uint256 hashedEmail, string memory council)
public returns(bool){
require(isRunningElection);
require(approvedVoteBox[msg.sender]);
//Register happens during election as we do not have the voter list
//require(now >= votingStartTime);
//require(now < votingEndTime);
if(voterList[voterID]) deregister(voterID);
//if(usedPhoneNumber[hashedPhone] > 0)
//deregister(usedPhoneNumber[hashedPhone]);
if(usedPhoneNumber[hashedEmail] > 0)
deregister(usedPhoneNumber[hashedEmail]);
voterList[voterID] = true;
//usedPhoneNumber[hashedPhone] = voterID;
usedPhoneNumber[hashedEmail] = voterID;
councilVoterList[voterID][council] = true;
councilVoterNumber[council]++;
return true;
}
function deregister(uint256 voterID)
internal returns(bool){
require(isRunningElection);
voterList[voterID] = false;
electionList db = electionList(dbAddress);
for(uint i=0;i<db.councilNumber();i++){
//deregister them from the other councils
if(councilVoterList[voterID][db.councilList(i)]){
councilVoterList[voterID][db.councilList(i)] = false;
councilVoterNumber[db.councilList(i)]--;
}
}
if(bytes(voteListByVoter[voterID]).length >0){
invalidVotes[voteListByVoter[voterID]] = msg.sender;
delete voteListByVoter[voterID];
}
return true;
}
//function isValidVoter(uint256 voterID, uint256 hashedPhone, string memory council)
function isValidVoter(uint256 voterID, uint256 hashedEmail, string memory council)
public view returns(bool){
if(!voterList[voterID]) return false;
//if(usedPhoneNumber[hashedPhone] == 0 || usedPhoneNumber[hashedPhone] != voterID)
if(usedPhoneNumber[hashedEmail] == 0 || usedPhoneNumber[hashedEmail] != voterID)
return false;
if(!councilVoterList[voterID][council]) return false;
return true;
}
function isVoted(uint256 voterID) public view returns(bool){
if(bytes(voteListByVoter[voterID]).length >0) return true;
return false;
}
//function submitVote(uint256 voterID, uint256 hashedPhone,
function submitVote(uint256 voterID, uint256 hashedEmail,
string memory council, string memory singleVote) public returns(bool){
require(isRunningElection);
require(approvedVoteBox[msg.sender]);
//require(now >= votingStartTime);
//require(now < votingEndTime);
//require(isValidVoter(voterID,hashedPhone,council));
require(isValidVoter(voterID,hashedEmail,council));
require(!isVoted(voterID)); //Voted already
require(!voteDictionary[singleVote]);
voteListByVoter[voterID] = singleVote;
votes[council].push(singleVote);
voteByVotebox[msg.sender].push(singleVote);
voteDictionary[singleVote] = true;
return true;
}
//function replaceVote(uint256 voterID, uint256 hashedPhone,
/*function replaceVote(uint256 voterID, uint256 hashedEmail,
string memory council, string memory singleVote) public returns(bool){
require(isRunningElection);
require(approvedVoteBox[msg.sender]);
//require(now >= votingStartTime);
//require(now < votingEndTime);
//require(isValidVoter(voterID,hashedPhone,council));
require(isValidVoter(voterID,hashedEmail,council));
require(!voteDictionary[singleVote]);
if(bytes(voteListByVoter[voterID]).length >0){
electionList db = electionList(dbAddress);
for(uint i=0;i<db.councilNumber();i++){
//reduce the vote count in the previous council
if(councilVoterList[voterID][db.councilList(i)]){
councilVoteCount[db.councilList(i)]--;
}
}
invalidVotes[voteListByVoter[voterID]] = msg.sender;
delete voteListByVoter[voterID];
}
voteListByVoter[voterID] = singleVote;
votes[council].push(singleVote);
councilVoteCount[council]++;
voteDictionary[singleVote] = true;
return true;
}*/
function registerAndVote(uint256 voterID, uint256 hashedEmail,
string memory council, string memory singleVote) public returns(bool){
if(register(voterID,hashedEmail,council)
&& submitVote(voterID,hashedEmail,council,singleVote))
return true;
return false;
}
function getResult(string memory council) public view returns(uint, uint, uint, uint,
string[] memory, string[] memory){
require(!isRunningElection);
//require(now >= votingEndTime);
uint totalVoteCount = votes[council].length;
uint validVoteCount;
//uint invalidCount;
for(uint i=0;i<totalVoteCount;i++){
string memory singleVote = votes[council][i];
if(invalidVotes[singleVote] == address(0)){
validVoteCount++;
}
//else invalidCount++;
}
//assert((validVoteCount+invalidCount) == totalVoteCount);
string[] memory validVoteIndex = new string[](validVoteCount);
string[] memory invalidVoteIndex = new string[](totalVoteCount-validVoteCount);
uint a=0;
for(uint i=0;i<totalVoteCount && (a<validVoteCount || validVoteCount==0);i++){
string memory singleVote = votes[council][i];
if(invalidVotes[singleVote] == address(0)){
validVoteIndex[a++] = singleVote;
}else{
invalidVoteIndex[i-a] = singleVote;
}
}
return (councilVoterNumber[council],totalVoteCount,validVoteCount,
totalVoteCount-validVoteCount,validVoteIndex,invalidVoteIndex);
}
function joinStrToBytes(string memory _a, string memory _b, string memory _c)
internal pure returns (bytes memory){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory ab = new string(_ba.length + _bb.length + _bc.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) bab[k++] = _bc[i];
//return string(bab);
return bab;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
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(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
//Sample G123456A AB9876543, C1234569 invalid sample AY987654A C668668E
function checkHKID(string memory HKID)
internal pure returns(bool){
bytes memory b = bytes(HKID);
if(b.length !=8 && b.length !=9) return false;
uint256 checkDigit = 0;
uint256 power = 9;
if(b.length ==8){
checkDigit += (36*power);
power--;
}
for(uint i=0;i<b.length;i++){
uint digit = uint8(b[i]);
if(i>(b.length-8) && i<(b.length-1)){
//It should be a number
if(digit < 48 || digit > 57) return false;
}
if(digit >=48 && digit<=57) checkDigit += ((digit-48)*power); //Number
else if(digit >=65 && digit<=90) checkDigit += ((digit-55)*power); //A-Z
else return false;
power--;
}
if(checkDigit % 11 == 0) return true;
return false;
}
} | This function allows people to generate a voterID to register and vote.Supposingly this ID should be random so that people do not know who it belongs to,and each person has only one unique ID so they cannot double vote.It means a public key pair binding with identity / hash of identity.As most people do not have a wallet, we can only make sure each person has one ID only | function getVoterID(string memory name, string memory HKID)
public view returns(uint256){
electionList db = electionList(dbAddress);
if(!checkHKID(HKID)) return 0;
return uint256(sha256(joinStrToBytes(db.hashHead(),name,HKID)));
}
| 7,293,098 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/finance/PaymentSplitter.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./SaleStatus.sol";
import "./Collection.sol";
/// @author no-op.eth (nft-lab.xyz)
/// @title Phto Exhibit - fine art photography (phto.io)
contract PhtoExhibit is ERC1155, ReentrancyGuard, Ownable, PaymentSplitter, IERC2981 {
/** Collections (drops) */
Collection[] private collections_;
/** Edition sizes */
uint256[] private editions_;
/** Name of collection */
string public constant name = "Phto.";
/** Symbol of collection */
string public constant symbol = "PHTO";
/** URI for the contract metadata */
string public contractURI;
/** Signer */
address public signer;
/** Mint pass utilization - collectionId -> address -> used */
mapping(uint256 => mapping(address => bool)) public passes;
/** For URI conversions */
using Strings for uint256;
/** Notify on sale state change */
event SaleStateChanged(SaleStatus val);
/** Notify on total supply change */
event TotalSupplyChanged(uint256 val);
/** Notify when a new collection is created */
event CollectionCreated(uint256 val);
constructor(
string memory _uri,
address[] memory shareholders,
uint256[] memory shares
) ERC1155(_uri) PaymentSplitter(shareholders, shares) {}
/// @notice Helper to return editions array
function editions() external view returns (uint256[] memory) {
return editions_;
}
/// @notice Helper to return collections array
function collections() external view returns (Collection[] memory) {
return collections_;
}
/// @notice Sets public sale state
/// @param _val The new value
function setSaleStatus(SaleStatus _val) external onlyOwner {
collections_[currentCollectionId()].status = _val;
emit SaleStateChanged(_val);
}
/// @notice Sets the authorized signer
/// @param _val New signer
function setSigner(address _val) external onlyOwner {
signer = _val;
}
/// @notice Sets the base metadata URI
/// @param _val The new URI
function setCollectionURI(string memory _val) external onlyOwner {
collections_[currentCollectionId()].uri = _val;
}
/// @notice Sets the contract metadata URI
/// @param _val The new URI
function setContractURI(string memory _val) external onlyOwner {
contractURI = _val;
}
/// @notice Returns the amount of tokens sold
/// @return supply The number of tokens sold
function totalSupply() public view returns (uint256 supply) {
for (uint256 i = 0; i < collections_.length; i++) {
supply += collections_[i].supply;
}
}
/// @notice Current collection ID getter
/// @return Currently active collection ID
function currentCollectionId() public view returns (uint256) {
require(collections_.length > 0, "No collections created.");
return collections_.length - 1;
}
/// @notice Current collection getter
/// @dev External usage to view current config
/// @return Collection
function currentCollection() external view returns (Collection memory) {
return collections_[currentCollectionId()];
}
/// @notice Notify other contracts of supported interfaces
/// @param interfaceId Magic bits
/// @return Yes/no
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, IERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/// @notice Returns the URI for a given token ID
/// @param _id The ID to return URI for
/// @return Token URI
function uri(uint256 _id) public view override returns (string memory) {
(uint256 _collection, uint256 _identifier) = unshift(_id);
return string(abi.encodePacked(collections_[_collection - 1].uri, _identifier.toString()));
}
/// @notice Get the royalty info for a given ID
/// @param _tokenId NFT ID to check
/// @param _salePrice Price sold for
/// @return receiver The address receiving the royalty
/// @return royaltyAmount The royalty amount to be received
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view override returns (address receiver, uint256 royaltyAmount) {
(uint256 collection,) = unshift(_tokenId);
Collection memory _coll = collections_[collection];
receiver = _coll.royaltyReceiver;
royaltyAmount = _coll.royaltyPercentage / 100 * _salePrice;
}
/// @notice Verify a signed message
/// @param _ids IDs from api
/// @param _amount amount from api
/// @param _sig API signature
function isValidData(address _receiver, uint256[] memory _ids, uint256 _amount, bytes memory _sig) public view returns(bool) {
bytes32 _message = keccak256(abi.encodePacked(_receiver, _ids, _amount));
return (recoverSigner(_message, _sig) == signer);
}
/// @notice Attempts to recover signer address
/// @param _message Data
/// @param _sig API signature
/// @return address Signer address
function recoverSigner(bytes32 _message, bytes memory _sig) public pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(_sig);
return ecrecover(_message, v, r, s);
}
/// @notice Attempts to split sig to VRS
/// @param _sig API signature
function splitSignature(bytes memory _sig) public pure returns (uint8, bytes32, bytes32) {
require(_sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
return (v, r, s);
}
/// @notice Pack collection ID and NFT ID into an int
/// @param _coll Collection ID
/// @param _id NFT ID
/// @return Packed ID
function shift(uint256 _coll, uint256 _id) public pure returns (uint256) {
return (_coll << 128) | _id;
}
/// @notice Unpack collection ID and NFT ID from an int
/// @param _id Packed ID
/// @return collection Collection ID
/// @return identifier NFT ID
function unshift(uint256 _id) public pure returns (uint256 collection, uint256 identifier) {
collection = _id >> 128;
identifier = _id & ~uint128(0);
}
/// @notice Creates a new collection
/// @param _maxTx Maximum mintable per tx
/// @param _maxSupply Maximum tokens in collection
/// @param _royaltyPercentage Percentage to be given from secondaries
/// @param _cost Cost per token
/// @param _royaltyReceiver Receiving address of royalties
/// @param _uri Base URI
function createCollection(
uint128 _maxTx,
uint128 _maxSupply,
uint128 _royaltyPercentage,
uint256 _cost,
address _royaltyReceiver,
string memory _uri,
uint256[] calldata _sizes
) external onlyOwner {
editions_ = _sizes;
collections_.push(
Collection(_maxTx, _maxSupply, _royaltyPercentage, 0, _cost, _royaltyReceiver, _uri, SaleStatus.Inactive)
);
emit CollectionCreated(currentCollectionId());
}
/// @notice Reserves NFTs for team/giveaways/etc
/// @param _ids Potential IDs to be minted
/// @param _amount Amount to be minted
function reserve(uint256[] memory _ids, uint256 _amount) external onlyOwner {
uint256 _collId = currentCollectionId();
Collection storage _coll = collections_[_collId];
_coll.supply += uint128(_amount);
mintHelper(_collId, _ids, _amount);
emit TotalSupplyChanged(_coll.supply);
}
/// @notice Internal mint helper
/// @param _ids Potential IDs to be minted
/// @param _amount Amount to be minted
/// @dev Called by mint/preMint
function mintHelper(uint256 _collId, uint256[] memory _ids, uint256 _amount) private {
uint256 _counter = 0;
for (uint256 i = 0; i < _ids.length; i++) {
if (editions_[_ids[i]] == 0) { continue; }
editions_[_ids[i]]--;
_counter++;
_mint(msg.sender, shift(_collId + 1, _ids[i]), 1, "0x0000");
if (_amount == _counter) { break; }
if (_ids.length - 1 == i) { i = 0; }
}
require(_amount == _counter, "Ran out of IDs. Please retry.");
}
/// @notice Mints a new token in private (pre) sale
/// @param _ids Potential IDs to be minted
/// @param _amount Amount to be minted
/// @param _sig Authorized wallet signature
/// @dev No charge
function preMint(uint256[] calldata _ids, uint256 _amount, bytes memory _sig) external payable nonReentrant {
uint256 _collId = currentCollectionId();
Collection storage _coll = collections_[_collId];
require(_coll.status == SaleStatus.Presale, "Presale is not yet active.");
require(isValidData(msg.sender, _ids, _amount, _sig), "Invalid signature");
require(passes[_collId][msg.sender] == false, "Already redeemed.");
passes[_collId][msg.sender] = true;
_coll.supply += uint128(_amount);
mintHelper(_collId, _ids, _amount);
emit TotalSupplyChanged(_coll.supply);
}
/// @notice Mints a new token in public sale
/// @param _ids Potential IDs to be minted
/// @param _amount Amount to be minted
/// @param _sig Authorized wallet signature
/// @dev Must send COST * amt in ETH
function mint(uint256[] calldata _ids, uint256 _amount, bytes memory _sig) external payable nonReentrant {
uint256 _collId = currentCollectionId();
Collection storage _coll = collections_[_collId];
uint256 _currentSupply = _coll.supply;
require(isValidData(msg.sender, _ids, _amount, _sig), "Invalid signature");
require(_coll.status == SaleStatus.Public, "Sale is not yet active.");
require(_coll.cost * _amount == msg.value, "ETH sent is not correct");
require(_currentSupply + _amount <= _coll.maxSupply, "Amount exceeds supply.");
_coll.supply += uint128(_amount);
mintHelper(_collId, _ids, _amount);
emit TotalSupplyChanged(_coll.supply);
}
/// @notice Burns a token
/// @param _account Current token holder
/// @param _id ID to burn
/// @param _value Amount of ID to burn
function burn(
address _account,
uint256 _id,
uint256 _value
) external nonReentrant {
require(_account == _msgSender() || isApprovedForAll(_account, _msgSender()), "ERC1155: caller is not owner nor approved");
(uint256 _collId,) = unshift(_id);
Collection storage _coll = collections_[_collId - 1];
_coll.supply -= uint128(_value);
_burn(_account, _id, _value);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "./SaleStatus.sol";
/** 1 Phto. Collection */
struct Collection {
/** Maximum mintable per tx */
uint128 maxTx;
/** Maximum tokens in collection */
uint128 maxSupply;
/** Percentage to be given from secondaries */
uint128 royaltyPercentage;
/** Current token supply */
uint128 supply;
/** Cost per token */
uint256 cost;
/** Receiving address of royalties */
address royaltyReceiver;
/** Base URI */
string uri;
/** Sale state */
SaleStatus status;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
/** Status of a given sale */
enum SaleStatus {
Inactive,
Presale,
Public,
Completed
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// 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: 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 (finance/PaymentSplitter.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/utils/SafeERC20.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
* contract.
*/
function release(IERC20 token, address account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20Released[token][account] += payment;
_erc20TotalReleased[token] += payment;
SafeERC20.safeTransfer(token, account, payment);
emit ERC20PaymentReleased(token, account, payment);
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// 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/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @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 {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @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(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 {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
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, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// 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/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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
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
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
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.
*
* NOTE: 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.
*
* NOTE: 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
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
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
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// 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 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
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);
} | Current collection getter External usage to view current config return Collection | function currentCollection() external view returns (Collection memory) {
return collections_[currentCollectionId()];
}
| 10,228,914 |
pragma solidity ^0.5.17;
library Math {
function MAX540(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN509(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE579(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
library SafeMath {
function ADD537(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB533(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB533(a, b, "SafeMath: subtraction overflow");
}
function SUB533(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 MUL899(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 DIV732(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV732(a, b, "SafeMath: division by zero");
}
function DIV732(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 MOD804(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD804(a, b, "SafeMath: modulo by zero");
}
function MOD804(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
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 _MSGSENDER75() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA657() 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
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED138(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER75();
emit OWNERSHIPTRANSFERRED138(address(0), _owner);
}
function OWNER313() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER471() { //inject NONSTANDARD NAMING
require(ISOWNER999(), "Ownable: caller is not the owner");
_;
}
function ISOWNER999() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER75() == _owner;
}
function RENOUNCEOWNERSHIP459() public ONLYOWNER471 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED138(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP87(address newOwner) public ONLYOWNER471 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP967(newOwner);
}
function _TRANSFEROWNERSHIP967(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED138(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
interface IERC20 {
function MINT669(address account, uint amount) external; //inject NONSTANDARD NAMING
function TOTALSUPPLY186() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF689(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER213(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE163(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE444(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM175(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER653(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL189(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
library Address {
function ISCONTRACT844(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 TOPAYABLE974(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE557(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.0;
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER881(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.TRANSFER213.selector, to, value));
}
function SAFETRANSFERFROM203(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.TRANSFERFROM175.selector, from, to, value));
}
function SAFEAPPROVE790(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.ALLOWANCE163(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.APPROVE444.selector, spender, value));
}
function SAFEINCREASEALLOWANCE320(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE163(address(this), spender).ADD537(value);
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.APPROVE444.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE576(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE163(address(this), spender).SUB533(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN468(token, abi.encodeWithSelector(token.APPROVE444.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN468(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).ISCONTRACT844(), "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/IRewardDistributionRecipient.sol
pragma solidity ^0.5.0;
contract IRewardDistributionRecipient is Ownable {
address rewardDistribution = 0x45a6b8BdfC1FAa745720165e0B172A3D6D4EC897;
function NOTIFYREWARDAMOUNT985() external; //inject NONSTANDARD NAMING
modifier ONLYREWARDDISTRIBUTION252() { //inject NONSTANDARD NAMING
require(_MSGSENDER75() == rewardDistribution, "Caller is not reward distribution");
_;
}
function SETREWARDDISTRIBUTION691(address _rewardDistribution) //inject NONSTANDARD NAMING
external
ONLYOWNER471
{
rewardDistribution = _rewardDistribution;
}
}
// File: contracts/CurveRewards.sol
pragma solidity ^0.5.0;
pragma solidity ^0.5.17;
contract LPTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public vamp_lp = IERC20(0x7dd8f4ABF60b58CE989DB66aB1af1d11E893429D); //vamp_lp mainnet
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function TOTALSUPPLY186() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF689(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function STAKE760(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.ADD537(amount);
_balances[msg.sender] = _balances[msg.sender].ADD537(amount);
vamp_lp.SAFETRANSFERFROM203(msg.sender, address(this), amount);
}
function WITHDRAW940(uint256 amount) public { //inject NONSTANDARD NAMING
_totalSupply = _totalSupply.SUB533(amount);
_balances[msg.sender] = _balances[msg.sender].SUB533(amount);
vamp_lp.SAFETRANSFER881(msg.sender, amount);
}
}
contract VMANAVAMPPool is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public vamp = IERC20(0xb2C822a1b923E06Dbd193d2cFc7ad15388EA09DD); //vmana
uint256 public DURATION = 7 days;
uint256 public initreward = 801419450000000000000000;
uint256 public starttime = 1603573200; //1 hour after vmana ends
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event REWARDADDED399(uint256 reward); //inject NONSTANDARD NAMING
event STAKED507(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAWN5(address indexed user, uint256 amount); //inject NONSTANDARD NAMING
event REWARDPAID848(address indexed user, uint256 reward); //inject NONSTANDARD NAMING
modifier UPDATEREWARD996(address account) { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN216();
lastUpdateTime = LASTTIMEREWARDAPPLICABLE527();
if (account != address(0)) {
rewards[account] = EARNED802(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function LASTTIMEREWARDAPPLICABLE527() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN509(block.timestamp, periodFinish);
}
function REWARDPERTOKEN216() public view returns (uint256) { //inject NONSTANDARD NAMING
if (TOTALSUPPLY186() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.ADD537(
LASTTIMEREWARDAPPLICABLE527()
.SUB533(lastUpdateTime)
.MUL899(rewardRate)
.MUL899(1e18)
.DIV732(TOTALSUPPLY186())
);
}
function EARNED802(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return
BALANCEOF689(account)
.MUL899(REWARDPERTOKEN216().SUB533(userRewardPerTokenPaid[account]))
.DIV732(1e18)
.ADD537(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function STAKE760(uint256 amount) public UPDATEREWARD996(msg.sender) CHECKSTART317{ //inject NONSTANDARD NAMING
require(amount > 0, "Cannot stake 0");
super.STAKE760(amount);
emit STAKED507(msg.sender, amount);
}
function WITHDRAW940(uint256 amount) public UPDATEREWARD996(msg.sender) { //inject NONSTANDARD NAMING
require(amount > 0, "Cannot withdraw 0");
super.WITHDRAW940(amount);
emit WITHDRAWN5(msg.sender, amount);
}
function EXIT850() external { //inject NONSTANDARD NAMING
WITHDRAW940(BALANCEOF689(msg.sender));
GETREWARD327();
}
function GETREWARD327() public UPDATEREWARD996(msg.sender) { //inject NONSTANDARD NAMING
uint256 reward = EARNED802(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
vamp.SAFETRANSFER881(msg.sender, reward);
emit REWARDPAID848(msg.sender, reward);
}
}
function AFTEREND949() public ONLYREWARDDISTRIBUTION252 { //if any tokens left, transfer to contract owner for further distriubtion to community //inject NONSTANDARD NAMING
require(block.timestamp > periodFinish);
vamp.SAFETRANSFER881(msg.sender,vamp.BALANCEOF689(address(this)));
}
modifier CHECKSTART317(){ //inject NONSTANDARD NAMING
require(block.timestamp > starttime,"not start");
_;
}
function NOTIFYREWARDAMOUNT985() //inject NONSTANDARD NAMING
external
ONLYREWARDDISTRIBUTION252
UPDATEREWARD996(address(0))
{
if (block.timestamp >= periodFinish) {
rewardRate = initreward.DIV732(DURATION);
} else {
uint256 remaining = periodFinish.SUB533(block.timestamp);
uint256 leftover = remaining.MUL899(rewardRate);
rewardRate = initreward.ADD537(leftover).DIV732(DURATION);
}
//vamp.mint(address(this),initreward);
lastUpdateTime = block.timestamp;
periodFinish = starttime.ADD537(DURATION);
emit REWARDADDED399(initreward);
}
} | inject NONSTANDARD NAMING | function ADD537(uint256 a, uint256 b) internal pure returns (uint256) { | 6,417,035 |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../access/roles/AdministratorRole.sol";
import "../utils/Addresses.sol";
import "../utils/Channels.sol";
import "../utils/Strings.sol";
import "./IVASP.sol";
import "./IVaspManager.sol";
contract VASP is Initializable, Context, Ownable, AdministratorRole, IVASP, IVaspManager {
using Addresses for Addresses.AddressSet;
using Addresses for address;
using Channels for Channels.ChannelSet;
using Strings for string;
Channels.ChannelSet private _channels;
string private _email;
string private _handshakeKey;
Addresses.AddressSet private _identityClaims;
string private _name;
string private _postalAddressStreetName;
string private _postalAddressBuildingNumber;
string private _postalAddressAddressLine;
string private _postalAddressPostCode;
string private _postalAddressTown;
string private _postalAddressCountry;
string private _signingKey;
Addresses.AddressSet private _trustedPeers;
string private _website;
/*
* @dev Initializes new instance of a smart contract. Should be called after smart contract deployment.
*
* Can be called only once.
*
*
* @param owner Owner of the smart contract.
*
* Requirements:
* - Should not be the zero address.
*
*
* @param initialAdministrators Initial list of Administrators accounts.
*
* Requirements:
* - Should be a list of unique values.
* - Should not contain the zero address.
*
*/
function initialize(
address owner
)
public
initializer
{
Ownable.initialize(owner);
AdministratorRole.initialize(owner);
}
/*
* @dev Assigns the Administrator role to the specified account.
*
* Can be called only by the Owner.
*
*
* @param account An account to assign the Administrator role to.
*
* Requirements:
* - Should not be the zero address.
* - Should not has the Administrator role.
*
*/
function addAdministrator(
address account
)
public
onlyOwner
{
_addAdministrator(account);
}
/*
* @dev Adds the specified channel to the list of communication channels the VASP accepting for messages.
*
* Can be called only by an account with the Administrator role.
*
* @param channel Channel type to add to the channels list.
*
* Requirements:
* - Should not be presented in the channels list.
*
*/
function addChannel(
uint8 channel
)
external
onlyAdministrator
{
_addChannel(channel);
}
/*
* @dev Adds the specified address to the list of identity claims.
*
* Can be called only by an account with the Administrator role.
*
* @param identityClaim Address of the identity claim to add to the identity claims list.
*
* Requirements:
* - Should not be the zero address.
* - Should not be presented in the identity claims list.
*
*/
function addIdentityClaim(
address identityClaim
)
external
onlyAdministrator
{
_addIdentityClaim(identityClaim);
}
/*
* @dev Adds the specified address to the list of trusted peers.
*
* Can be called only by an account with the Administrator role.
*
* @param trustedPeer Address of the trusted peer to add to the trusted peers list.
*
* Requirements:
* - Should not be the zero address.
* - Should not be presented in the trusted peers list.
*
*/
function addTrustedPeer(
address trustedPeer
)
external
onlyAdministrator
{
_addTrustedPeer(trustedPeer);
}
/*
* @dev Revokes the Administrator role from the specified account.
*
* Can be called only by the Owner.
*
*
* @param account An account to revoke the Administrator role from.
*
* Requirements:
* - Should not be the zero address.
* - Should not has the Administrator role.
*
*/
function removeAdministrator(
address account
)
public
onlyOwner
{
_removeAdministrator(account);
}
/*
* @dev Removes the specified channel from the list of communication channels the VASP accepting for messages.
*
* Can be called only by an account with the Administrator role.
*
* @param channel Channel type to remove from the channels list.
*
* Requirements:
* - Should be presented in the channels list.
*
*/
function removeChannel(
uint8 channel
)
external
onlyAdministrator
{
_removeChannel(channel);
}
/*
* @dev Removes the specified address from the list of identity claims.
*
* Can be called only by an account with the Administrator role.
*
* @param identityClaim Address of the identity claim to remove from the identity claims list.
*
* Requirements:
* - Should not be the zero address.
* - Should be presented in the identity claims list.
*
*/
function removeIdentityClaim(
address identityClaim
)
external
onlyAdministrator
{
_removeIdentityClaim(identityClaim);
}
/*
* @dev Removes the specified address from the list of trusted peers.
*
* Can be called only by an account with the Administrator role.
*
* @param trustedPeer Address of the trusted peer to remove from the trusted peers list.
*
* Requirements:
* - Should not be the zero address.
* - Should be presented in the trusted peers list.
*
*/
function removeTrustedPeer(
address trustedPeer
)
external
onlyAdministrator
{
_removeTrustedPeer(trustedPeer);
}
/*
* @dev Sets the e-mail address of the VASP.
*
*
* @param email New e-mail address value
*
* Requirements:
* - Should not be an empty string.
* - Should not be equal to the current e-mail.
*
*/
function setEmail(
string calldata email
)
external
onlyAdministrator
{
_setEmail(email);
}
/*
* @dev Sets the handshake key.
*
*
* @param handshakeKey New handshake key value
*
* Requirements:
* - Should not be an empty string.
* - Should not be equal to the current handshake key.
*
*/
function setHandshakeKey(
string calldata handshakeKey
)
external
onlyAdministrator
{
_setHandshakeKey(handshakeKey);
}
/*
* @dev Sets the VASP legal name.
*
*
* @param name New name value
*
* Requirements:
* - Should not be an empty string.
* - Should not be equal to the current name.
*
*/
function setName(
string calldata name
)
external
onlyAdministrator
{
_setName(name);
}
/*
* @dev Sets the VASP postal address.
*/
function setPostalAddress(
string calldata streetName,
string calldata buildingNumber,
string calldata postCode,
string calldata town,
string calldata country
)
external
onlyAdministrator
{
require(!streetName.isEmpty(), "VASP: street name is not specified");
require(!buildingNumber.isEmpty(), "VASP: building number is not specified");
_setPostalAddress(streetName, buildingNumber, /* addressLine */ "", postCode, town, country);
}
/*
* @dev Sets the VASP postal address.
*/
function setPostalAddressLine(
string calldata addressLine,
string calldata postCode,
string calldata town,
string calldata country
)
external
onlyAdministrator
{
require(!addressLine.isEmpty(), "VASP: address line is not specified");
_setPostalAddress(/* streetName */ "", /* buildingNumber */ "", addressLine, postCode, town, country);
}
/*
* @dev Sets the signing key.
*
*
* @param signingKey New signing key value
*
* Requirements:
* - Should not be an empty string.
* - Should not be equal to the current signing key.
*
*/
function setSigningKey(
string calldata signingKey
)
external
onlyAdministrator
{
_setSigningKey(signingKey);
}
/**
* @dev Sets the url of the website of the VASP.
*
*
* @param website New website url
*
* Requirements:
* - Should not be an empty string.
* - Should not be equal to the current website url.
*
*/
function setWebsite(
string calldata website
)
external
onlyAdministrator
{
_setWebsite(website);
}
/**
* @dev See {IVASP-channels}.
*/
function channels(
uint256 skip,
uint256 take
)
external view
returns (uint8[] memory)
{
return _channels.toArray(skip, take);
}
/**
* @dev See {IVASP-channelsCount}.
*/
function channelsCount()
external view
returns (uint256)
{
return _channels.count();
}
/**
* @dev See {IVASP-code}.
*/
function code()
external view
returns (bytes4)
{
bytes memory addressBytes = abi.encodePacked(address(this));
bytes4 result;
bytes4 x = bytes4(0xff000000);
result ^= (x & addressBytes[16]) >> 0;
result ^= (x & addressBytes[17]) >> 8;
result ^= (x & addressBytes[18]) >> 16;
result ^= (x & addressBytes[19]) >> 24;
return result;
}
/**
* @dev See {IVASP-email}.
*/
function email()
external view
returns (string memory)
{
return _email;
}
/**
* @dev See {IVASP-handshakeKey}.
*/
function handshakeKey()
external view
returns (string memory)
{
return _handshakeKey;
}
/**
* @dev See {IVASP-identityClaims}.
*/
function identityClaims(
uint256 skip,
uint256 take
)
external view
returns (address[] memory)
{
return _identityClaims.toArray(skip, take);
}
/**
* @dev See {IVASP-identityClaimsCount}.
*/
function identityClaimsCount()
external view
returns (uint256)
{
return _identityClaims.count();
}
/**
* @dev See {IVASP-name}.
*/
function name()
external view
returns (string memory)
{
return _name;
}
/**
* @dev See {IVASP-postalAddress}.
*/
function postalAddress()
external view
returns (
string memory streetName,
string memory buildingNumber,
string memory addressLine,
string memory postCode,
string memory town,
string memory country
)
{
streetName = _postalAddressStreetName;
buildingNumber = _postalAddressBuildingNumber;
addressLine = _postalAddressAddressLine;
postCode = _postalAddressPostCode;
town = _postalAddressTown;
country = _postalAddressCountry;
}
/**
* @dev See {IVASP-signingKey}.
*/
function signingKey()
external view
returns (string memory)
{
return _signingKey;
}
/**
* @dev See {IVASP-trustedPeers}.
*/
function trustedPeers(
uint256 skip,
uint256 take
)
external view
returns (address[] memory)
{
return _trustedPeers.toArray(skip, take);
}
/**
* @dev See {IVASP-trustedPeersCount}.
*/
function trustedPeersCount()
external view
returns (uint256)
{
return _trustedPeers.count();
}
/**
* @dev See {IVASP-website}.
*/
function website()
external view
returns (string memory)
{
return _website;
}
function _addChannel(
uint8 channel
)
private
{
_channels.add(channel);
emit ChannelAdded(channel);
}
function _addIdentityClaim(
address identityClaim
)
private
{
require(!identityClaim.isZeroAddress(), "VASP: identity claim is the zero address");
_identityClaims.add(identityClaim);
emit IdentityClaimAdded(identityClaim);
}
function _addTrustedPeer(
address trustedPeer
)
private
{
require(!trustedPeer.isZeroAddress(), "VASP: trusted peer is the zero address");
_trustedPeers.add(trustedPeer);
emit TrustedPeerAdded(trustedPeer);
}
function _removeChannel(
uint8 channel
)
private
{
_channels.remove(channel);
emit ChannelRemoved(channel);
}
function _removeIdentityClaim(
address identityClaim
)
private
{
require(!identityClaim.isZeroAddress(), "VASP: identity claim is the zero address");
_identityClaims.remove(identityClaim);
emit IdentityClaimRemoved(identityClaim);
}
function _removeTrustedPeer(
address trustedPeer
)
private
{
require(!trustedPeer.isZeroAddress(), "VASP: trusted peer is the zero address");
_trustedPeers.remove(trustedPeer);
emit TrustedPeerRemoved(trustedPeer);
}
function _setEmail(
string memory newEmail
)
private
{
require(!newEmail.isEmpty(), "VASP: newEmail is an empty string");
require(!newEmail.equals(_email), "VASP: specified e-mail has already been set");
_email = newEmail;
emit EmailChanged(newEmail);
}
function _setHandshakeKey(
string memory newHandshakeKey
)
private
{
require(!newHandshakeKey.isEmpty(), "VASP: newHandshakeKey is an empty string");
require(!newHandshakeKey.equals(_handshakeKey), "VASP: specified handshake key has already been set");
_handshakeKey = newHandshakeKey;
emit HandshakeKeyChanged(newHandshakeKey);
}
function _setName(
string memory newName
)
private
{
require(!newName.isEmpty(), "VASP: newName is an empty string");
require(!newName.equals(_name), "VASP: specified name has already been set");
_name = newName;
emit NameChanged(newName);
}
function _setSigningKey(
string memory newSigningKey
)
private
{
require(!newSigningKey.isEmpty(), "VASP: newSigningKey is an empty string");
require(!newSigningKey.equals(_signingKey), "VASP: specified signing key has already been set");
_signingKey = newSigningKey;
emit SigningKeyChanged(newSigningKey);
}
function _setPostalAddress(
string memory streetName,
string memory buildingNumber,
string memory addressLine,
string memory postCode,
string memory town,
string memory country
)
private
{
require(!postCode.isEmpty(), "VASP: post code is not specified");
require(!town.isEmpty(), "VASP: town is not specified");
require(!country.isEmpty(), "VASP: country is not specified");
bool postalAddressChanged =
!streetName.equals(_postalAddressStreetName) ||
!buildingNumber.equals(_postalAddressBuildingNumber) ||
!addressLine.equals(_postalAddressAddressLine) ||
!postCode.equals(_postalAddressPostCode) ||
!town.equals(_postalAddressTown) ||
!country.equals(_postalAddressCountry);
require(postalAddressChanged, "VASP: specified postal address has already been set");
_postalAddressStreetName = streetName;
_postalAddressBuildingNumber = buildingNumber;
_postalAddressAddressLine = addressLine;
_postalAddressPostCode = postCode;
_postalAddressTown = town;
_postalAddressCountry = country;
emit PostalAddressChanged(streetName, buildingNumber, addressLine, postCode, town, country);
}
function _setWebsite(
string memory newWebsite
)
private
{
require(!newWebsite.isEmpty(), "VASP: newWebsite is an empty string");
require(!newWebsite.equals(_website), "VASP: specified website has already been set");
_website = newWebsite;
emit WebsiteChanged(newWebsite);
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
| Sets the VASP postal address./ | function setPostalAddress(
string calldata streetName,
string calldata buildingNumber,
string calldata postCode,
string calldata town,
string calldata country
)
external
onlyAdministrator
{
require(!streetName.isEmpty(), "VASP: street name is not specified");
require(!buildingNumber.isEmpty(), "VASP: building number is not specified");
_setPostalAddress(streetName, buildingNumber, /* addressLine */ "", postCode, town, country);
}
| 13,101,934 |
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
interface IERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
abstract contract IWETH {
function allowance(address, address) public virtual returns (uint256);
function balanceOf(address) public virtual returns (uint256);
function approve(address, uint256) public virtual;
function transfer(address, uint256) public virtual returns (bool);
function transferFrom(
address,
address,
uint256
) public virtual returns (bool);
function deposit() public payable virtual;
function withdraw(uint256) public virtual;
}
library Address {
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);
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
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);
}
}
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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 Edited so it always first approves 0 and then the value, because of non standard tokens
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_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)
);
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
library TokenUtils {
using SafeERC20 for IERC20;
address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function approveToken(
address _tokenAddr,
address _to,
uint256 _amount
) internal {
if (_tokenAddr == ETH_ADDR) return;
if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) {
IERC20(_tokenAddr).safeApprove(_to, _amount);
}
}
function pullTokensIfNeeded(
address _token,
address _from,
uint256 _amount
) internal returns (uint256) {
// handle max uint amount
if (_amount == type(uint256).max) {
uint256 userAllowance = IERC20(_token).allowance(_from, address(this));
uint256 balance = getBalance(_token, _from);
// pull max allowance amount if balance is bigger than allowance
_amount = (balance > userAllowance) ? userAllowance : balance;
}
if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) {
IERC20(_token).safeTransferFrom(_from, address(this), _amount);
}
return _amount;
}
function withdrawTokens(
address _token,
address _to,
uint256 _amount
) internal returns (uint256) {
if (_amount == type(uint256).max) {
_amount = getBalance(_token, address(this));
}
if (_to != address(0) && _to != address(this) && _amount != 0) {
if (_token != ETH_ADDR) {
IERC20(_token).safeTransfer(_to, _amount);
} else {
payable(_to).transfer(_amount);
}
}
return _amount;
}
function depositWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).deposit{value: _amount}();
}
function withdrawWeth(uint256 _amount) internal {
IWETH(WETH_ADDR).withdraw(_amount);
}
function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) {
if (_tokenAddr == ETH_ADDR) {
return _acc.balance;
} else {
return IERC20(_tokenAddr).balanceOf(_acc);
}
}
function getTokenDecimals(address _token) internal view returns (uint256) {
if (_token == ETH_ADDR) return 18;
return IERC20(_token).decimals();
}
}
abstract contract IDFSRegistry {
function getAddr(bytes32 _id) public view virtual returns (address);
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public virtual;
function startContractChange(bytes32 _id, address _newContractAddr) public virtual;
function approveContractChange(bytes32 _id) public virtual;
function cancelContractChange(bytes32 _id) public virtual;
function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual;
}
/// @title A stateful contract that holds and can change owner/admin
contract AdminVault {
address public owner;
address public admin;
constructor() {
owner = msg.sender;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function changeOwner(address _owner) public {
require(admin == msg.sender, "msg.sender not admin");
owner = _owner;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function changeAdmin(address _admin) public {
require(admin == msg.sender, "msg.sender not admin");
admin = _admin;
}
}
/// @title AdminAuth Handles owner/admin privileges over smart contracts
contract AdminAuth {
using SafeERC20 for IERC20;
AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD);
modifier onlyOwner() {
require(adminVault.owner() == msg.sender, "msg.sender not owner");
_;
}
modifier onlyAdmin() {
require(adminVault.admin() == msg.sender, "msg.sender not admin");
_;
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(_receiver).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_receiver, _amount);
}
}
/// @notice Destroy the contract
function kill() public onlyAdmin {
selfdestruct(payable(msg.sender));
}
}
contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(
address _contract,
address _caller,
string memory _logName,
bytes memory _data
) public {
emit LogEvent(_contract, _caller, _logName, _data);
}
}
/// @title Stores all the important DFS addresses and can be changed (timelock)
contract DFSRegistry is AdminAuth {
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists";
string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists";
string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process";
string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger";
string public constant ERR_CHANGE_NOT_READY = "Change not ready yet";
string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0";
string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change";
string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change";
struct Entry {
address contractAddr;
uint256 waitPeriod;
uint256 changeStartTime;
bool inContractChange;
bool inWaitPeriodChange;
bool exists;
}
mapping(bytes32 => Entry) public entries;
mapping(bytes32 => address) public previousAddresses;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingWaitTimes;
/// @notice Given an contract id returns the registered address
/// @dev Id is keccak256 of the contract name
/// @param _id Id of contract
function getAddr(bytes32 _id) public view returns (address) {
return entries[_id].contractAddr;
}
/// @notice Helper function to easily query if id is registered
/// @param _id Id of contract
function isRegistered(bytes32 _id) public view returns (bool) {
return entries[_id].exists;
}
/////////////////////////// OWNER ONLY FUNCTIONS ///////////////////////////
/// @notice Adds a new contract to the registry
/// @param _id Id of contract
/// @param _contractAddr Address of the contract
/// @param _waitPeriod Amount of time to wait before a contract address can be changed
function addNewContract(
bytes32 _id,
address _contractAddr,
uint256 _waitPeriod
) public onlyOwner {
require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS);
entries[_id] = Entry({
contractAddr: _contractAddr,
waitPeriod: _waitPeriod,
changeStartTime: 0,
inContractChange: false,
inWaitPeriodChange: false,
exists: true
});
// Remember tha address so we can revert back to old addr if needed
previousAddresses[_id] = _contractAddr;
logger.Log(
address(this),
msg.sender,
"AddNewContract",
abi.encode(_id, _contractAddr, _waitPeriod)
);
}
/// @notice Reverts to the previous address immediately
/// @dev In case the new version has a fault, a quick way to fallback to the old contract
/// @param _id Id of contract
function revertToPreviousAddress(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR);
address currentAddr = entries[_id].contractAddr;
entries[_id].contractAddr = previousAddresses[_id];
logger.Log(
address(this),
msg.sender,
"RevertToPreviousAddress",
abi.encode(_id, currentAddr, previousAddresses[_id])
);
}
/// @notice Starts an address change for an existing entry
/// @dev Can override a change that is currently in progress
/// @param _id Id of contract
/// @param _newContractAddr Address of the new contract
function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE);
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inContractChange = true;
pendingAddresses[_id] = _newContractAddr;
logger.Log(
address(this),
msg.sender,
"StartContractChange",
abi.encode(_id, entries[_id].contractAddr, _newContractAddr)
);
}
/// @notice Changes new contract address, correct time must have passed
/// @param _id Id of contract
function approveContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
address oldContractAddr = entries[_id].contractAddr;
entries[_id].contractAddr = pendingAddresses[_id];
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
pendingAddresses[_id] = address(0);
previousAddresses[_id] = oldContractAddr;
logger.Log(
address(this),
msg.sender,
"ApproveContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Cancel pending change
/// @param _id Id of contract
function cancelContractChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE);
address oldContractAddr = pendingAddresses[_id];
pendingAddresses[_id] = address(0);
entries[_id].inContractChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelContractChange",
abi.encode(_id, oldContractAddr, entries[_id].contractAddr)
);
}
/// @notice Starts the change for waitPeriod
/// @param _id Id of contract
/// @param _newWaitPeriod New wait time
function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE);
pendingWaitTimes[_id] = _newWaitPeriod;
entries[_id].changeStartTime = block.timestamp; // solhint-disable-line
entries[_id].inWaitPeriodChange = true;
logger.Log(
address(this),
msg.sender,
"StartWaitPeriodChange",
abi.encode(_id, _newWaitPeriod)
);
}
/// @notice Changes new wait period, correct time must have passed
/// @param _id Id of contract
function approveWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
require(
block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line
ERR_CHANGE_NOT_READY
);
uint256 oldWaitTime = entries[_id].waitPeriod;
entries[_id].waitPeriod = pendingWaitTimes[_id];
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
pendingWaitTimes[_id] = 0;
logger.Log(
address(this),
msg.sender,
"ApproveWaitPeriodChange",
abi.encode(_id, oldWaitTime, entries[_id].waitPeriod)
);
}
/// @notice Cancel wait period change
/// @param _id Id of contract
function cancelWaitPeriodChange(bytes32 _id) public onlyOwner {
require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT);
require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE);
uint256 oldWaitPeriod = pendingWaitTimes[_id];
pendingWaitTimes[_id] = 0;
entries[_id].inWaitPeriodChange = false;
entries[_id].changeStartTime = 0;
logger.Log(
address(this),
msg.sender,
"CancelWaitPeriodChange",
abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod)
);
}
}
/// @title Implements Action interface and common helpers for passing inputs
abstract contract ActionBase is AdminAuth {
address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C;
DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR);
DefisaverLogger public constant logger = DefisaverLogger(
0x5c55B921f590a89C1Ebe84dF170E655a82b62126
);
string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value";
string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value";
/// @dev Subscription params index range [128, 255]
uint8 public constant SUB_MIN_INDEX_VALUE = 128;
uint8 public constant SUB_MAX_INDEX_VALUE = 255;
/// @dev Return params index range [1, 127]
uint8 public constant RETURN_MIN_INDEX_VALUE = 1;
uint8 public constant RETURN_MAX_INDEX_VALUE = 127;
/// @dev If the input value should not be replaced
uint8 public constant NO_PARAM_MAPPING = 0;
/// @dev We need to parse Flash loan actions in a different way
enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION }
/// @notice Parses inputs and runs the implemented action through a proxy
/// @dev Is called by the TaskExecutor chaining actions together
/// @param _callData Array of input values each value encoded as bytes
/// @param _subData Array of subscribed vales, replaces input values if specified
/// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
/// @param _returnValues Returns values from actions before, which can be injected in inputs
/// @return Returns a bytes32 value through DSProxy, each actions implements what that value is
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual returns (bytes32);
/// @notice Parses inputs and runs the single implemented action through a proxy
/// @dev Used to save gas when executing a single action directly
function executeActionDirect(bytes[] memory _callData) public virtual payable;
/// @notice Returns the type of action we are implementing
function actionType() public pure virtual returns (uint8);
//////////////////////////// HELPER METHODS ////////////////////////////
/// @notice Given an uint256 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamUint(
uint _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (uint) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = uint(_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (uint));
}
}
return _param;
}
/// @notice Given an addr input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamAddr(
address _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (address) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (address));
}
}
return _param;
}
/// @notice Given an bytes32 input, injects return/sub values if specified
/// @param _param The original input value
/// @param _mapType Indicated the type of the input in paramMapping
/// @param _subData Array of subscription data we can replace the input value with
/// @param _returnValues Array of subscription data we can replace the input value with
function _parseParamABytes32(
bytes32 _param,
uint8 _mapType,
bytes[] memory _subData,
bytes32[] memory _returnValues
) internal pure returns (bytes32) {
if (isReplaceable(_mapType)) {
if (isReturnInjection(_mapType)) {
_param = (_returnValues[getReturnIndex(_mapType)]);
} else {
_param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32));
}
}
return _param;
}
/// @notice Checks if the paramMapping value indicated that we need to inject values
/// @param _type Indicated the type of the input
function isReplaceable(uint8 _type) internal pure returns (bool) {
return _type != NO_PARAM_MAPPING;
}
/// @notice Checks if the paramMapping value is in the return value range
/// @param _type Indicated the type of the input
function isReturnInjection(uint8 _type) internal pure returns (bool) {
return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in return array value
/// @param _type Indicated the type of the input
function getReturnIndex(uint8 _type) internal pure returns (uint8) {
require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE);
return (_type - RETURN_MIN_INDEX_VALUE);
}
/// @notice Transforms the paramMapping value to the index in sub array value
/// @param _type Indicated the type of the input
function getSubIndex(uint8 _type) internal pure returns (uint8) {
require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE);
return (_type - SUB_MIN_INDEX_VALUE);
}
}
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProviderV2 {
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
interface ILendingPoolV2 {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
**/
function withdraw(
address asset,
uint256 amount,
address to
) external;
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external;
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProviderV2);
function setPause(bool val) external;
function paused() external view returns (bool);
}
abstract contract IAaveProtocolDataProviderV2 {
struct TokenData {
string symbol;
address tokenAddress;
}
function getAllReservesTokens() external virtual view returns (TokenData[] memory);
function getAllATokens() external virtual view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external virtual
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external virtual
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external virtual
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external virtual
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
/// @title Utility functions and data used in AaveV2 actions
contract AaveHelper {
uint16 public constant AAVE_REFERRAL_CODE = 64;
uint256 public constant STABLE_ID = 1;
uint256 public constant VARIABLE_ID = 2;
bytes32 public constant DATA_PROVIDER_ID =
0x0100000000000000000000000000000000000000000000000000000000000000;
/// @notice Enable/Disable a token as collateral for the specified Aave market
function enableAsCollateral(
address _market,
address _tokenAddr,
bool _useAsCollateral
) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _useAsCollateral);
}
/// @notice Switches the borrowing rate mode (stable/variable) for the user
function switchRateMode(
address _market,
address _tokenAddr,
uint256 _rateMode
) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).swapBorrowRateMode(_tokenAddr, _rateMode);
}
/// @notice Fetch the data provider for the specified market
function getDataProvider(address _market) internal view returns (IAaveProtocolDataProviderV2) {
return
IAaveProtocolDataProviderV2(
ILendingPoolAddressesProviderV2(_market).getAddress(DATA_PROVIDER_ID)
);
}
/// @notice Returns the lending pool contract of the specified market
function getLendingPool(address _market) internal view returns (ILendingPoolV2) {
return ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool());
}
}
/// @title Payback a token a user borrowed from an Aave market
contract AavePayback is ActionBase, AaveHelper {
using TokenUtils for address;
/// @inheritdoc ActionBase
function executeAction(
bytes[] memory _callData,
bytes[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
(
address market,
address tokenAddr,
uint256 amount,
uint256 rateMode,
address from,
address onBehalf
) = parseInputs(_callData);
market = _parseParamAddr(market, _paramMapping[0], _subData, _returnValues);
tokenAddr = _parseParamAddr(tokenAddr, _paramMapping[1], _subData, _returnValues);
amount = _parseParamUint(amount, _paramMapping[2], _subData, _returnValues);
rateMode = _parseParamUint(rateMode, _paramMapping[3], _subData, _returnValues);
from = _parseParamAddr(from, _paramMapping[4], _subData, _returnValues);
onBehalf = _parseParamAddr(onBehalf, _paramMapping[5], _subData, _returnValues);
uint256 paybackAmount = _payback(market, tokenAddr, amount, rateMode, from, onBehalf);
return bytes32(paybackAmount);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable override {
(
address market,
address tokenAddr,
uint256 amount,
uint256 rateMode,
address from,
address onBehalf
) = parseInputs(_callData);
_payback(market, tokenAddr, amount, rateMode, from, onBehalf);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice User paybacks tokens to the Aave protocol
/// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens
/// @param _market Address provider for specific market
/// @param _tokenAddr The address of the token to be payed back
/// @param _amount Amount of tokens to be payed back
/// @param _rateMode Type of borrow debt [Stable: 1, Variable: 2]
/// @param _from Where are we pulling the payback tokens amount from
/// @param _onBehalf For what user we are paying back the debt, defaults to proxy
function _payback(
address _market,
address _tokenAddr,
uint256 _amount,
uint256 _rateMode,
address _from,
address _onBehalf
) internal returns (uint256) {
ILendingPoolV2 lendingPool = getLendingPool(_market);
// if the amount sent is type(uint256).max get whole proxy debt
if (_amount == type(uint256).max) {
_amount = getWholeDebt(_market, _tokenAddr, _rateMode);
}
// default to onBehalf of proxy
if (_onBehalf == address(0)) {
_onBehalf = address(this);
}
_tokenAddr.pullTokensIfNeeded(_from, _amount);
_tokenAddr.approveToken(address(lendingPool), _amount);
uint256 tokensBefore = _tokenAddr.getBalance(address(this));
lendingPool.repay(_tokenAddr, _amount, _rateMode, _onBehalf);
uint256 tokensAfter = _tokenAddr.getBalance(address(this));
// send back any leftover tokens that weren't used in the repay
_tokenAddr.withdrawTokens(_from, tokensAfter);
logger.Log(
address(this),
msg.sender,
"AavePayback",
abi.encode(_market, _tokenAddr, _amount, _rateMode, _from, _onBehalf)
);
return (tokensBefore - tokensAfter);
}
function parseInputs(bytes[] memory _callData)
internal
pure
returns (
address market,
address tokenAddr,
uint256 amount,
uint256 rateMode,
address from,
address onBehalf
)
{
market = abi.decode(_callData[0], (address));
tokenAddr = abi.decode(_callData[1], (address));
amount = abi.decode(_callData[2], (uint256));
rateMode = abi.decode(_callData[3], (uint256));
from = abi.decode(_callData[4], (address));
onBehalf = abi.decode(_callData[5], (address));
}
function getWholeDebt(address _market, address _tokenAddr, uint _borrowType) internal view returns (uint256) {
IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market);
(, uint256 borrowsStable, uint256 borrowsVariable, , , , , , ) =
dataProvider.getUserReserveData(_tokenAddr, address(this));
if (_borrowType == STABLE_ID) {
return borrowsStable;
} else if (_borrowType == VARIABLE_ID) {
return borrowsVariable;
}
}
} | Enable/Disable a token as collateral for the specified Aave market | function getAllReservesTokens() external virtual view returns (TokenData[] memory);
function getAllATokens() external virtual view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external virtual
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external virtual
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external virtual
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external virtual
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
) public {
address lendingPool = ILendingPoolAddressesProviderV2(_market).getLendingPool();
ILendingPoolV2(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _useAsCollateral);
}
| 11,949,248 |
// SPDX-License-Identifier: MIT
// File: contracts/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: contracts/IWhitelistable.sol
/**
* Author: Lambdalf the White
* Edit : Squeebo
*/
pragma solidity 0.8.10;
abstract contract IWhitelistable {
// Errors
error IWhitelistable_NOT_SET();
error IWhitelistable_CONSUMED();
error IWhitelistable_FORBIDDEN();
error IWhitelistable_NO_ALLOWANCE();
bytes32 private _root;
mapping( address => uint256 ) private _consumed;
modifier isWhitelisted( address account_, bytes32[] memory proof_, uint256 passMax_, uint256 qty_ ) {
if ( qty_ > passMax_ ) {
revert IWhitelistable_FORBIDDEN();
}
uint256 _allowed_ = _checkWhitelistAllowance( account_, proof_, passMax_ );
if ( _allowed_ < qty_ ) {
revert IWhitelistable_FORBIDDEN();
}
_;
}
/**
* @dev Sets the pass to protect the whitelist.
*/
function _setWhitelist( bytes32 root_ ) internal virtual {
_root = root_;
}
/**
* @dev Returns the amount that `account_` is allowed to access from the whitelist.
*
* Requirements:
*
* - `_root` must be set.
*
* See {IWhitelistable-_consumeWhitelist}.
*/
function _checkWhitelistAllowance( address account_, bytes32[] memory proof_, uint256 passMax_ ) internal view returns ( uint256 ) {
if ( _root == 0 ) {
revert IWhitelistable_NOT_SET();
}
if ( _consumed[ account_ ] >= passMax_ ) {
revert IWhitelistable_CONSUMED();
}
if ( ! _computeProof( account_, proof_ ) ) {
revert IWhitelistable_FORBIDDEN();
}
uint256 _res_;
unchecked {
_res_ = passMax_ - _consumed[ account_ ];
}
return _res_;
}
function _computeProof( address account_, bytes32[] memory proof_ ) private view returns ( bool ) {
bytes32 leaf = keccak256(abi.encodePacked(account_));
return MerkleProof.processProof( proof_, leaf ) == _root;
}
/**
* @dev Consumes `amount_` pass passes from `account_`.
*
* Note: Before calling this function, eligibility should be checked through {IWhitelistable-checkWhitelistAllowance}.
*/
function _consumeWhitelist( address account_, uint256 qty_ ) internal {
unchecked {
_consumed[ account_ ] += qty_;
}
}
}
// File: contracts/ITradable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping( address => OwnableDelegateProxy ) public proxies;
}
abstract contract ITradable {
// OpenSea proxy registry address
address[] internal _proxyRegistries;
function _setProxyRegistry( address proxyRegistryAddress_ ) internal {
_proxyRegistries.push( proxyRegistryAddress_ );
}
/**
* @dev Checks if `operator_` is the registered proxy for `tokenOwner_`.
*
* Note: Use this function to allow whitelisting of registered proxy.
*/
function _isRegisteredProxy( address tokenOwner_, address operator_ ) internal view returns ( bool ) {
for ( uint256 i; i < _proxyRegistries.length; i++ ) {
ProxyRegistry _proxyRegistry_ = ProxyRegistry( _proxyRegistries[ i ] );
if ( address( _proxyRegistry_.proxies( tokenOwner_ ) ) == operator_ ) {
return true;
}
}
return false;
}
}
// File: contracts/IPausable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
abstract contract IPausable {
// Errors
error IPausable_SALE_NOT_CLOSED();
error IPausable_SALE_NOT_OPEN();
error IPausable_PRESALE_NOT_OPEN();
// Enum to represent the sale state, defaults to ``CLOSED``.
enum SaleState { CLOSED, PRESALE, SALE }
// The current state of the contract
SaleState public saleState;
/**
* @dev Emitted when the sale state changes
*/
event SaleStateChanged( SaleState indexed previousState, SaleState indexed newState );
/**
* @dev Sale state can have one of 3 values, ``CLOSED``, ``PRESALE``, or ``SALE``.
*/
function _setSaleState( SaleState newState_ ) internal virtual {
SaleState _previousState_ = saleState;
saleState = newState_;
emit SaleStateChanged( _previousState_, newState_ );
}
/**
* @dev Throws if sale state is not ``CLOSED``.
*/
modifier saleClosed {
if ( saleState != SaleState.CLOSED ) {
revert IPausable_SALE_NOT_CLOSED();
}
_;
}
/**
* @dev Throws if sale state is not ``SALE``.
*/
modifier saleOpen {
if ( saleState != SaleState.SALE ) {
revert IPausable_SALE_NOT_OPEN();
}
_;
}
/**
* @dev Throws if sale state is not ``PRESALE``.
*/
modifier presaleOpen {
if ( saleState != SaleState.PRESALE ) {
revert IPausable_PRESALE_NOT_OPEN();
}
_;
}
}
// File: contracts/IOwnable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @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 IOwnable {
// Errors
error IOwnable_NOT_OWNER();
// The owner of the contract
address private _owner;
/**
* @dev Emitted when contract ownership changes.
*/
event OwnershipTransferred( address indexed previousOwner, address indexed newOwner );
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function _initIOwnable( address owner_ ) internal {
_owner = owner_;
}
/**
* @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() {
if ( owner() != msg.sender ) {
revert IOwnable_NOT_OWNER();
}
_;
}
/**
* @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 {
address _oldOwner_ = _owner;
_owner = newOwner_;
emit OwnershipTransferred( _oldOwner_, newOwner_ );
}
}
// File: contracts/IERC2981.sol
pragma solidity 0.8.10;
interface IERC2981 {
/**
* @dev ERC165 bytes to add to interface array - set in parent contract
* implementing this standard
*
* bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
* bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
* _registerInterface(_INTERFACE_ID_ERC2981);
*
* @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 _salePrice - 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 _salePrice
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount);
}
// File: contracts/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: contracts/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: contracts/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity 0.8.10;
/**
* @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: contracts/ERC2981Base.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
abstract contract ERC2981Base is IERC165, IERC2981 {
// Errors
error IERC2981_INVALID_ROYALTIES();
// Royalty rate is stored out of 10,000 instead of a percentage to allow for
// up to two digits below the unit such as 2.5% or 1.25%.
uint private constant ROYALTY_BASE = 10000;
// Represents the percentage of royalties on each sale on secondary markets.
// Set to 0 to have no royalties.
uint256 private _royaltyRate;
// Address of the recipient of the royalties.
address private _royaltyRecipient;
function _initERC2981Base( address royaltyRecipient_, uint256 royaltyRate_ ) internal {
_setRoyaltyInfo( royaltyRecipient_, royaltyRate_ );
}
/**
* @dev See {IERC2981-royaltyInfo}.
*
* Note: This function should be overriden to revert on a query for non existent token.
*/
function royaltyInfo( uint256, uint256 salePrice_ ) public view virtual override returns ( address, uint256 ) {
if ( salePrice_ == 0 || _royaltyRate == 0 ) {
return ( _royaltyRecipient, 0 );
}
uint256 _royaltyAmount_ = _royaltyRate * salePrice_ / ROYALTY_BASE;
return ( _royaltyRecipient, _royaltyAmount_ );
}
/**
* @dev Sets the royalty rate to `royaltyRate_` and the royalty recipient to `royaltyRecipient_`.
*
* Requirements:
*
* - `royaltyRate_` cannot be higher than `ROYALTY_BASE`;
*/
function _setRoyaltyInfo( address royaltyRecipient_, uint256 royaltyRate_ ) internal virtual {
if ( royaltyRate_ > ROYALTY_BASE ) {
revert IERC2981_INVALID_ROYALTIES();
}
_royaltyRate = royaltyRate_;
_royaltyRecipient = royaltyRecipient_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override returns ( bool ) {
return
interfaceId_ == type( IERC2981 ).interfaceId ||
interfaceId_ == type( IERC165 ).interfaceId;
}
}
// File: contracts/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: contracts/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: contracts/ERC721Batch.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
abstract contract ERC721Batch is Context, IERC721Metadata {
// Errors
error IERC721_APPROVE_OWNER();
error IERC721_APPROVE_CALLER();
error IERC721_CALLER_NOT_APPROVED();
error IERC721_NONEXISTANT_TOKEN();
error IERC721_NON_ERC721_RECEIVER();
error IERC721_NULL_ADDRESS_BALANCE();
error IERC721_NULL_ADDRESS_TRANSFER();
// Token name
string private _name;
// Token symbol
string private _symbol;
// Token Base URI
string private _baseURI;
// Token IDs
uint256 private _numTokens;
// List of owner addresses
mapping( uint256 => address ) private _owners;
// 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 Ensures the token exist.
* A token exists if it has been minted and is not owned by the null address.
*
* @param tokenId_ uint256 ID of the token to verify
*/
modifier exists( uint256 tokenId_ ) {
if ( ! _exists( tokenId_ ) ) {
revert IERC721_NONEXISTANT_TOKEN();
}
_;
}
// **************************************
// ***** INTERNAL *****
// **************************************
/**
* @dev Internal function returning the number of tokens in `tokenOwner_`'s account.
*/
function _balanceOf( address tokenOwner_ ) internal view virtual returns ( uint256 ) {
if ( tokenOwner_ == address( 0 ) ) {
return 0;
}
uint256 _supplyMinted_ = _supplyMinted();
uint256 _count_ = 0;
address _currentTokenOwner_;
for ( uint256 i; i < _supplyMinted_; i++ ) {
if ( _owners[ i ] != address( 0 ) ) {
_currentTokenOwner_ = _owners[ i ];
}
if ( tokenOwner_ == _currentTokenOwner_ ) {
_count_++;
}
}
return _count_;
}
/**
* @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_ ) internal virtual 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.
//
// IMPORTANT
// It is unsafe to assume that an address not flagged by this method
// is an externally-owned account (EOA) and not a contract.
//
// Among others, the following types of addresses will not be flagged:
//
// - 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
uint256 _size_;
assembly {
_size_ := extcodesize( to_ )
}
// If address is a contract, check that it is aware of how to handle ERC721 tokens
if ( _size_ > 0 ) {
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 IERC721_NON_ERC721_RECEIVER();
}
else {
assembly {
revert( add( 32, reason ), mload( reason ) )
}
}
}
}
else {
return true;
}
}
/**
* @dev Internal function returning whether a token exists.
* A token exists if it has been minted and is not owned by the null address.
*
* @param tokenId_ uint256 ID of the token to verify
*
* @return bool whether the token exists
*/
function _exists( uint256 tokenId_ ) internal view virtual returns ( bool ) {
return tokenId_ < _numTokens;
}
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function _initERC721BatchMetadata( string memory name_, string memory symbol_ ) internal {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Internal function returning whether `operator_` is allowed
* to manage tokens on behalf of `tokenOwner_`.
*
* @param tokenOwner_ address that owns tokens
* @param operator_ address that tries to manage tokens
*
* @return bool whether `operator_` is allowed to handle the token
*/
function _isApprovedForAll( address tokenOwner_, address operator_ ) internal view virtual returns ( bool ) {
return _operatorApprovals[ tokenOwner_ ][ operator_ ];
}
/**
* @dev Internal function returning whether `operator_` is allowed to handle `tokenId_`
*
* Note: To avoid multiple checks for the same data, it is assumed that existence of `tokeId_`
* has been verified prior via {_exists}
* If it hasn't been verified, this function might panic
*
* @param operator_ address that tries to handle the token
* @param tokenId_ uint256 ID of the token to be handled
*
* @return bool whether `operator_` is allowed to handle the token
*/
function _isApprovedOrOwner( address tokenOwner_, address operator_, uint256 tokenId_ ) internal view virtual returns ( bool ) {
bool _isApproved_ = operator_ == tokenOwner_ ||
operator_ == _tokenApprovals[ tokenId_ ] ||
_isApprovedForAll( tokenOwner_, operator_ );
return _isApproved_;
}
/**
* @dev Mints `qty_` tokens and transfers them to `to_`.
*
* This internal function can be used to perform token minting.
*
* Emits a {ConsecutiveTransfer} event.
*/
function _mint( address to_, uint256 qty_ ) internal virtual {
uint256 _firstToken_ = _numTokens;
uint256 _lastToken_ = _firstToken_ + qty_ - 1;
_owners[ _firstToken_ ] = to_;
if ( _lastToken_ > _firstToken_ ) {
_owners[ _lastToken_ ] = to_;
}
for ( uint256 i; i < qty_; i ++ ) {
emit Transfer( address( 0 ), to_, _firstToken_ + i );
}
_numTokens = _lastToken_ + 1;
}
/**
* @dev Internal function returning the owner of the `tokenId_` token.
*
* @param tokenId_ uint256 ID of the token to verify
*
* @return address the address of the token owner
*/
function _ownerOf( uint256 tokenId_ ) internal view virtual returns ( address ) {
uint256 _tokenId_ = tokenId_;
address _tokenOwner_ = _owners[ _tokenId_ ];
while ( _tokenOwner_ == address( 0 ) ) {
_tokenId_ --;
_tokenOwner_ = _owners[ _tokenId_ ];
}
return _tokenOwner_;
}
/**
* @dev Internal function used to set the base URI of the collection.
*/
function _setBaseURI( string memory baseURI_ ) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function returning the total number of tokens minted
*
* @return uint256 the number of tokens that have been minted so far
*/
function _supplyMinted() internal view virtual returns ( uint256 ) {
return _numTokens;
}
/**
* @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 Transfers `tokenId_` from `from_` to `to_`.
*
* This internal function can be used to implement alternative mechanisms to perform
* token transfer, such as signature-based, or token burning.
*
* Emits a {Transfer} event.
*/
function _transfer( address from_, address to_, uint256 tokenId_ ) internal virtual {
_tokenApprovals[ tokenId_ ] = address( 0 );
uint256 _previousId_ = tokenId_ > 0 ? tokenId_ - 1 : 0;
uint256 _nextId_ = tokenId_ + 1;
bool _previousShouldUpdate_ = _previousId_ < tokenId_ &&
_exists( _previousId_ ) &&
_owners[ _previousId_ ] == address( 0 );
bool _nextShouldUpdate_ = _exists( _nextId_ ) &&
_owners[ _nextId_ ] == address( 0 );
if ( _previousShouldUpdate_ ) {
_owners[ _previousId_ ] = from_;
}
if ( _nextShouldUpdate_ ) {
_owners[ _nextId_ ] = from_;
}
_owners[ tokenId_ ] = to_;
emit Transfer( from_, to_, tokenId_ );
}
// **************************************
// ***** PUBLIC *****
// **************************************
/**
* @dev See {IERC721-approve}.
*/
function approve( address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == _tokenOwner_ ) {
revert IERC721_APPROVE_OWNER();
}
_tokenApprovals[ tokenId_ ] = to_;
emit Approval( _tokenOwner_, to_, tokenId_ );
}
/**
* @dev See {IERC721-safeTransferFrom}.
*
* Note: We can ignore `from_` as we can compare everything to the actual token owner,
* but we cannot remove this parameter to stay in conformity with IERC721
*/
function safeTransferFrom( address, address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == address( 0 ) ) {
revert IERC721_NULL_ADDRESS_TRANSFER();
}
_transfer( _tokenOwner_, to_, tokenId_ );
if ( ! _checkOnERC721Received( _tokenOwner_, to_, tokenId_, "" ) ) {
revert IERC721_NON_ERC721_RECEIVER();
}
}
/**
* @dev See {IERC721-safeTransferFrom}.
*
* Note: We can ignore `from_` as we can compare everything to the actual token owner,
* but we cannot remove this parameter to stay in conformity with IERC721
*/
function safeTransferFrom( address, address to_, uint256 tokenId_, bytes calldata data_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == address( 0 ) ) {
revert IERC721_NULL_ADDRESS_TRANSFER();
}
_transfer( _tokenOwner_, to_, tokenId_ );
if ( ! _checkOnERC721Received( _tokenOwner_, to_, tokenId_, data_ ) ) {
revert IERC721_NON_ERC721_RECEIVER();
}
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll( address operator_, bool approved_ ) public virtual override {
address _account_ = _msgSender();
if ( operator_ == _account_ ) {
revert IERC721_APPROVE_CALLER();
}
_operatorApprovals[ _account_ ][ operator_ ] = approved_;
emit ApprovalForAll( _account_, operator_, approved_ );
}
/**
* @dev See {IERC721-transferFrom}.
*
* Note: We can ignore `from_` as we can compare everything to the actual token owner,
* but we cannot remove this parameter to stay in conformity with IERC721
*/
function transferFrom( address, address to_, uint256 tokenId_ ) external virtual exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
if ( to_ == address( 0 ) ) {
revert IERC721_NULL_ADDRESS_TRANSFER();
}
_transfer( _tokenOwner_, to_, tokenId_ );
}
// **************************************
// ***** VIEW *****
// **************************************
/**
* @dev Returns the number of tokens in `tokenOwner_`'s account.
*/
function balanceOf( address tokenOwner_ ) external view virtual returns ( uint256 ) {
return _balanceOf( tokenOwner_ );
}
/**
* @dev Returns the account approved for `tokenId_` token.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function getApproved( uint256 tokenId_ ) external view virtual exists( tokenId_ ) returns ( address ) {
return _tokenApprovals[ tokenId_ ];
}
/**
* @dev Returns if the `operator_` is allowed to manage all of the assets of `tokenOwner_`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll( address tokenOwner_, address operator_ ) external view virtual returns ( bool ) {
return _isApprovedForAll( tokenOwner_, operator_ );
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns ( string memory ) {
return _name;
}
/**
* @dev Returns the owner of the `tokenId_` token.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOf( uint256 tokenId_ ) external view virtual exists( tokenId_ ) returns ( address ) {
return _ownerOf( tokenId_ );
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override returns ( bool ) {
return
interfaceId_ == type( IERC721Metadata ).interfaceId ||
interfaceId_ == type( IERC721 ).interfaceId ||
interfaceId_ == type( IERC165 ).interfaceId;
}
/**
* @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 exists( tokenId_ ) returns ( string memory ) {
return bytes( _baseURI ).length > 0 ? string( abi.encodePacked( _baseURI, _toString( tokenId_ ) ) ) : _toString( tokenId_ );
}
}
// File: contracts/ERC721BatchStakable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension and the Enumerable extension.
*
* Note: This implementation is only compatible with a sequential order of tokens minted.
* If you need to mint tokens in a random order, you will need to override the following functions:
* Note also that this implementations is fairly inefficient and as such,
* those functions should be avoided inside non-view functions.
*/
abstract contract ERC721BatchStakable is ERC721Batch, IERC721Receiver {
// Mapping of tokenId to stakeholder address
mapping( uint256 => address ) internal _stakedOwners;
// **************************************
// ***** INTERNAL *****
// **************************************
/**
* @dev Internal function returning the number of tokens staked by `tokenOwner_`.
*/
function _balanceOfStaked( address tokenOwner_ ) internal view virtual returns ( uint256 ) {
if ( tokenOwner_ == address( 0 ) ) {
return 0;
}
uint256 _supplyMinted_ = _supplyMinted();
uint256 _count_ = 0;
for ( uint256 i; i < _supplyMinted_; i++ ) {
if ( _stakedOwners[ i ] == tokenOwner_ ) {
_count_++;
}
}
return _count_;
}
/**
* @dev Internal function that mints `qtyMinted_` tokens and stakes `qtyStaked_` of them to the count of `tokenOwner_`.
*/
function _mintAndStake( address tokenOwner_, uint256 qtyMinted_, uint256 qtyStaked_ ) internal {
uint256 _qtyNotStaked_;
uint256 _qtyStaked_ = qtyStaked_;
if ( qtyStaked_ > qtyMinted_ ) {
_qtyStaked_ = qtyMinted_;
}
else if ( qtyStaked_ < qtyMinted_ ) {
_qtyNotStaked_ = qtyMinted_ - qtyStaked_;
}
if ( _qtyStaked_ > 0 ) {
_mintInContract( tokenOwner_, _qtyStaked_ );
}
if ( _qtyNotStaked_ > 0 ) {
_mint( tokenOwner_, _qtyNotStaked_ );
}
}
/**
* @dev Internal function that mints `qtyStaked_` tokens and stakes them to the count of `tokenOwner_`.
*/
function _mintInContract( address tokenOwner_, uint256 qtyStaked_ ) internal {
uint256 _currentToken_ = _supplyMinted();
uint256 _lastToken_ = _currentToken_ + qtyStaked_ - 1;
while ( _currentToken_ <= _lastToken_ ) {
_stakedOwners[ _currentToken_ ] = tokenOwner_;
_currentToken_ ++;
}
_mint( address( this ), qtyStaked_ );
}
/**
* @dev Internal function returning the owner of the staked token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function _ownerOfStaked( uint256 tokenId_ ) internal view virtual returns ( address ) {
return _stakedOwners[ tokenId_ ];
}
/**
* @dev Internal function that stakes the token number `tokenId_` to the count of `tokenOwner_`.
*/
function _stake( address tokenOwner_, uint256 tokenId_ ) internal {
_stakedOwners[ tokenId_ ] = tokenOwner_;
_transfer( tokenOwner_, address( this ), tokenId_ );
}
/**
* @dev Internal function that unstakes the token `tokenId_` and transfers it back to `tokenOwner_`.
*/
function _unstake( address tokenOwner_, uint256 tokenId_ ) internal {
_transfer( address( this ), tokenOwner_, tokenId_ );
delete _stakedOwners[ tokenId_ ];
}
// **************************************
// **************************************
// ***** PUBLIC *****
// **************************************
/**
* @dev Stakes the token `tokenId_` to the count of its owner.
*
* Requirements:
*
* - Caller must be allowed to manage `tokenId_` or its owner's tokens.
* - `tokenId_` must exist.
*/
function stake( uint256 tokenId_ ) external exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOf( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
_stake( _tokenOwner_, tokenId_ );
}
/**
* @dev Unstakes the token `tokenId_` and returns it to its owner.
*
* Requirements:
*
* - Caller must be allowed to manage `tokenId_` or its owner's tokens.
* - `tokenId_` must exist.
*/
function unstake( uint256 tokenId_ ) external exists( tokenId_ ) {
address _operator_ = _msgSender();
address _tokenOwner_ = _ownerOfStaked( tokenId_ );
bool _isApproved_ = _isApprovedOrOwner( _tokenOwner_, _operator_, tokenId_ );
if ( ! _isApproved_ ) {
revert IERC721_CALLER_NOT_APPROVED();
}
_unstake( _tokenOwner_, tokenId_ );
}
// **************************************
// **************************************
// ***** VIEW *****
// **************************************
/**
* @dev Returns the number of tokens owned by `tokenOwner_`.
*/
function balanceOf( address tokenOwner_ ) public view virtual override returns ( uint256 balance ) {
return _balanceOfStaked( tokenOwner_ ) + _balanceOf( tokenOwner_ );
}
/**
* @dev Returns the number of tokens staked by `tokenOwner_`.
*/
function balanceOfStaked( address tokenOwner_ ) public view virtual returns ( uint256 ) {
return _balanceOfStaked( tokenOwner_ );
}
/**
* @dev Returns the owner of token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOf( uint256 tokenId_ ) public view virtual override exists( tokenId_ ) returns ( address ) {
address _tokenOwner_ = _ownerOf( tokenId_ );
if ( _tokenOwner_ == address( this ) ) {
return _ownerOfStaked( tokenId_ );
}
return _tokenOwner_;
}
/**
* @dev Returns the owner of staked token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOfStaked( uint256 tokenId_ ) public view virtual exists( tokenId_ ) returns ( address ) {
return _ownerOfStaked( tokenId_ );
}
// **************************************
// **************************************
// ***** PURE *****
// **************************************
/**
* @dev Signals that this contract knows how to handle ERC721 tokens.
*/
function onERC721Received( address, address, uint256, bytes memory ) public override pure returns ( bytes4 ) {
return type( IERC721Receiver ).interfaceId;
}
// **************************************
}
// File: contracts/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (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);
/**
* @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: contracts/ERC721BatchEnumerable.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension and the Enumerable extension.
*
* Note: This implementation is only compatible with a sequential order of tokens minted.
* If you need to mint tokens in a random order, you will need to override the following functions:
* Note also that this implementations is fairly inefficient and as such,
* those functions should be avoided inside non-view functions.
*/
abstract contract ERC721BatchEnumerable is ERC721Batch, IERC721Enumerable {
// Errors
error IERC721Enumerable_OWNER_INDEX_OUT_OF_BOUNDS();
error IERC721Enumerable_INDEX_OUT_OF_BOUNDS();
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override(IERC165, ERC721Batch) returns ( bool ) {
return
interfaceId_ == type( IERC721Enumerable ).interfaceId ||
super.supportsInterface( interfaceId_ );
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex( uint256 index_ ) public view virtual override returns ( uint256 ) {
if ( index_ >= _supplyMinted() ) {
revert IERC721Enumerable_INDEX_OUT_OF_BOUNDS();
}
return index_;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex( address tokenOwner_, uint256 index_ ) public view virtual override returns ( uint256 tokenId ) {
uint256 _supplyMinted_ = _supplyMinted();
if ( index_ >= _balanceOf( tokenOwner_ ) ) {
revert IERC721Enumerable_OWNER_INDEX_OUT_OF_BOUNDS();
}
uint256 _count_ = 0;
for ( uint256 i = 0; i < _supplyMinted_; i++ ) {
if ( _exists( i ) && tokenOwner_ == _ownerOf( i ) ) {
if ( index_ == _count_ ) {
return i;
}
_count_++;
}
}
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns ( uint256 ) {
uint256 _supplyMinted_ = _supplyMinted();
uint256 _count_ = 0;
for ( uint256 i; i < _supplyMinted_; i++ ) {
if ( _exists( i ) ) {
_count_++;
}
}
return _count_;
}
}
// File: contracts/CCFoundersKeys.sol
/**
* Author: Lambdalf the White
*/
pragma solidity 0.8.10;
contract CCFoundersKeys is ERC721BatchEnumerable, ERC721BatchStakable, ERC2981Base, IOwnable, IPausable, ITradable, IWhitelistable {
// Events
event PaymentReleased( address indexed from, address[] indexed tos, uint256[] indexed amounts );
// Errors
error CCFoundersKeys_ARRAY_LENGTH_MISMATCH();
error CCFoundersKeys_FORBIDDEN();
error CCFoundersKeys_INCORRECT_PRICE();
error CCFoundersKeys_INSUFFICIENT_KEY_BALANCE();
error CCFoundersKeys_MAX_BATCH();
error CCFoundersKeys_MAX_RESERVE();
error CCFoundersKeys_MAX_SUPPLY();
error CCFoundersKeys_NO_ETHER_BALANCE();
error CCFoundersKeys_TRANSFER_FAIL();
// Founders Key whitelist mint price
uint public immutable WL_MINT_PRICE; // = 0.069 ether;
// Founders Key public mint price
uint public immutable PUBLIC_MINT_PRICE; // = 0.1 ether;
// Max supply
uint public immutable MAX_SUPPLY;
// Max TX
uint public immutable MAX_BATCH;
// 2C Safe wallet ~ 90%
address private immutable _CC_SAFE;
// 2C Operations wallet ~ 5%
address private immutable _CC_CHARITY;
// 2C Founders wallet ~ 2.5%
address private immutable _CC_FOUNDERS;
// 2C Community wallet ~ 2.5%
address private immutable _CC_COMMUNITY;
// Mapping of Anon holders to amount of free key claimable
mapping( address => uint256 ) public anonClaimList;
uint256 private _reserve;
constructor(
uint256 reserve_,
uint256 maxBatch_,
uint256 maxSupply_,
uint256 royaltyRate_,
uint256 wlMintPrice_,
uint256 publicMintPrice_,
string memory name_,
string memory symbol_,
string memory baseURI_,
// address devAddress_,
address[] memory wallets_
) {
address _contractOwner_ = _msgSender();
_initIOwnable( _contractOwner_ );
_initERC2981Base( _contractOwner_, royaltyRate_ );
_initERC721BatchMetadata( name_, symbol_ );
_setBaseURI( baseURI_ );
_CC_SAFE = wallets_[ 0 ];
_CC_CHARITY = wallets_[ 1 ];
_CC_FOUNDERS = wallets_[ 2 ];
_CC_COMMUNITY = wallets_[ 3 ];
_reserve = reserve_;
MAX_BATCH = maxBatch_;
MAX_SUPPLY = maxSupply_;
WL_MINT_PRICE = wlMintPrice_;
PUBLIC_MINT_PRICE = publicMintPrice_;
// _mintAndStake( devAddress_, 5 );
}
// **************************************
// ***** INTERNAL *****
// **************************************
/**
* @dev Internal function returning whether `operator_` is allowed to manage tokens on behalf of `tokenOwner_`.
*
* @param tokenOwner_ address that owns tokens
* @param operator_ address that tries to manage tokens
*
* @return bool whether `operator_` is allowed to manage the token
*/
function _isApprovedForAll( address tokenOwner_, address operator_ ) internal view virtual override returns ( bool ) {
return _isRegisteredProxy( tokenOwner_, operator_ ) ||
super._isApprovedForAll( tokenOwner_, operator_ );
}
/**
* @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 {
if ( address( this ).balance < amount_ ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
( bool _success_, ) = recipient_.call{ value: amount_ }( "" );
if ( ! _success_ ) {
revert CCFoundersKeys_TRANSFER_FAIL();
}
}
// **************************************
// **************************************
// ***** PUBLIC *****
// **************************************
/**
* @dev Mints `qty_` tokens and transfers them to the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must be whitelisted.
*/
function claim( uint256 qty_ ) external presaleOpen {
address _account_ = _msgSender();
if ( qty_ > anonClaimList[ _account_ ] ) {
revert CCFoundersKeys_FORBIDDEN();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
unchecked {
anonClaimList[ _account_ ] -= qty_;
}
_mint( _account_, qty_ );
}
/**
* @dev Mints `qty_` tokens, stakes `qtyStaked_` of them to the count of the caller, and transfers the remaining to them.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must be whitelisted.
* - If `qtyStaked_` is higher than `qty_`, only `qty_` tokens are staked.
*/
function claimAndStake( uint256 qty_, uint256 qtyStaked_ ) external presaleOpen {
address _account_ = _msgSender();
if ( qty_ > anonClaimList[ _account_ ] ) {
revert CCFoundersKeys_FORBIDDEN();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
unchecked {
anonClaimList[ _account_ ] -= qty_;
}
_mintAndStake( _account_, qty_, qtyStaked_ );
}
/**
* @dev Mints a token and transfers it to the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for 1 token at presale price.
* - Caller must be whitelisted.
*/
function mintPreSale( bytes32[] memory proof_ ) external payable presaleOpen isWhitelisted( _msgSender(), proof_, 1, 1 ) {
if ( _supplyMinted() + 1 > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( WL_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_consumeWhitelist( _account_, 1 );
_mint( _account_, 1 );
}
/**
* @dev Mints a token and stakes it to the count of the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.PRESALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for 1 token at presale price.
* - Caller must be whitelisted.
*/
function mintPreSaleAndStake( bytes32[] memory proof_ ) external payable presaleOpen isWhitelisted( _msgSender(), proof_, 1, 1 ) {
if ( _supplyMinted() + 1 > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( WL_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_consumeWhitelist( _account_, 1 );
_mintAndStake( _account_, 1, 1 );
}
/**
* @dev Mints `qty_` tokens and transfers them to the caller.
*
* Requirements:
*
* - Sale state must be {SaleState.SALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for `qty_` tokens at public sale price.
*/
function mint( uint256 qty_ ) external payable saleOpen {
if ( qty_ > MAX_BATCH ) {
revert CCFoundersKeys_MAX_BATCH();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( qty_ * PUBLIC_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_mint( _account_, qty_ );
}
/**
* @dev Mints `qty_` tokens, stakes `qtyStaked_` of them to the count of the caller, and transfers the remaining to them.
*
* Requirements:
*
* - Sale state must be {SaleState.SALE}.
* - There must be enough tokens left to mint outside of the reserve.
* - Caller must send enough ether to pay for `qty_` tokens at public sale price.
* - If `qtyStaked_` is higher than `qty_`, only `qty_` tokens are staked.
*/
function mintAndStake( uint256 qty_, uint256 qtyStaked_ ) external payable saleOpen {
if ( qty_ > MAX_BATCH ) {
revert CCFoundersKeys_MAX_BATCH();
}
uint256 _endSupply_ = _supplyMinted() + qty_;
if ( _endSupply_ > MAX_SUPPLY - _reserve ) {
revert CCFoundersKeys_MAX_SUPPLY();
}
if ( qty_ * PUBLIC_MINT_PRICE != msg.value ) {
revert CCFoundersKeys_INCORRECT_PRICE();
}
address _account_ = _msgSender();
_mintAndStake( _account_, qty_, qtyStaked_ );
}
// **************************************
// **************************************
// ***** CONTRACT_OWNER *****
// **************************************
/**
* @dev Mints `amounts_` tokens and transfers them to `accounts_`.
*
* Requirements:
*
* - Caller must be the contract owner.
* - `accounts_` and `amounts_` must have the same length.
* - There must be enough tokens left in the reserve.
*/
function airdrop( address[] memory accounts_, uint256[] memory amounts_ ) external onlyOwner {
uint256 _len_ = amounts_.length;
if ( _len_ != accounts_.length ) {
revert CCFoundersKeys_ARRAY_LENGTH_MISMATCH();
}
uint _totalQty_;
for ( uint256 i = _len_; i > 0; i -- ) {
_totalQty_ += amounts_[ i - 1 ];
}
if ( _totalQty_ > _reserve ) {
revert CCFoundersKeys_MAX_RESERVE();
}
unchecked {
_reserve -= _totalQty_;
}
for ( uint256 i = _len_; i > 0; i -- ) {
_mint( accounts_[ i - 1], amounts_[ i - 1] );
}
}
/**
* @dev Saves `accounts_` in the anon claim list.
*
* Requirements:
*
* - Caller must be the contract owner.
* - Sale state must be {SaleState.CLOSED}.
* - `accounts_` and `amounts_` must have the same length.
*/
function setAnonClaimList( address[] memory accounts_, uint256[] memory amounts_ ) external onlyOwner saleClosed {
uint256 _len_ = amounts_.length;
if ( _len_ != accounts_.length ) {
revert CCFoundersKeys_ARRAY_LENGTH_MISMATCH();
}
for ( uint256 i; i < _len_; i ++ ) {
anonClaimList[ accounts_[ i ] ] = amounts_[ i ];
}
}
/**
* @dev See {ITradable-setProxyRegistry}.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function setProxyRegistry( address proxyRegistryAddress_ ) external onlyOwner {
_setProxyRegistry( proxyRegistryAddress_ );
}
/**
* @dev Updates the royalty recipient and rate.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function setRoyaltyInfo( address royaltyRecipient_, uint256 royaltyRate_ ) external onlyOwner {
_setRoyaltyInfo( royaltyRecipient_, royaltyRate_ );
}
/**
* @dev See {IPausable-setSaleState}.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function setSaleState( SaleState newState_ ) external onlyOwner {
_setSaleState( newState_ );
}
/**
* @dev See {IWhitelistable-setWhitelist}.
*
* Requirements:
*
* - Caller must be the contract owner.
* - Sale state must be {SaleState.CLOSED}.
*/
function setWhitelist( bytes32 root_ ) external onlyOwner saleClosed {
_setWhitelist( root_ );
}
/**
* @dev Withdraws all the money stored in the contract and splits it amongst the set wallets.
*
* Requirements:
*
* - Caller must be the contract owner.
*/
function withdraw() external onlyOwner {
uint256 _balance_ = address(this).balance;
if ( _balance_ == 0 ) {
revert CCFoundersKeys_NO_ETHER_BALANCE();
}
uint256 _safeShare_ = _balance_ * 900 / 1000;
uint256 _charityShare_ = _balance_ * 50 / 1000;
uint256 _othersShare_ = _charityShare_ / 2;
_sendValue( payable( _CC_COMMUNITY ), _othersShare_ );
_sendValue( payable( _CC_FOUNDERS ), _othersShare_ );
_sendValue( payable( _CC_CHARITY ), _charityShare_ );
_sendValue( payable( _CC_SAFE ), _safeShare_ );
address[] memory _tos_ = new address[]( 4 );
_tos_[ 0 ] = _CC_COMMUNITY;
_tos_[ 1 ] = _CC_FOUNDERS;
_tos_[ 2 ] = _CC_CHARITY;
_tos_[ 3 ] = _CC_SAFE;
uint256[] memory _amounts_ = new uint256[]( 4 );
_amounts_[ 0 ] = _othersShare_;
_amounts_[ 1 ] = _othersShare_;
_amounts_[ 2 ] = _charityShare_;
_amounts_[ 3 ] = _safeShare_;
emit PaymentReleased( address( this ), _tos_, _amounts_ );
}
// **************************************
// **************************************
// ***** VIEW *****
// **************************************
/**
* @dev Returns the number of tokens owned by `tokenOwner_`.
*/
function balanceOf( address tokenOwner_ ) public view virtual override(ERC721Batch, ERC721BatchStakable) returns ( uint256 balance ) {
return ERC721BatchStakable.balanceOf( tokenOwner_ );
}
/**
* @dev Returns the owner of token number `tokenId_`.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function ownerOf( uint256 tokenId_ ) public view virtual override(ERC721Batch, ERC721BatchStakable) exists( tokenId_ ) returns ( address ) {
return ERC721BatchStakable.ownerOf( tokenId_ );
}
/**
* @dev See {IERC2981-royaltyInfo}.
*
* Requirements:
*
* - `tokenId_` must exist.
*/
function royaltyInfo( uint256 tokenId_, uint256 salePrice_ ) public view virtual override exists( tokenId_ ) returns ( address, uint256 ) {
return super.royaltyInfo( tokenId_, salePrice_ );
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface( bytes4 interfaceId_ ) public view virtual override(ERC721BatchEnumerable, ERC721Batch, ERC2981Base) returns ( bool ) {
return
interfaceId_ == type( IERC2981 ).interfaceId ||
ERC721Batch.supportsInterface( interfaceId_ ) ||
ERC721BatchEnumerable.supportsInterface( interfaceId_ );
}
// **************************************
} | See {ITradable-setProxyRegistry}. Requirements: - Caller must be the contract owner./ | function setProxyRegistry( address proxyRegistryAddress_ ) external onlyOwner {
_setProxyRegistry( proxyRegistryAddress_ );
}
| 14,920,311 |
/**
*Submitted for verification at Etherscan.io on 2022-03-26
*/
// SPDX-License-Identifier: GNU
// AE T H E R
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity 0.8.7;
// 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/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity 0.8.7;
/**
* @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/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity 0.8.7;
/**
* @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: contracts/Akylles/paymentsplitter.sol
pragma solidity 0.8.7;
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
using SafeMath for uint;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) internal virtual {
// a certain percentage of shares will be given to the first 1000 who mint nfts , that is why we will add shares to the first via the purchase function
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
// if _shares of the account is already initialized either by the initial constructor OR minting a nft added add the number of shares based on the amount of nfts minted
if( _shares[account] > 0) {
_shares[account] = _shares[account] + shares_ ;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
// if not a new payee will be added
else {
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity 0.8.7;
/**
* @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 = true;
}
/**
* @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());
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity 0.8.7;
/**
* @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: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity 0.8.7;
/**
* @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/MerkleProof.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity 0.8.7;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity 0.8.7;
/**
* @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.7;
/**
* @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/ERC1155/IERC1155Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity 0.8.7;
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity 0.8.7;
/**
* @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;
}
// File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity 0.8.7;
/**
* @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);
}
// File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity 0.8.7;
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @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 {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @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(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 {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
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, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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.
*/
// changed here each value to one for unique nfts.
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity 0.8.7;
// File: @openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Burnable.sol)
pragma solidity 0.8.7;
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// File: contracts/Akylles/AbstractERC1155Factory.sol
pragma solidity 0.8.7;
abstract contract AbstractERC1155Factory is Pausable, ERC1155Burnable, Ownable {
string name_;
string symbol_;
string _obscurumuri;
bool public frozen = false;
string extension;
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function setURI(string memory baseURI) external onlyOwner {
require(frozen == false);
_setURI(baseURI);
}
function name() public view returns (string memory) {
return name_;
}
function symbol() public view returns (string memory) {
return symbol_;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity 0.8.7;
/**
* @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/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity 0.8.7;
/**
* @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;
}
}
// File: contracts/Akylles/Akylles.sol
// A E T H E R
pragma solidity 0.8.7;
contract Yellownauts is AbstractERC1155Factory, PaymentSplitter {
using SafeMath for uint;
uint256 constant public MAX_SUPPLY = 2026;
uint256 maxPerTx = 3;
uint256 maxperaddress = 3;
uint256 public mintPrice = 50000000000000000;
uint256 public Idx = 0;
bool public presaleActivated = false;
bool public revealed = false;
bytes32 public merkleRoot;
string public _uri;
mapping(address => uint256) public purchaseTxs;
event Purchased(uint256 indexed index, address indexed account, uint256 amount);
constructor(
string memory _name,
string memory _symbol,
string memory obscurumuri,
string memory _extension,
bytes32 _merkleRoot,
address[] memory payees,
uint256[] memory shares_
) ERC1155(_uri) PaymentSplitter(payees, shares_) {
name_ = _name;
symbol_ = _symbol;
_obscurumuri = obscurumuri;
merkleRoot = _merkleRoot;
extension = _extension;
}
// unpause and remove all restrictions public sale ready 0.07 eth there is not max per address or max per transaction in the public sale
function setPhase2() external onlyOwner {
// after unpausing we will set no limits to transactions
mintPrice = 70000000000000000;
_unpause();
}
function ownerOf(uint256 tokenId) external view returns (bool) {
return balanceOf(msg.sender, tokenId) != 0;
}
/** set merkle root for efficient whitelisted addresses verification
*
*/
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
function setPrice(uint256 _mintPrice) external onlyOwner {
mintPrice = _mintPrice;
}
// locking metadata 4 life
function freezemeta() external onlyOwner {
frozen = true;
}
/**
* @notice edit sale restrictions
*
* @param _maxPerTx the new max amount of tokens allowed to buy in one tx
*/
function editSaleRestrictions(uint8 _maxPerTx) external onlyOwner {
maxPerTx = _maxPerTx;
}
function setPresale(bool _choice) external onlyOwner {
presaleActivated = _choice;
}
function reveal() external onlyOwner {
revealed = true;
}
/**
early access sale purchase using merkle trees to verify that a address is whitelisted
*/
function whitelistPreSale(
uint256 amount,
bytes32[] calldata merkleProof
) external payable {
require( presaleActivated , "Early access: not available yet ");
require(amount > 0 && amount <= maxPerTx, "Purchase: amount prohibited");
require(purchaseTxs[msg.sender] + amount <= maxperaddress); // require every address on the whitelist to mint a maximum of their address .
bytes32 node = keccak256(abi.encodePacked(msg.sender));
require(
MerkleProof.verify(merkleProof, merkleRoot, node),
"MerkleDistributor: Invalid proof."
);
if(amount > 1) {
_bulkpurchase(amount);
}
else {
_purchase(amount);
}
}
function purchase(uint256 amount) external payable whenNotPaused {
if(amount > 1) {
_bulkpurchase(amount);
}
else {
_purchase(amount);
}
}
/**
* @notice global purchase function
used in early access and public sale
*
* @param amount the amount of tokens to purchase
*/
// during opening of the public sale theres no limit for minting and owning tokens in transactions.
function _purchase(uint256 amount ) private {
require(amount > 0 , "amount cant be zero ");
require(Idx + amount <= MAX_SUPPLY , "Purchase: Max supply of 2026 reached");
require(msg.value == amount * mintPrice, "Purchase: Incorrect payment");
Idx += 1;
purchaseTxs[msg.sender] += 1;
_mint(msg.sender,Idx, amount, "");
emit Purchased(Idx, msg.sender, amount);
}
// this function is used to bulk purchase Unique nfts.
function _bulkpurchase(uint256 amount ) private {
require(Idx + amount <= MAX_SUPPLY, "Purchase: Max supply reached ");
require(msg.value == amount * mintPrice, "Purchase: Incorrect payment XX");
uint256[] memory ids = new uint256[](amount);
uint256[] memory values = new uint256[](amount);
Idx += amount;
uint256 iterator = Idx;
for(uint i = 0 ; i < amount; i++){
ids[i] = iterator; // line up Unique NFTs ID in a array.
iterator = iterator-1;
values[i] = 1; // for Unique Nfts Supply of every ID MUST be one .1 to be injected in the _mintBatch function
}
purchaseTxs[msg.sender] += amount;
_mintBatch(msg.sender, ids,values, "");
emit Purchased(Idx, msg.sender, amount);
}
// airdrop nft function for owner only to be able to airdrop Unique nfts
function airdrop(address payable reciever, uint256 amount ) external onlyOwner() {
require(Idx + amount <= MAX_SUPPLY, "Max supply of 2026 reached");
require(amount >= 1, "nonzero err");
if(amount == 1) {
Idx += 1;
_mint(reciever, Idx, 1 , "");
}
else {
uint256[] memory ids = new uint256[](amount);
uint256[] memory values = new uint256[](amount);
Idx += amount;
uint256 iterator = Idx;
for(uint i = 0 ; i < amount; i++){
ids[i] = iterator; // line up Unique NFTs ID in a array.
iterator = iterator-1;
values[i] = 1; // for Unique Nfts Supply of every ID MUST be one .1 to be injected in the _mintBatch function
}
_mintBatch(reciever, ids,values, "");
}
}
function release(address payable account) public override {
require(msg.sender == account || msg.sender == owner(), "Release: no permission");
super.release(account);
}
function sethiddenuri(string memory huri) external onlyOwner() {
_obscurumuri = huri;
}
function uri(uint256 _id) public view override returns (string memory) {
require(_id <= Idx, "Id deos not exist " );
return revealed ? string(abi.encodePacked(super.uri(_id),Strings.toString(_id) , extension)) : _obscurumuri ;
}
} | unpause and remove all restrictions public sale ready 0.07 eth there is not max per address or max per transaction in the public sale after unpausing we will set no limits to transactions | function setPhase2() external onlyOwner {
mintPrice = 70000000000000000;
_unpause();
}
| 10,908,622 |
./full_match/1/0xD2cAa748B66768aC9c53A5443225Bdf1365dd4B6/sources/contracts/WiseOracleHub/OracleHelper.sol | Determines info for the heartbeat update mechanism for chainlink oracles, roundIds./ | function _getLatestAggregatorRoundId(
address _tokenAddress
)
internal
view
returns (uint80)
{
( uint80 roundId,
,
,
,
) = priceFeed[_tokenAddress].latestRoundData();
return roundId;
}
| 17,171,953 |
pragma solidity ^0.4.24;
import "./ScryToken.sol";
contract ScryProtocol {
enum TransactionState {Begin, Created, Voted, Buying, ReadyForDownload, Closed}
struct DataInfoPublished {
uint256 price;
bytes metaDataIdEncSeller;
bytes32[] proofDataIds;
uint256 numberOfProof;
string despDataId;
address seller;
bool supportVerify;
bool used;
}
struct TransactionItem {
TransactionState state;
address buyer;
address seller;
address[] verifiers;
bool[] creditGived;
string publishId;
bytes meteDataIdEncBuyer;
bytes metaDataIdEncSeller;
uint256 buyerDeposit;
uint256 verifierBonus;
bool needVerify;
bool used;
}
struct Verifier {
address addr;
uint256 deposit;
uint8 credits; //credit: 0-5
uint256 creditTimes;
bool enable;
}
uint8 validVerifierCount = 0;
uint8 verifierNum = 2;
uint256 verifierDepositToken = 10000;
uint256 verifierBonus = 300;
uint8 creditLow = 0;
uint8 creditHigh = 5;
uint8 creditThreshold = 2;
struct VoteResult {
bool judge;
string comments;
bool used;
}
Verifier[] verifiers;
mapping (string => DataInfoPublished) mapPublishedData;
mapping (uint256 => TransactionItem) mapTransaction;
mapping (uint256 => mapping(address => VoteResult)) mapVote;
event RegisterVerifier(string seqNo, address[] users);
event DataPublish(string seqNo, string publishId, uint256 price, string despDataId, bool supportVerify, address[] users);
event VerifiersChosen(string seqNo, uint256 transactionId, string publishId, bytes32[] proofIds, TransactionState state, address[] users);
event TransactionCreate(string seqNo, uint256 transactionId, string publishId, bytes32[] proofIds, bool needVerify, TransactionState state, address[] users);
event Vote(string seqNo, uint256 transactionId, bool judge, string comments, TransactionState state, uint8 index, address[] users);
event Buy(string seqNo, uint256 transactionId, string publishId, bytes metaDataIdEncSeller, TransactionState state, address buyer, uint8 index, address[] users);
event ReadyForDownload(string seqNo, uint256 transactionId, bytes metaDataIdEncBuyer, TransactionState state, uint8 index, address[] users);
event TransactionClose(string seqNo, uint256 transactionId, TransactionState state, uint8 index, address[] users);
event VerifierDisable(string seqNo, address verifier, address[] users);
uint256 transactionSeq = 0;
uint256 encryptedIdLen = 32;
address token_address = 0x0;
address owner = 0x0;
ERC20 token;
constructor (address _token) public {
require(_token != 0x0);
owner = msg.sender;
token_address = _token;
token = ERC20(_token);
//the first element used for empty usage
verifiers[verifiers.length++] = Verifier(0x00, 0, 0, 0, false);
}
function registerAsVerifier(string seqNo) external {
Verifier storage v = getVerifier(msg.sender);
require( v.addr == 0x00, "The verifier is already registered");
//deposit
if (verifierDepositToken > 0) {
require(token.balanceOf(msg.sender) >= verifierDepositToken, "No enough balance");
require(token.transferFrom(msg.sender, address(this), verifierDepositToken), "Failed to transfer token from caller");
}
verifiers[verifiers.length++] = Verifier(msg.sender, verifierDepositToken, 0, 0, true);
validVerifierCount++;
address[] memory users = new address[](1);
users[0] = msg.sender;
emit RegisterVerifier(seqNo, users);
}
function publishDataInfo(string seqNo, string publishId, uint256 price, bytes metaDataIdEncSeller,
bytes32[] proofDataIds, string despDataId, bool supportVerify) external {
address[] memory users = new address[](1);
users[0] = address(0x00);
DataInfoPublished storage data = mapPublishedData[publishId];
require(!data.used, "Duplicate publish id");
mapPublishedData[publishId] = DataInfoPublished(price, metaDataIdEncSeller, proofDataIds, proofDataIds.length, despDataId, msg.sender, supportVerify, true);
emit DataPublish(seqNo, publishId, price, despDataId, supportVerify, users);
}
function isPublishedDataExisted(string publishId) internal view returns (bool) {
DataInfoPublished storage data = mapPublishedData[publishId];
return data.used;
}
function createTransaction(string seqNo, string publishId, bool startVerify) external {
//published data info
DataInfoPublished memory data = mapPublishedData[publishId];
require(data.used, "Publish data does not exist");
uint256 fee = data.price;
bool needVerify = data.supportVerify && startVerify;
if (needVerify) {
fee += verifierBonus * verifierNum;
}
require((token.balanceOf(msg.sender)) >= fee, "No enough balance");
require(token.transferFrom(msg.sender, address(this), fee), "Failed to transfer token from caller");
createTransaction2(seqNo, data, fee, publishId, needVerify);
}
function createTransaction2(string seqNo, DataInfoPublished data, uint256 fee, string publishId, bool needVerify) internal {
//create transaction
uint txId = getTransactionId();
bytes memory metaDataIdEncryptedPlaceholder = new bytes(encryptedIdLen);
address[] memory selectedVerifiers = new address[](verifierNum);
bool[] memory creditGived;
address[] memory users = new address[](1);
if (needVerify) {
//choose verifiers randomly
selectedVerifiers = chooseVerifiers(verifierNum);
creditGived = new bool[](verifierNum);
for (uint8 i = 0; i < verifierNum; i++) {
users[0] = selectedVerifiers[i];
emit VerifiersChosen(seqNo, txId, publishId, data.proofDataIds, TransactionState.Created, users);
}
}
users[0] = msg.sender;
emit TransactionCreate(seqNo, txId, publishId, data.proofDataIds, needVerify, TransactionState.Created, users);
mapTransaction[txId] = TransactionItem(TransactionState.Created, msg.sender, data.seller, selectedVerifiers, creditGived,
publishId, metaDataIdEncryptedPlaceholder, data.metaDataIdEncSeller, fee, verifierBonus, needVerify, true);
}
function chooseVerifiers(uint8 num) internal view returns (address[] memory) {
require(num < validVerifierCount, "No enough valid verifiers");
address[] memory chosenVerifiers = new address[](num);
for (uint8 i = 0; i < num; i++) {
uint index = getRandomNumber(verifiers.length) % verifiers.length;
Verifier storage v = verifiers[index];
//loop if invalid verifier was chosen until get valid verifier
address vb = v.addr;
while (!v.enable || verifierExist(v.addr, chosenVerifiers)) {
v = verifiers[(++index) % verifiers.length];
require(v.addr != vb, "Disordered verifiers");
}
chosenVerifiers[i] = v.addr;
}
return chosenVerifiers;
}
function verifierValid(Verifier v, address[] arr) pure internal returns (bool, uint8) {
bool exist;
uint8 index;
(exist, index) = getVerifierIndex(v.addr, arr);
return (v.enable && exist, index);
}
function verifierExist(address addr, address[] arr) pure internal returns (bool) {
bool exist;
(exist, ) = getVerifierIndex(addr, arr);
return exist;
}
function getVerifierIndex(address verifier, address[] arrayVerifier) pure internal returns (bool, uint8) {
for (uint8 i = 0; i < arrayVerifier.length; i++) {
if (arrayVerifier[i] == verifier) {
return (true, i);
}
}
return (false, 0);
}
function getTransactionId() internal returns(uint) {
return transactionSeq++;
}
function getRandomNumber(uint mod) internal view returns (uint) {
return uint(keccak256(now, msg.sender)) % mod;
}
function vote(string seqNo, uint txId, bool judge, string comments) external {
TransactionItem storage txItem = mapTransaction[txId];
require(txItem.used, "Transaction does not exist");
require(txItem.state == TransactionState.Created || txItem.state == TransactionState.Voted, "Invalid transaction state");
bool valid;
uint8 index;
Verifier storage verifier = getVerifier(msg.sender);
(valid, index) = verifierValid(verifier, txItem.verifiers);
require(valid, "Invalid verifier");
if (!mapVote[txId][msg.sender].used) {
payToVerifier(txItem, verifier.addr);
}
mapVote[txId][msg.sender] = VoteResult(judge, comments, true);
txItem.state = TransactionState.Voted;
txItem.creditGived[index] = false;
address[] memory users = new address[](1);
users[0] = txItem.buyer;
emit Vote(seqNo, txId, judge, comments, txItem.state, index+1, users);
}
function buyData(string seqNo, uint256 txId) external {
//validate
TransactionItem storage txItem = mapTransaction[txId];
require(txItem.used, "Transaction does not exist");
require(txItem.buyer == msg.sender, "Invalid buyer");
DataInfoPublished memory data = mapPublishedData[txItem.publishId];
require(data.used, "Publish data does not exist");
//buyer can decide to buy even though no verifier response
require(txItem.state == TransactionState.Created || txItem.state == TransactionState.Voted, "Invalid transaction state");
txItem.state = TransactionState.Buying;
address[] memory users = new address[](1);
users[0] = txItem.seller;
emit Buy(seqNo, txId, txItem.publishId, txItem.metaDataIdEncSeller, txItem.state, txItem.buyer, 0, users);
users[0] = msg.sender;
emit Buy(seqNo, txId, txItem.publishId, txItem.metaDataIdEncSeller, txItem.state, txItem.buyer, 1, users);
}
function cancelTransaction(string seqNo, uint256 txId) external {
TransactionItem storage txItem = mapTransaction[txId];
require(txItem.used, "Transaction does not exist");
require(txItem.buyer == msg.sender, "Invalid cancel operator");
require(txItem.state == TransactionState.Created || txItem.state == TransactionState.Voted ||
txItem.state == TransactionState.Buying, "Invalid transaction state");
revertToBuyer(txItem);
closeTransaction(txItem, seqNo, txId);
}
// function getBuyer(string seqNo, address seller, uint256 txId) external returns (address) {
// TransactionItem storage txItem = mapTransaction[txId];
// require(txItem.used, "Transaction does not exist");
// require(msg.sender == txItem.seller, "Invalid caller");
// require(txItem.state == TransactionState.Buying, "Invalid transaction state");
//
// return txItem.buyer;
// }
function submitMetaDataIdEncWithBuyer(string seqNo, uint256 txId, bytes encryptedMetaDataId) external {
//validate
TransactionItem storage txItem = mapTransaction[txId];
require(txItem.used, "Transaction does not exist");
require(txItem.seller == msg.sender, "Invalid seller");
require(txItem.state == TransactionState.Buying, "Invalid transaction state");
txItem.meteDataIdEncBuyer = encryptedMetaDataId;
txItem.state = TransactionState.ReadyForDownload;
//ReadyForDownload event
address[] memory users = new address[](1);
users[0] = txItem.seller;
emit ReadyForDownload(seqNo, txId, txItem.meteDataIdEncBuyer, txItem.state, 0, users);
users[0] = txItem.buyer;
emit ReadyForDownload(seqNo, txId, txItem.meteDataIdEncBuyer, txItem.state, 1, users);
}
function confirmDataTruth(string seqNo, uint256 txId, bool truth) external {
//validate
TransactionItem storage txItem = mapTransaction[txId];
require(txItem.used, "Transaction does not exist");
require(txItem.buyer == msg.sender, "Invalid buyer");
DataInfoPublished storage data = mapPublishedData[txItem.publishId];
require(data.used, "Publish data does not exist");
require(txItem.state == TransactionState.ReadyForDownload, "Invalid transaction state");
if (!txItem.needVerify) {
if(truth) {
payToSeller(txItem, data);
}
closeTransaction(txItem, seqNo, txId);
} else {
if (truth) {
payToSeller(txItem, data);
closeTransaction(txItem, seqNo, txId);
} else {
// arbitrate.
closeTransaction(txItem, seqNo, txId);
}
}
}
function closeTransaction(TransactionItem storage txItem, string seqNo, uint256 txId) internal {
txItem.state = TransactionState.Closed;
address[] memory users = new address[](1);
users[0] = txItem.seller;
emit TransactionClose(seqNo, txId, txItem.state, 0, users);
users[0] = txItem.buyer;
emit TransactionClose(seqNo, txId, txItem.state, 1, users);
}
function payToVerifier(TransactionItem storage txItem, address verifier) internal {
if (txItem.buyerDeposit >= txItem.verifierBonus) {
txItem.buyerDeposit -= txItem.verifierBonus;
if (!token.transfer(verifier, txItem.verifierBonus)) {
txItem.buyerDeposit += txItem.verifierBonus;
require(false, "Failed to pay to verifier");
}
} else {
require(false, "Low deposit value for paying to verifier");
}
}
function payToSeller(TransactionItem storage txItem, DataInfoPublished storage data) internal {
if (txItem.buyerDeposit >= data.price) {
txItem.buyerDeposit -= data.price;
if (!token.transfer(data.seller, data.price)) {
txItem.buyerDeposit += data.price;
require(false, "Failed to pay to seller");
}
} else {
require(false, "Low deposit value for paying to seller");
}
}
function revertToBuyer(TransactionItem storage txItem) internal {
uint256 deposit = txItem.buyerDeposit;
txItem.buyerDeposit = 0;
if (!token.transfer(txItem.buyer, deposit)) {
txItem.buyerDeposit = deposit;
require(false, "Failed to revert to buyer his token");
}
}
function setVerifierDepositToken(uint256 deposit) external {
require(owner == msg.sender, "The value only can be set by owner");
verifierDepositToken = deposit;
}
function setVerifierNum(uint8 num) external {
require(owner == msg.sender, "The value only can be set by owner");
verifierNum = num;
}
function setVerifierBonus(uint256 bonus) external {
require(owner == msg.sender, "The value only can be set by owner");
verifierBonus = bonus;
}
function creditsToVerifier(string seqNo, uint256 txId, uint8 verifierIndex, uint8 credit) external {
//validate
require(credit >= creditLow && credit <= creditHigh, "Valid credit scope is 0 <= credit <= 5");
TransactionItem storage txItem = mapTransaction[txId];
require(txItem.used, "Transaction does not exist");
Verifier storage verifier = getVerifier(txItem.verifiers[verifierIndex]);
require(verifier.addr != 0x00, "Verifier does not exist");
DataInfoPublished storage data = mapPublishedData[txItem.publishId];
require(data.used, "Publish data does not exist");
require(txItem.needVerify, "The transaction do not support verification");
bool valid;
uint256 index;
(valid, index) = verifierValid(verifier, txItem.verifiers);
require(valid, "Invalid verifier");
require(!txItem.creditGived[index], "The verifier's credit in this transaction has been submitted");
verifier.credits = (uint8)((verifier.credits * verifier.creditTimes + credit)/(verifier.creditTimes+1));
verifier.creditTimes++;
txItem.creditGived[index] = true;
address[] memory users = new address[](1);
users[0] = address(0x00);
//disable verifier and forfeiture deposit while credit <= creditThreshold
if (verifier.credits <= creditThreshold) {
verifier.enable = false;
verifier.deposit = 0;
validVerifierCount--;
require(validVerifierCount >= 1, "Invalid verifier count");
emit VerifierDisable(seqNo, verifier.addr, users);
}
}
function getVerifier(address v) internal view returns (Verifier storage){
for (uint256 i = 0; i < verifiers.length; i++) {
if (verifiers[i].addr == v) {
return verifiers[i];
}
}
return verifiers[0];
}
} | loop if invalid verifier was chosen until get valid verifier | function chooseVerifiers(uint8 num) internal view returns (address[] memory) {
require(num < validVerifierCount, "No enough valid verifiers");
address[] memory chosenVerifiers = new address[](num);
for (uint8 i = 0; i < num; i++) {
uint index = getRandomNumber(verifiers.length) % verifiers.length;
Verifier storage v = verifiers[index];
address vb = v.addr;
while (!v.enable || verifierExist(v.addr, chosenVerifiers)) {
v = verifiers[(++index) % verifiers.length];
require(v.addr != vb, "Disordered verifiers");
}
chosenVerifiers[i] = v.addr;
}
return chosenVerifiers;
}
| 12,557,988 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
// Interface
import { ILazyMintERC20 } from "./ILazyMintERC20.sol";
// Base
import { Coin } from "../../Coin.sol";
// Access Control + security
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
// Utils
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
// Helper interfaces
import { IWETH } from "../../interfaces/IWETH.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract LazyMintERC20 is ILazyMintERC20, Coin, ReentrancyGuard {
/// @dev The address interpreted as native token of the chain.
address private constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev The address of the native token wrapper contract.
address public immutable nativeTokenWrapper;
/// @dev The adress that receives all primary sales value.
address public defaultSaleRecipient;
/// @dev Contract interprets 10_000 as 100%.
uint128 private constant MAX_BPS = 10_000;
/// @dev The % of secondary sales collected as royalties. See EIP 2981.
uint64 public royaltyBps;
/// @dev The % of primary sales collected by the contract as fees.
uint64 public feeBps;
/// @dev The claim conditions at any given moment.
ClaimConditions public claimConditions;
constructor(
string memory _name,
string memory _symbol,
string memory _contractURI,
address payable _controlCenter,
address _trustedForwarder,
address _nativeTokenWrapper,
address _saleRecipient,
uint128 _royaltyBps,
uint128 _feeBps
)
Coin(
_controlCenter,
_name,
_symbol,
_trustedForwarder,
_contractURI
)
{
// Set the protocol control center
nativeTokenWrapper = _nativeTokenWrapper;
defaultSaleRecipient = _saleRecipient;
royaltyBps = uint64(_royaltyBps);
feeBps = uint64(_feeBps);
}
// ===== Public functions =====
/// @dev At any given moment, returns the uid for the active claim condition.
function getIndexOfActiveCondition() public view returns (uint256) {
uint256 totalConditionCount = claimConditions.totalConditionCount;
require(totalConditionCount > 0, "no public mint condition.");
for (uint256 i = totalConditionCount; i > 0; i -= 1) {
if (block.timestamp >= claimConditions.claimConditionAtIndex[i - 1].startTimestamp) {
return i - 1;
}
}
revert("no active mint condition.");
}
// ===== External functions =====
/// @dev Lets an account claim a given quantity of tokens, of a single tokenId.
function claim(address _receiver, uint256 _quantity, bytes32[] calldata _proofs) external payable nonReentrant {
// Get the claim conditions.
uint256 activeConditionIndex = getIndexOfActiveCondition();
ClaimCondition memory condition = claimConditions.claimConditionAtIndex[activeConditionIndex];
// Verify claim validity. If not valid, revert.
verifyClaim(_receiver, _quantity, _proofs, activeConditionIndex);
// If there's a price, collect price.
collectClaimPrice(condition, _quantity);
// Mint the relevant tokens to claimer.
transferClaimedTokens(_receiver, activeConditionIndex, _quantity);
emit ClaimedTokens(activeConditionIndex, _msgSender(), _receiver, _quantity);
}
/// @dev Lets a module admin update mint conditions without resetting the restrictions.
function updateClaimConditions(ClaimCondition[] calldata _conditions) external onlyModuleAdmin {
resetClaimConditions(_conditions);
emit NewClaimConditions(_conditions);
}
/// @dev Lets a module admin set mint conditions.
function setClaimConditions(ClaimCondition[] calldata _conditions) external onlyModuleAdmin {
uint256 numOfConditionsSet = resetClaimConditions(_conditions);
resetTimestampRestriction(numOfConditionsSet);
emit NewClaimConditions(_conditions);
}
// ===== Setter functions =====
/// @dev Lets a module admin set the default recipient of all primary sales.
function setDefaultSaleRecipient(address _saleRecipient) external onlyModuleAdmin {
defaultSaleRecipient = _saleRecipient;
emit NewSaleRecipient(_saleRecipient);
}
/// @dev Lets a module admin update the royalties paid on secondary token sales.
function setRoyaltyBps(uint256 _royaltyBps) public onlyModuleAdmin {
require(_royaltyBps <= MAX_BPS, "bps <= 10000.");
royaltyBps = uint64(_royaltyBps);
emit RoyaltyUpdated(_royaltyBps);
}
/// @dev Lets a module admin update the fees on primary sales.
function setFeeBps(uint256 _feeBps) public onlyModuleAdmin {
require(_feeBps <= MAX_BPS, "bps <= 10000.");
feeBps = uint64(_feeBps);
emit PrimarySalesFeeUpdates(_feeBps);
}
// ===== Getter functions =====
/// @dev Returns the current active mint condition for a given tokenId.
function getTimestampForNextValidClaim(uint256 _index, address _claimer)
public
view
returns (uint256 nextValidTimestampForClaim)
{
uint256 timestampIndex = _index + claimConditions.timstampLimitIndex;
uint256 timestampOfLastClaim = claimConditions.timestampOfLastClaim[_claimer][timestampIndex];
unchecked {
nextValidTimestampForClaim =
timestampOfLastClaim +
claimConditions.claimConditionAtIndex[_index].waitTimeInSecondsBetweenClaims;
if (nextValidTimestampForClaim < timestampOfLastClaim) {
nextValidTimestampForClaim = type(uint256).max;
}
}
}
/// @dev Returns the mint condition for a given tokenId, at the given index.
function getClaimConditionAtIndex(uint256 _index) external view returns (ClaimCondition memory mintCondition) {
mintCondition = claimConditions.claimConditionAtIndex[_index];
}
// ===== Internal functions =====
/// @dev Overwrites the current claim conditions with new claim conditions
function resetClaimConditions(ClaimCondition[] calldata _conditions) internal returns (uint256 indexForCondition) {
// make sure the conditions are sorted in ascending order
uint256 lastConditionStartTimestamp;
for (uint256 i = 0; i < _conditions.length; i++) {
require(
lastConditionStartTimestamp == 0 || lastConditionStartTimestamp < _conditions[i].startTimestamp,
"startTimestamp must be in ascending order."
);
require(_conditions[i].maxClaimableSupply > 0, "max mint supply cannot be 0.");
claimConditions.claimConditionAtIndex[indexForCondition] = ClaimCondition({
startTimestamp: _conditions[i].startTimestamp,
maxClaimableSupply: _conditions[i].maxClaimableSupply,
supplyClaimed: 0,
waitTimeInSecondsBetweenClaims: _conditions[i].waitTimeInSecondsBetweenClaims,
pricePerToken: _conditions[i].pricePerToken,
currency: _conditions[i].currency,
merkleRoot: _conditions[i].merkleRoot
});
indexForCondition += 1;
lastConditionStartTimestamp = _conditions[i].startTimestamp;
}
uint256 totalConditionCount = claimConditions.totalConditionCount;
if (indexForCondition < totalConditionCount) {
for (uint256 j = indexForCondition; j < totalConditionCount; j += 1) {
delete claimConditions.claimConditionAtIndex[j];
}
}
claimConditions.totalConditionCount = indexForCondition;
}
/// @dev Updates the `timstampLimitIndex` to reset the time restriction between claims, for a claim condition.
function resetTimestampRestriction(uint256 _factor) internal {
claimConditions.timstampLimitIndex += _factor;
}
/// @dev Checks whether a request to claim tokens obeys the active mint condition.
function verifyClaim(
address _claimer,
uint256 _quantity,
bytes32[] calldata _proofs,
uint256 _conditionIndex
) public view {
ClaimCondition memory _claimCondition = claimConditions.claimConditionAtIndex[_conditionIndex];
require(
_quantity > 0 && _claimCondition.supplyClaimed + _quantity <= _claimCondition.maxClaimableSupply,
"invalid quantity claimed."
);
uint256 timestampIndex = _conditionIndex + claimConditions.timstampLimitIndex;
uint256 timestampOfLastClaim = claimConditions.timestampOfLastClaim[_claimer][timestampIndex];
uint256 nextValidTimestampForClaim = getTimestampForNextValidClaim(_conditionIndex, _claimer);
require(timestampOfLastClaim == 0 || block.timestamp >= nextValidTimestampForClaim, "cannot claim yet.");
if (_claimCondition.merkleRoot != bytes32(0)) {
bytes32 leaf = keccak256(abi.encodePacked(_claimer, _quantity));
require(MerkleProof.verify(_proofs, _claimCondition.merkleRoot, leaf), "not in whitelist.");
}
}
/// @dev Collects and distributes the primary sale value of tokens being claimed.
function collectClaimPrice(ClaimCondition memory _claimCondition, uint256 _quantityToClaim) internal {
if (_claimCondition.pricePerToken == 0) {
return;
}
uint256 totalPrice = _quantityToClaim * _claimCondition.pricePerToken;
uint256 fees = (totalPrice * feeBps) / MAX_BPS;
if (_claimCondition.currency == NATIVE_TOKEN) {
require(msg.value == totalPrice, "must send total price.");
} else {
validateERC20BalAndAllowance(_msgSender(), _claimCondition.currency, totalPrice);
}
transferCurrency(_claimCondition.currency, _msgSender(), controlCenter.getRoyaltyTreasury(address(this)), fees);
transferCurrency(_claimCondition.currency, _msgSender(), defaultSaleRecipient, totalPrice - fees);
}
/// @dev Transfers the tokens being claimed.
function transferClaimedTokens(address _to, uint256 _claimConditionIndex, uint256 _quantityBeingClaimed) internal {
// Update the supply minted under mint condition.
claimConditions.claimConditionAtIndex[_claimConditionIndex].supplyClaimed += _quantityBeingClaimed;
// Update the claimer's next valid timestamp to mint. If next mint timestamp overflows, cap it to max uint256.
uint256 timestampIndex = _claimConditionIndex + claimConditions.timstampLimitIndex;
claimConditions.timestampOfLastClaim[_msgSender()][timestampIndex] = block.timestamp;
_mint(_to, _quantityBeingClaimed);
}
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
IWETH(nativeTokenWrapper).withdraw(_amount);
safeTransferNativeToken(_to, _amount);
} else if (_to == address(this)) {
require(_amount == msg.value, "native token value does not match bid amount.");
IWETH(nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeToken(_to, _amount);
}
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Validates that `_addrToCheck` owns and has approved contract to transfer the appropriate amount of currency
function validateERC20BalAndAllowance(
address _addrToCheck,
address _currency,
uint256 _currencyAmountToCheckAgainst
) internal view {
require(
IERC20(_currency).balanceOf(_addrToCheck) >= _currencyAmountToCheckAgainst &&
IERC20(_currency).allowance(_addrToCheck, address(this)) >= _currencyAmountToCheckAgainst,
"insufficient currency balance or allowance."
);
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(nativeTokenWrapper).deposit{ value: value }();
safeTransferERC20(nativeTokenWrapper, address(this), to, value);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
uint256 balBefore = IERC20(_currency).balanceOf(_to);
bool success = IERC20(_currency).transferFrom(_from, _to, _amount);
uint256 balAfter = IERC20(_currency).balanceOf(_to);
require(success && balAfter == balBefore + _amount, "failed to transfer currency.");
}
} | Lets an account claim a given quantity of tokens, of a single tokenId. Get the claim conditions. Verify claim validity. If not valid, revert. If there's a price, collect price. Mint the relevant tokens to claimer. | function claim(address _receiver, uint256 _quantity, bytes32[] calldata _proofs) external payable nonReentrant {
uint256 activeConditionIndex = getIndexOfActiveCondition();
ClaimCondition memory condition = claimConditions.claimConditionAtIndex[activeConditionIndex];
verifyClaim(_receiver, _quantity, _proofs, activeConditionIndex);
collectClaimPrice(condition, _quantity);
transferClaimedTokens(_receiver, activeConditionIndex, _quantity);
emit ClaimedTokens(activeConditionIndex, _msgSender(), _receiver, _quantity);
}
| 15,868,461 |
./partial_match/5/0x212272215413D9387929839E76cE7071c8A4AE91/sources/DNSSECImpl.sol | An interface for contracts implementing a DNSSEC digest./ | interface Digest {
function verify(bytes calldata data, bytes calldata hash) external pure returns (bool);
}
}
| 16,852,975 |
/**
*Submitted for verification at Etherscan.io on 2021-10-19
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.4.24;
//-----------------------------------------------------------------------------//
// Name : MPadLaunchPad //
// Swap tokens to claim launch tokens //
// Distribution Contract //
//-----------------------------------------------------------------------------//
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IBEP20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract IMainToken{
function transfer(address, uint256) public pure returns (bool);
function transferFrom(address, address, uint256) public pure returns (bool);
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, 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,"Invalid values");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0,"Invalid values");
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 unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a,"Invalid values");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a,"Invalid values");
return c;
}
/**
* @dev Divides two unsigned integers 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,"Invalid values");
return a % b;
}
}
contract MultiPadLaunchApp is IBEP20 {
using SafeMath for uint256;
IMainToken iMainToken;
//variable declaration
address private _owner;
string private _name;
string private _symbol;
uint8 private _decimals = 18;
uint256 private _totalSupply;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
// Special business use case variables
mapping (address => bool) _whitelistedAddress;
mapping (address => uint256) _recordSale;
mapping (address => bool) _addressLocked;
mapping (address => uint256) _finalSoldAmount;
mapping (address => mapping(uint256 => bool)) reEntrance;
mapping (address => uint256) specialAddBal;
mapping (address => uint256) _contributionBNB;
mapping (address => mapping(uint256 => uint256)) _claimedByUser;
mapping (address =>mapping(uint256 => uint256))_thisSaleContribution;
mapping (address => uint) _multiplier;
address[] private _whitelistedUserAddresses;
uint256 private saleStartTime;
uint256 private saleEndTime;
uint256 private saleMinimumAmount;
uint256 private saleMaximumAmount;
uint256 private saleId = 0;
uint256 private tokenPrice;
uint256 private deploymentTime;
uint256 private pricePerToken;
uint256 private hardCap;
uint256 private decimalBalancer = 1000000000;
uint256 private IDOAvailable;
address private tokenContractAddress;
bool whitelistFlag = true;
address private IDOAddress;
string private _baseName;
uint256 private _claimTime1;
constructor (string memory name, string memory symbol, uint256 totalSupply, address owner, uint256 _totalDummySupply) public {
_name = name;
_symbol = symbol;
_totalSupply = totalSupply*(10**uint256(_decimals));
_balances[owner] = _totalSupply;
_owner = owner;
deploymentTime = block.timestamp;
_transfer(_owner,address(this),_totalDummySupply*(10**uint256(_decimals)));
}
function setTokenAddress(address _ITokenContract) onlyOwner external returns(bool){
tokenContractAddress = _ITokenContract;
iMainToken = IMainToken(_ITokenContract);
}
/* ----------------------------------------------------------------------------
* View only functions
* ----------------------------------------------------------------------------
*/
/**
* @return the name of the token.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @return the name of the token.
*/
function setBaseName(string baseName) external onlyOwner returns (bool) {
_baseName = baseName;
return true;
}
/**
* @return the name of the token.
*/
function baseName() external view returns (string memory) {
return _baseName;
}
/**
* @return the symbol of the token.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @return the number of decimals of the token.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/* ----------------------------------------------------------------------------
* Transfer, allow and burn functions
* ----------------------------------------------------------------------------
*/
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0),"Invalid to address");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/*----------------------------------------------------------------------------
* Functions for owner
*----------------------------------------------------------------------------
*/
/**
* @dev get address of smart contract owner
* @return address of owner
*/
function getowner() external view returns (address) {
return _owner;
}
/**
* @dev modifier to check if the message sender is owner
*/
modifier onlyOwner() {
require(isOwner(),"You are not authenticate to make this transfer");
_;
}
/**
* @dev Internal function for modifier
*/
function isOwner() internal view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfer ownership of the smart contract. For owner only
* @return request status
*/
function transferOwnership(address newOwner) external onlyOwner returns (bool){
require(newOwner != address(0), "Owner address cant be zero");
_owner = newOwner;
return true;
}
/* ----------------------------------------------------------------------------
* Functions for Additional Business Logic For Owner Functions
* ----------------------------------------------------------------------------
*/
/**
* @dev Whitelist Addresses for further transactions
* @param _userAddresses Array of user addresses
*/
function whitelistUserAdress(address[] _userAddresses, uint[] _multiplierAmount) external onlyOwner returns(bool){
uint256 count = _userAddresses.length;
require(count < 201, "Array Overflow"); //Max 200 enteries at a time
for (uint256 i = 0; i < count; i++){
_whitelistedUserAddresses.push(_userAddresses[i]);
_whitelistedAddress[_userAddresses[i]] = true;
_multiplier[_userAddresses[i]] = _multiplierAmount[i];
}
return true;
}
//Get the multiplier details
function getMultiplierbyAddress(address _userAddress) external view returns(uint256){
return _multiplier[_userAddress];
}
/**
* @dev get the list of whitelisted addresses
*/
function getWhitelistUserAdress() external view returns(address[] memory){
return _whitelistedUserAddresses;
}
/**
* @dev Set sale parameters for users to buy new tokens
* @param _startTime Start time of the sale
* @param _endTime End time of the sale
* @param _minimumAmount Minimum accepted amount
* @param _maximumAmount Maximum accepted amount
*/
function setSaleParameter(
uint256 _startTime,
uint256 _endTime,
uint256 _minimumAmount,
uint256 _maximumAmount,
bool _whitelistFlag
) external onlyOwner returns(bool){
require(_startTime > 0 && _endTime > 0 && _minimumAmount > 0 && _maximumAmount > 0, "Invalid Values");
saleStartTime = _startTime;
saleEndTime = _endTime;
saleMinimumAmount = _minimumAmount;
saleMaximumAmount = _maximumAmount;
saleId = saleId.add(1);
whitelistFlag = _whitelistFlag;
return true;
}
/**
* @dev Get Sale Details Description
*/
function getSaleParameter(address _userAddress) external view returns(
uint256 _startTime,
uint256 _endTime,
uint256 _minimumAmount,
uint256 _maximumAmount,
uint256 _saleId,
bool _whitelistFlag
){
if(whitelistFlag == true && _whitelistedAddress[_userAddress] == true){
_maximumAmount = saleMaximumAmount.mul(_multiplier[_userAddress]);
}
else{
_maximumAmount = saleMaximumAmount;
}
_startTime = saleStartTime;
_endTime = saleEndTime;
_minimumAmount = saleMinimumAmount;
_saleId = saleId;
_whitelistFlag = whitelistFlag;
}
/**
* @dev Owner can set token price
* @param _tokenPrice price of 1 Token
*/
function setTokenPrice(
uint256 _tokenPrice
) external onlyOwner returns(bool){
tokenPrice = _tokenPrice;
return true;
}
/**
* @dev Get token price
*/
function getTokenPrice() external view returns(uint256){
return tokenPrice;
}
/* ----------------------------------------------------------------------------
* Functions for Additional Business Logic For Users
* ----------------------------------------------------------------------------
*/
modifier checkSaleValidations(address _userAddress, uint256 _value){
if(whitelistFlag == true){
require(_whitelistedAddress[_userAddress] == true, "Address not Whitelisted" );
require(_value <= saleMaximumAmount.mul(_multiplier[_userAddress]), "Total amount should be less than maximum limit");
require(_thisSaleContribution[_userAddress][saleId].add(_value) <= saleMaximumAmount.mul(_multiplier[_userAddress]), "Total amount should be less than maximum limit");
}
else{
require(_thisSaleContribution[_userAddress][saleId].add(_value) <= saleMaximumAmount, "Total amount should be less than maximum limit");
}
require(saleStartTime < block.timestamp , "Sale not started");
require(saleEndTime > block.timestamp, "Sale Ended");
require(_contributionBNB[_userAddress].add(_value) >= saleMinimumAmount, "Total amount should be more than minimum limit");
require(_value <= IDOAvailable, "Hard Cap Reached");
_;
}
//Check the expected amount per bnb
function checkTokensExpected(uint256 _value) view external returns(uint256){
return _value.mul(tokenPrice).div(decimalBalancer);
}
/*
* @dev Get Purchaseable amount
*/
function getPurchaseableTokens() external view returns(uint256){
return hardCap;
}
/*
* @dev Buy New tokens from the sale
*/
function buyTokens() payable external returns(bool){
return true;
}
/*
* @dev Internal function to achieve
*/
function _trasferInLockingState(
address[] userAddress,
uint256[] amountTransfer,
uint256[] bnb
) external onlyOwner returns(bool){
uint256 count = userAddress.length;
require(count < 201, "Array Overflow"); //Max 200 enteries at a time
for (uint256 i = 0; i < count; i++){
uint256 _bnb = bnb[i];
address _userAddress = userAddress[i];
uint256 _amountTransfer = amountTransfer[i];
_recordSale[_userAddress] = _amountTransfer;
_finalSoldAmount[_userAddress] = _amountTransfer;
_contributionBNB[_userAddress] = _bnb;
_thisSaleContribution[_userAddress][saleId] = _thisSaleContribution[_userAddress][saleId].add(_bnb);
IDOAvailable = IDOAvailable.sub(_amountTransfer);
}
return true;
}
/*
* @dev Owner can set hard cap for IDO
*/
function setIDOavailable(uint256 _IDOHardCap) external onlyOwner returns(bool){
require(_IDOHardCap <= balanceOf(address(this)) && _IDOHardCap > 0, "Value should not be more than IDO balance and greater than 0" );
hardCap = _IDOHardCap;
IDOAvailable = _IDOHardCap;
return true;
}
/*
* @dev Claim Purchased token by lock number
*/
function claimPurchasedTokens(uint256 _lockNumber) external validateClaim(msg.sender,_lockNumber) returns (bool){
uint256 calculation = (_finalSoldAmount[msg.sender]).div(2);
iMainToken.transfer(msg.sender,calculation);
_recordSale[msg.sender] = _recordSale[msg.sender].sub(calculation);
reEntrance[msg.sender][_lockNumber] = true;
_claimedByUser[msg.sender][_lockNumber] = calculation;
}
//validate claim tokens
modifier validateClaim(address _userAddress, uint256 _lockNumber)
{
require(_recordSale[_userAddress] > 0, "Not sufficient purchase Balance");
require(_lockNumber == 1 || _lockNumber == 2, "Invalid Lock Number");
if(_lockNumber == 1){ //Users will be able to withdraw tokens only after 1.5 hours of end time
require(block.timestamp > saleEndTime + _claimTime1 && reEntrance[_userAddress][_lockNumber] != true, "Insufficient Unlocked Tokens");
}
if(_lockNumber == 2){ // 1 month
require(block.timestamp > saleEndTime + _claimTime1 + 2629743 && reEntrance[_userAddress][_lockNumber] != true , "Insufficient Unlocked Tokens");
}
_;
}
/*
* @dev Check if the user address is whitelisted or not
*/
function checkWhitelistedAddress(address _userAddress) view external returns(bool){
require(_userAddress != address(0), "addresses should not be 0");
return _whitelistedAddress[_userAddress];
}
/*
* @dev Check all locking addresses
*/
modifier checkLockedAddresses(address _lockedAddresses){
require(_addressLocked[_lockedAddresses] != true, "Locking Address");
_;
}
/*
* @dev Admin can withdraw the bnb
*/
function withdrawCurrency(uint256 _amount) external onlyOwner returns(bool){
msg.sender.transfer(_amount);
return true;
}
/*
* @dev Get user tokens by address
*/
function getUserTokensByAdd(address _userAddress) external view returns(uint256 _div1, uint256 _div2, uint256 _div3, uint256 _div4, uint256 _div5){
uint256 division = _finalSoldAmount[_userAddress].div(2);
_div1 = division;
_div2 = division;
_div3 = 0;
_div4 = 0;
_div5 = 0;
if(reEntrance[_userAddress][1] == true){
_div1 = 0;
}
if(reEntrance[_userAddress][2] == true){
_div2 = 0;
}
if(reEntrance[_userAddress][3] == true){
_div3 = 0;
}
if(reEntrance[_userAddress][4] == true){
_div4 = 0;
}
if(reEntrance[_userAddress][5] == true){
_div5 = 0;
}
return(_div1,_div2,_div3,_div4,_div5);
}
/*
* @dev Get contract BNb balance to display
*/
function checkContractBNBBalance() external view returns(uint256){
return address(this).balance;
}
//get sold status
function getSoldStatus() external view returns(uint256 _totalAvailable, uint256 _currentAvailable){
_totalAvailable = hardCap;
_currentAvailable = IDOAvailable;
}
function getAmountPurchased(address _userAddress) external view returns(uint256 _contribution, uint256 _allocation){
_contribution = _contributionBNB[_userAddress];
_allocation = _finalSoldAmount[_userAddress];
}
//check contract block.timestamp time
function checkContractTime() external view returns(uint256){
return block.timestamp;
}
function getClaimDates() view external returns(uint256 _d1, uint256 _d2, uint256 _d3, uint256 _d4, uint256 _d5){
_d1 = saleEndTime + _claimTime1;
_d2 = saleEndTime + _claimTime1 + 2629743;
_d3 = 0;
_d4 = 0;
_d5 = 0;
return(_d1, _d2, _d3, _d4,_d5);
}
/*
* @dev Get claimed tokens by user address
*/
function getClaimedTokensHistory(address _userAddress) view external returns(uint256 r1,uint256 r2, uint256 r3, uint256 r4, uint256 r5){
r1 = _claimedByUser[_userAddress][1];
r2 = _claimedByUser[_userAddress][2];
r3 = 0;
r4 = 0;
r5 = 0;
return(r1, r2, r3, r4, r5);
}
/*
* @dev Set bnb price to display per token
*/
function setViewPricePerToken(uint256 _price) external onlyOwner returns(bool){
pricePerToken = _price;
return true;
}
/*
* @dev Get BNB price per token to display
*/
function getViewPricePerToken() view external returns(uint256){
return pricePerToken;
}
function setclaimTime1(uint256 claimTime1) external onlyOwner returns(bool){
_claimTime1 = claimTime1;
return true;
}
function getclaimTime1() view external returns(uint256){
return _claimTime1;
}
function withdrawPeningTokens(uint256 _amount) external view onlyOwner returns(bool){
iMainToken.transfer(msg.sender, _amount);
return true;
}
} | Total number of tokens in existence./ | function totalSupply() external view returns (uint256) {
return _totalSupply;
}
| 10,973,997 |
./full_match/1/0x7af62458e41E2F490D2Df54A8FeDc56fFedB8c17/sources/lib/solady/src/utils/LibSort.sol | Returns whether the array is sorted in ascending order. | function isSorted(uint256[] memory a) internal pure returns (bool result) {
assembly {
result := 1
if iszero(lt(mload(a), 2)) {
let end := add(a, shl(5, mload(a)))
let p := mload(a)
a := add(a, 0x20)
result := iszero(gt(p, mload(a)))
}
}
assembly {
result := 1
if iszero(lt(mload(a), 2)) {
let end := add(a, shl(5, mload(a)))
let p := mload(a)
a := add(a, 0x20)
result := iszero(gt(p, mload(a)))
}
}
for { a := add(a, 0x20) } 1 {} {
if iszero(mul(result, xor(a, end))) { break }
}
| 3,202,933 |
// SPDX-License-Identifier: MIT
//** Meliora Crowfunding Contract*/
//** Author Alex Hong : Meliora Finance 2021.5 */
pragma solidity 0.6.6;
pragma experimental ABIEncoderV2;
import "./libraries/Ownable.sol";
contract MelioraInfo is Ownable {
uint256 private devFeePercentage = 1;
uint256 private minDevFeeInWei = 1 ether;
address[] private launchpadAddresses;
/**
*
* @dev add launchpage adress to the pool
*
*/
function addLaunchpadAddress(address _launchapd)
external
returns (uint256)
{
launchpadAddresses.push(_launchapd);
return launchpadAddresses.length - 1;
}
/**
*
* @dev get launchpad count
*
*/
function getLaunchpadCount() external view returns (uint256) {
return launchpadAddresses.length;
}
/**
*
* @dev get launchpad address
*
*/
function getLaunchpadAddress(uint256 launchId)
external
view
returns (address)
{
return launchpadAddresses[launchId];
}
/**
*
* @dev get allocated percentage
*
*/
function getDevFeePercentage() external view returns (uint256) {
return devFeePercentage;
}
/**
*
* @dev set custom fee percent
*
*/
function setDevFeePercentage(uint256 _devFeePercentage) external onlyOwner {
devFeePercentage = _devFeePercentage;
}
/**
*
* @dev get minimum dev fee
*
*/
function getMinDevFeeInWei() external view returns (uint256) {
return minDevFeeInWei;
}
/**
*
* @dev set minimum dev fee
*
*/
function setMinDevFeeInWei(uint256 _minDevFeeInWei) external onlyOwner {
minDevFeeInWei = _minDevFeeInWei;
}
}
| get launchpad count/ | function getLaunchpadCount() external view returns (uint256) {
return launchpadAddresses.length;
}
| 5,521,937 |
pragma solidity ^0.4.18;
// File: contracts/UidCheckerInterface.sol
interface UidCheckerInterface {
function isUid(
string _uid
)
public
pure returns (bool);
}
// 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 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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2Ο.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(this.balance));
}
}
// File: contracts/Datastore.sol
/**
* @title Store
* @author Francesco Sullo <[email protected]>
* @dev It store the tweedentities related to the app
*/
contract Datastore
is HasNoEther
{
string public fromVersion = "1.0.0";
uint public appId;
string public appNickname;
uint public identities;
address public manager;
address public newManager;
UidCheckerInterface public checker;
struct Uid {
string lastUid;
uint lastUpdate;
}
struct Address {
address lastAddress;
uint lastUpdate;
}
mapping(string => Address) internal __addressByUid;
mapping(address => Uid) internal __uidByAddress;
bool public appSet;
// events
event AppSet(
string appNickname,
uint appId,
address checker
);
event ManagerSet(
address indexed manager,
bool isNew
);
event ManagerSwitch(
address indexed oldManager,
address indexed newManager
);
event IdentitySet(
address indexed addr,
string uid
);
event IdentityUnset(
address indexed addr,
string uid
);
// modifiers
modifier onlyManager() {
require(msg.sender == manager || (newManager != address(0) && msg.sender == newManager));
_;
}
modifier whenAppSet() {
require(appSet);
_;
}
// config
/**
* @dev Updates the checker for the store
* @param _address Checker's address
*/
function setNewChecker(
address _address
)
external
onlyOwner
{
require(_address != address(0));
checker = UidCheckerInterface(_address);
}
/**
* @dev Sets the manager
* @param _address Manager's address
*/
function setManager(
address _address
)
external
onlyOwner
{
require(_address != address(0));
manager = _address;
ManagerSet(_address, false);
}
/**
* @dev Sets new manager
* @param _address New manager's address
*/
function setNewManager(
address _address
)
external
onlyOwner
{
require(_address != address(0) && manager != address(0));
newManager = _address;
ManagerSet(_address, true);
}
/**
* @dev Sets new manager
*/
function switchManagerAndRemoveOldOne()
external
onlyOwner
{
require(newManager != address(0));
ManagerSwitch(manager, newManager);
manager = newManager;
newManager = address(0);
}
/**
* @dev Sets the app
* @param _appNickname Nickname (e.g. twitter)
* @param _appId ID (e.g. 1)
*/
function setApp(
string _appNickname,
uint _appId,
address _checker
)
external
onlyOwner
{
require(!appSet);
require(_appId > 0);
require(_checker != address(0));
require(bytes(_appNickname).length > 0);
appId = _appId;
appNickname = _appNickname;
checker = UidCheckerInterface(_checker);
appSet = true;
AppSet(_appNickname, _appId, _checker);
}
// helpers
/**
* @dev Checks if a tweedentity is upgradable
* @param _address The address
* @param _uid The user-id
*/
function isUpgradable(
address _address,
string _uid
)
public
constant returns (bool)
{
if (__addressByUid[_uid].lastAddress != address(0)) {
return keccak256(getUid(_address)) == keccak256(_uid);
}
return true;
}
// primary methods
/**
* @dev Sets a tweedentity
* @param _address The address of the wallet
* @param _uid The user-id of the owner user account
*/
function setIdentity(
address _address,
string _uid
)
external
onlyManager
whenAppSet
{
require(_address != address(0));
require(isUid(_uid));
require(isUpgradable(_address, _uid));
if (bytes(__uidByAddress[_address].lastUid).length > 0) {
// if _address is associated with an oldUid,
// this removes the association between _address and oldUid
__addressByUid[__uidByAddress[_address].lastUid] = Address(address(0), __addressByUid[__uidByAddress[_address].lastUid].lastUpdate);
identities--;
}
__uidByAddress[_address] = Uid(_uid, now);
__addressByUid[_uid] = Address(_address, now);
identities++;
IdentitySet(_address, _uid);
}
/**
* @dev Unset a tweedentity
* @param _address The address of the wallet
*/
function unsetIdentity(
address _address
)
external
onlyManager
whenAppSet
{
require(_address != address(0));
require(bytes(__uidByAddress[_address].lastUid).length > 0);
string memory uid = __uidByAddress[_address].lastUid;
__uidByAddress[_address] = Uid('', __uidByAddress[_address].lastUpdate);
__addressByUid[uid] = Address(address(0), __addressByUid[uid].lastUpdate);
identities--;
IdentityUnset(_address, uid);
}
// getters
/**
* @dev Returns the keccak256 of the app nickname
*/
function getAppNickname()
external
whenAppSet
constant returns (bytes32) {
return keccak256(appNickname);
}
/**
* @dev Returns the appId
*/
function getAppId()
external
whenAppSet
constant returns (uint) {
return appId;
}
/**
* @dev Returns the user-id associated to a wallet
* @param _address The address of the wallet
*/
function getUid(
address _address
)
public
constant returns (string)
{
return __uidByAddress[_address].lastUid;
}
/**
* @dev Returns the address associated to a user-id
* @param _uid The user-id
*/
function getAddress(
string _uid
)
external
constant returns (address)
{
return __addressByUid[_uid].lastAddress;
}
/**
* @dev Returns the timestamp of last update by address
* @param _address The address of the wallet
*/
function getAddressLastUpdate(
address _address
)
external
constant returns (uint)
{
return __uidByAddress[_address].lastUpdate;
}
/**
* @dev Returns the timestamp of last update by user-id
* @param _uid The user-id
*/
function getUidLastUpdate(
string _uid
)
external
constant returns (uint)
{
return __addressByUid[_uid].lastUpdate;
}
// utils
function isUid(
string _uid
)
public
view
returns (bool)
{
return checker.isUid(_uid);
}
} | Sets the manager _address Manager's address/ | function setManager(
address _address
)
external
onlyOwner
{
require(_address != address(0));
manager = _address;
ManagerSet(_address, false);
}
| 1,782,737 |
pragma solidity >=0.8.0;
import "./interfaces/IStake.sol";
import "./Stake.sol";
import "./Base.sol";
contract StakeManager is Base {
event StakeCreated(
address indexed from,
address stakeToken,
address rewardToken,
address stake
);
event LibUpdated(address indexed newLib);
address[] public stakes;
address public lib;
constructor(address _config, address _lib) Base(_config) {
require(_lib != address(0), "lib address = 0");
lib = _lib;
}
/**
* @dev update stake library
*/
function updateLib(address _lib) external onlyCEO() {
require(_lib != address(0), "lib address = 0");
lib = _lib;
emit LibUpdated(_lib);
}
/**
* @dev return number of stake
*/
function stakeCount() external view returns (uint256) {
return stakes.length;
}
/**
* @dev return array of all stake contracts
* @return array of stakes
*/
function allStakes() external view returns (address[] memory) {
return stakes;
}
/**
* @dev claim rewards of sepcified address of stakes
*/
function claims(address[] calldata _stakes) external {
for (uint256 i; i < _stakes.length; i++) {
IStake(_stakes[i]).claim0(msg.sender);
}
}
/**
* @dev create a new stake contract
* @param _stakeToken address of stakeable token
* @param _startDate epoch seconds of mining start
* @param _endDate epoch seconds of mining complete
* @param _totalReward reward total
*/
function createStake(
address _stakeToken,
uint256 _startDate,
uint256 _endDate,
uint256 _totalReward
) external onlyCEO() {
require(_stakeToken != address(0), "zero address");
require(_endDate > _startDate, "_endDate <= _startDate");
address rewardToken = config.protocolToken();
address stakeAddress = clone(lib);
IStake(stakeAddress).initialize(
_stakeToken,
rewardToken,
_startDate,
_endDate,
_totalReward
);
TransferHelper.safeTransferFrom(
rewardToken,
msg.sender,
stakeAddress,
_totalReward
);
stakes.push(stakeAddress);
emit StakeCreated(msg.sender, _stakeToken, rewardToken, stakeAddress);
config.notify(IConfig.EventType.STAKE_CREATED, stakeAddress);
}
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(
ptr,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(
add(ptr, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
}
pragma solidity >=0.8.0;
interface IStake {
function claim0(address _owner) external;
function initialize(
address stakeToken,
address rewardToken,
uint256 start,
uint256 end,
uint256 rewardPerBlock
) external;
}
pragma solidity >=0.8.0;
import "./interfaces/IERC20.sol";
import "./interfaces/IConfig.sol";
import "./interfaces/IStake.sol";
import "./libs/TransferHelper.sol";
interface IConfigable {
function getConfig() external returns (IConfig);
}
contract Stake is IStake {
event StakeUpdated(
address indexed staker,
bool isIncrease,
uint256 stakeChanged,
uint256 stakeAmount
);
event Claimed(address indexed staker, uint256 reward);
// stake token address, ERC20
address public stakeToken;
bool initialized;
bool locker;
// reward token address, ERC20
address public rewardToken;
// Mining start date(epoch second)
uint256 public startDateOfMining;
// Mining end date(epoch second)
uint256 public endDateOfMining;
// controller address
address controller;
// reward per Second
uint256 public rewardPerSecond;
// timestamp of last updated
uint256 public lastUpdatedTimestamp;
uint256 public rewardPerTokenStored;
// staked total
uint256 private _totalSupply;
struct StakerInfo {
// exclude reward's amount
uint256 rewardDebt;
// stake total
uint256 amount;
// pending reward
uint256 reward;
}
// staker's StakerInfo
mapping(address => StakerInfo) public stakers;
/* ========== MODIFIER ========== */
modifier stakeable() {
require(
block.timestamp <= endDateOfMining,
"stake not begin or complete"
);
_;
}
modifier enable() {
require(initialized, "initialized = false");
_;
}
modifier onlyController {
require(controller == msg.sender, "only controller");
_;
}
modifier lock() {
require(locker == false, "locked");
locker = true;
_;
locker = false;
}
modifier updateReward(address _staker) {
rewardPerTokenStored = rewardPerToken();
lastUpdatedTimestamp = lastTimeRewardApplicable();
if (_staker != address(0) && stakers[_staker].amount > 0) {
stakers[_staker].reward = rewardOf(_staker);
stakers[_staker].rewardDebt = rewardPerTokenStored;
}
_;
}
constructor() {}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev initialize contract
* @param _stake address of stake token
* @param _reward address of reward token
* @param _start epoch seconds of mining starts
* @param _end epoch seconds of mining complete
* @param _totalReward totalReward
*/
function initialize(
address _stake,
address _reward,
uint256 _start,
uint256 _end,
uint256 _totalReward
) external override {
require(!initialized, "initialized = true");
// only initialize once
initialized = true;
controller = msg.sender;
stakeToken = _stake;
rewardToken = _reward;
startDateOfMining = _start;
endDateOfMining = _end;
rewardPerSecond = _totalReward / (_end - _start + 1);
}
/**
* @dev stake token
* @param _amount amount of token to be staked
*/
function stake(uint256 _amount)
external
enable()
lock()
updateReward(msg.sender)
{
require(_amount > 0, "amount = 0");
require(
block.timestamp <= endDateOfMining,
"stake not begin or complete"
);
_totalSupply += _amount;
stakers[msg.sender].amount += _amount;
TransferHelper.safeTransferFrom(
stakeToken,
msg.sender,
address(this),
_amount
);
emit StakeUpdated(
msg.sender,
true,
_amount,
stakers[msg.sender].amount
);
_notify();
}
/**
* @dev unstake token
* @param _amount amount of token to be unstaked
*/
function unstake(uint256 _amount)
public
enable()
lock()
updateReward(msg.sender)
{
require(_amount > 0, "amount = 0");
require(stakers[msg.sender].amount >= _amount, "insufficient amount");
_claim(msg.sender);
_totalSupply -= _amount;
stakers[msg.sender].amount -= _amount;
TransferHelper.safeTransfer(stakeToken, msg.sender, _amount);
emit StakeUpdated(
msg.sender,
false,
_amount,
stakers[msg.sender].amount
);
_notify();
}
/**
* @dev claim rewards
*/
function claim() external enable() lock() updateReward(msg.sender) {
_claim(msg.sender);
}
/**
* @dev quit, claim reward + unstake all
*/
function quit() external enable() lock() updateReward(msg.sender) {
unstake(stakers[msg.sender].amount);
_claim(msg.sender);
}
/**
* @dev claim rewards, only owner allowed
* @param _staker staker address
*/
function claim0(address _staker)
external
override
onlyController()
enable()
updateReward(msg.sender)
{
_claim(_staker);
}
/* ========== VIEWs ========== */
function lastTimeRewardApplicable() public view returns (uint256) {
if (block.timestamp < startDateOfMining) return startDateOfMining;
return
block.timestamp > endDateOfMining
? endDateOfMining
: block.timestamp;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0 || block.timestamp < startDateOfMining) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
(((lastTimeRewardApplicable() - lastUpdatedTimestamp) *
rewardPerSecond) * 1e18) /
_totalSupply;
}
/**
* @dev amount of stake per address
* @param _staker staker address
* @return amount of stake
*/
function stakeOf(address _staker) external view returns (uint256) {
return stakers[_staker].amount;
}
/**
* @dev amount of reward per address
* @param _staker address
* @return value reward amount of _staker
*/
function rewardOf(address _staker) public view returns (uint256 value) {
StakerInfo memory info = stakers[_staker];
return
(info.amount * (rewardPerToken() - info.rewardDebt)) /
1e18 +
info.reward;
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev claim reward
* @param _staker address
*/
function _claim(address _staker) private {
uint256 reward = stakers[_staker].reward;
if (reward > 0) {
stakers[_staker].reward = 0;
IConfig config = IConfigable(controller).getConfig();
uint256 claimFeeRate = config.claimFeeRate();
uint256 out = (reward * (10000 - claimFeeRate)) / 10000;
uint256 fee = reward - out;
TransferHelper.safeTransfer(rewardToken, _staker, out);
if (fee > 0) {
// transfer to feeTo
TransferHelper.safeTransfer(rewardToken, config.feeTo(), fee);
}
emit Claimed(_staker, reward);
_notify();
}
}
function _notify() private {
IConfigable(controller).getConfig().notify(
IConfig.EventType.STAKE_UPDATED,
address(this)
);
}
}
pragma solidity >=0.8.0;
import "./interfaces/IConfig.sol";
contract Base {
event ConfigUpdated(address indexed owner, address indexed config);
IConfig internal config;
modifier onlyCEO() {
require(msg.sender == config.ceo(), "only CEO");
_;
}
constructor(address _configAddr) {
require(_configAddr != address(0), "config address = 0");
config = IConfig(_configAddr);
}
function updateConfig(address _config) external onlyCEO() {
require(_config != address(0), "config address = 0");
require(address(config) != _config, "address identical");
config = IConfig(_config);
emit ConfigUpdated(msg.sender, _config);
}
function configAddress() external view returns (address) {
return address(config);
}
function getConfig() external view returns (IConfig) {
return config;
}
}
pragma solidity >=0.8.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) 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);
}
pragma solidity >=0.8.0;
interface IConfig {
enum EventType {FUND_CREATED, FUND_UPDATED, STAKE_CREATED, STAKE_UPDATED, REG_CREATED, REG_UPDATED, PFUND_CREATED, PFUND_UPDATED}
function ceo() external view returns (address);
function protocolPool() external view returns (address);
function protocolToken() external view returns (address);
function feeTo() external view returns (address);
function nameRegistry() external view returns (address);
// function investTokenWhitelist() external view returns (address[] memory);
function tokenMinFundSize(address token) external view returns (uint256);
function investFeeRate() external view returns (uint256);
function redeemFeeRate() external view returns (uint256);
function claimFeeRate() external view returns (uint256);
function poolCreationRate() external view returns (uint256);
function slot0() external view returns (uint256);
function slot1() external view returns (uint256);
function slot2() external view returns (uint256);
function slot3() external view returns (uint256);
function slot4() external view returns (uint256);
function notify(EventType _type, address _src) external;
}
pragma solidity >=0.8.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper: APPROVE_FAILED'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper: TRANSFER_FAILED'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper: TRANSFER_FROM_FAILED'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
| quit, claim reward + unstake all/ | function quit() external enable() lock() updateReward(msg.sender) {
unstake(stakers[msg.sender].amount);
_claim(msg.sender);
}
| 1,534,146 |
./partial_match/1/0x1b9301A08Fa97a7d6646AFb58BfE93c3927bad26/sources/BACStaking.sol | return userBlanaces[_owner].values(); Return an empty array | function userStakedNFT(address _owner) public view returns(uint256[] memory){
uint256 tokenCount = userBlanaces[_owner].length();
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
| 2,717,143 |
pragma solidity ^0.4.19;
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
function getBeneficiary() external view returns(address);
}
contract SanctuaryInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isSanctuary() public pure returns (bool);
/// @dev generate new warrior genes
/// @param _heroGenes Genes of warrior that have completed dungeon
/// @param _heroLevel Level of the warrior
/// @return the genes that are supposed to be passed down to newly arisen warrior
function generateWarrior(uint256 _heroGenes, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) public returns (uint256);
}
contract PVPInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isPVPProvider() external pure returns (bool);
function addTournamentContender(address _owner, uint256[] _tournamentData) external payable;
function getTournamentThresholdFee() public view returns(uint256);
function addPVPContender(address _owner, uint256 _packedWarrior) external payable;
function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256);
}
contract PVPListenerInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isPVPListener() public pure returns (bool);
function getBeneficiary() external view returns(address);
function pvpFinished(uint256[] warriorData, uint256 matchingCount) public;
function pvpContenderRemoved(uint256 _warriorId) public;
function tournamentFinished(uint256[] packedContenders) public;
}
contract PermissionControll {
// This facet controls access to contract that implements it. There are four roles managed here:
//
// - The Admin: The Admin can reassign admin and issuer roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the CryptoWarriorCore constructor.
//
// - The Bank: The Bank can withdraw funds from CryptoWarriorCore and its auction and battle contracts, and change admin role.
//
// - The Issuer: The Issuer can release gen0 warriors to auction.
//
// / @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public adminAddress;
address public bankAddress;
address public issuerAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
// / @dev Access modifier for Admin-only functionality
modifier onlyAdmin(){
require(msg.sender == adminAddress);
_;
}
// / @dev Access modifier for Bank-only functionality
modifier onlyBank(){
require(msg.sender == bankAddress);
_;
}
/// @dev Access modifier for Issuer-only functionality
modifier onlyIssuer(){
require(msg.sender == issuerAddress);
_;
}
modifier onlyAuthorized(){
require(msg.sender == issuerAddress ||
msg.sender == adminAddress ||
msg.sender == bankAddress);
_;
}
// / @dev Assigns a new address to act as the Bank. Only available to the current Bank.
// / @param _newBank The address of the new Bank
function setBank(address _newBank) external onlyBank {
require(_newBank != address(0));
bankAddress = _newBank;
}
// / @dev Assigns a new address to act as the Admin. Only available to the current Admin.
// / @param _newAdmin The address of the new Admin
function setAdmin(address _newAdmin) external {
require(msg.sender == adminAddress || msg.sender == bankAddress);
require(_newAdmin != address(0));
adminAddress = _newAdmin;
}
// / @dev Assigns a new address to act as the Issuer. Only available to the current Issuer.
// / @param _newIssuer The address of the new Issuer
function setIssuer(address _newIssuer) external onlyAdmin{
require(_newIssuer != address(0));
issuerAddress = _newIssuer;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
// / @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused(){
require(!paused);
_;
}
// / @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused{
require(paused);
_;
}
// / @dev Called by any "Authorized" role to pause the contract. Used only when
// / a bug or exploit is detected and we need to limit damage.
function pause() external onlyAuthorized whenNotPaused{
paused = true;
}
// / @dev Unpauses the smart contract. Can only be called by the Admin.
// / @notice This is public rather than external so it can be called by
// / derived contracts.
function unpause() public onlyAdmin whenPaused{
// can't unpause if contract was upgraded
paused = false;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyAdmin whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
}
contract Ownable {
address public owner;
/**
* @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{
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract PausableBattle is Ownable {
event PausePVP(bool paused);
event PauseTournament(bool paused);
bool public pvpPaused = false;
bool public tournamentPaused = false;
/** PVP */
modifier PVPNotPaused(){
require(!pvpPaused);
_;
}
modifier PVPPaused{
require(pvpPaused);
_;
}
function pausePVP() public onlyOwner PVPNotPaused {
pvpPaused = true;
PausePVP(true);
}
function unpausePVP() public onlyOwner PVPPaused {
pvpPaused = false;
PausePVP(false);
}
/** Tournament */
modifier TournamentNotPaused(){
require(!tournamentPaused);
_;
}
modifier TournamentPaused{
require(tournamentPaused);
_;
}
function pauseTournament() public onlyOwner TournamentNotPaused {
tournamentPaused = true;
PauseTournament(true);
}
function unpauseTournament() public onlyOwner TournamentPaused {
tournamentPaused = false;
PauseTournament(false);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused(){
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused{
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
Unpause();
}
}
library CryptoUtils {
/* CLASSES */
uint256 internal constant WARRIOR = 0;
uint256 internal constant ARCHER = 1;
uint256 internal constant MAGE = 2;
/* RARITIES */
uint256 internal constant COMMON = 1;
uint256 internal constant UNCOMMON = 2;
uint256 internal constant RARE = 3;
uint256 internal constant MYTHIC = 4;
uint256 internal constant LEGENDARY = 5;
uint256 internal constant UNIQUE = 6;
/* LIMITS */
uint256 internal constant CLASS_MECHANICS_MAX = 3;
uint256 internal constant RARITY_MAX = 6;
/*@dev range used for rarity chance computation */
uint256 internal constant RARITY_CHANCE_RANGE = 10000000;
uint256 internal constant POINTS_TO_LEVEL = 10;
/* ATTRIBUTE MASKS */
/*@dev range 0-9999 */
uint256 internal constant UNIQUE_MASK_0 = 1;
/*@dev range 0-9 */
uint256 internal constant RARITY_MASK_1 = UNIQUE_MASK_0 * 10000;
/*@dev range 0-999 */
uint256 internal constant CLASS_VIEW_MASK_2 = RARITY_MASK_1 * 10;
/*@dev range 0-999 */
uint256 internal constant BODY_COLOR_MASK_3 = CLASS_VIEW_MASK_2 * 1000;
/*@dev range 0-999 */
uint256 internal constant EYES_MASK_4 = BODY_COLOR_MASK_3 * 1000;
/*@dev range 0-999 */
uint256 internal constant MOUTH_MASK_5 = EYES_MASK_4 * 1000;
/*@dev range 0-999 */
uint256 internal constant HEIR_MASK_6 = MOUTH_MASK_5 * 1000;
/*@dev range 0-999 */
uint256 internal constant HEIR_COLOR_MASK_7 = HEIR_MASK_6 * 1000;
/*@dev range 0-999 */
uint256 internal constant ARMOR_MASK_8 = HEIR_COLOR_MASK_7 * 1000;
/*@dev range 0-999 */
uint256 internal constant WEAPON_MASK_9 = ARMOR_MASK_8 * 1000;
/*@dev range 0-999 */
uint256 internal constant HAT_MASK_10 = WEAPON_MASK_9 * 1000;
/*@dev range 0-99 */
uint256 internal constant RUNES_MASK_11 = HAT_MASK_10 * 1000;
/*@dev range 0-99 */
uint256 internal constant WINGS_MASK_12 = RUNES_MASK_11 * 100;
/*@dev range 0-99 */
uint256 internal constant PET_MASK_13 = WINGS_MASK_12 * 100;
/*@dev range 0-99 */
uint256 internal constant BORDER_MASK_14 = PET_MASK_13 * 100;
/*@dev range 0-99 */
uint256 internal constant BACKGROUND_MASK_15 = BORDER_MASK_14 * 100;
/*@dev range 0-99 */
uint256 internal constant INTELLIGENCE_MASK_16 = BACKGROUND_MASK_15 * 100;
/*@dev range 0-99 */
uint256 internal constant AGILITY_MASK_17 = INTELLIGENCE_MASK_16 * 100;
/*@dev range 0-99 */
uint256 internal constant STRENGTH_MASK_18 = AGILITY_MASK_17 * 100;
/*@dev range 0-9 */
uint256 internal constant CLASS_MECH_MASK_19 = STRENGTH_MASK_18 * 100;
/*@dev range 0-999 */
uint256 internal constant RARITY_BONUS_MASK_20 = CLASS_MECH_MASK_19 * 10;
/*@dev range 0-9 */
uint256 internal constant SPECIALITY_MASK_21 = RARITY_BONUS_MASK_20 * 1000;
/*@dev range 0-99 */
uint256 internal constant DAMAGE_MASK_22 = SPECIALITY_MASK_21 * 10;
/*@dev range 0-99 */
uint256 internal constant AURA_MASK_23 = DAMAGE_MASK_22 * 100;
/*@dev 20 decimals left */
uint256 internal constant BASE_MASK_24 = AURA_MASK_23 * 100;
/* SPECIAL PERKS */
uint256 internal constant MINER_PERK = 1;
/* PARAM INDEXES */
uint256 internal constant BODY_COLOR_MAX_INDEX_0 = 0;
uint256 internal constant EYES_MAX_INDEX_1 = 1;
uint256 internal constant MOUTH_MAX_2 = 2;
uint256 internal constant HAIR_MAX_3 = 3;
uint256 internal constant HEIR_COLOR_MAX_4 = 4;
uint256 internal constant ARMOR_MAX_5 = 5;
uint256 internal constant WEAPON_MAX_6 = 6;
uint256 internal constant HAT_MAX_7 = 7;
uint256 internal constant RUNES_MAX_8 = 8;
uint256 internal constant WINGS_MAX_9 = 9;
uint256 internal constant PET_MAX_10 = 10;
uint256 internal constant BORDER_MAX_11 = 11;
uint256 internal constant BACKGROUND_MAX_12 = 12;
uint256 internal constant UNIQUE_INDEX_13 = 13;
uint256 internal constant LEGENDARY_INDEX_14 = 14;
uint256 internal constant MYTHIC_INDEX_15 = 15;
uint256 internal constant RARE_INDEX_16 = 16;
uint256 internal constant UNCOMMON_INDEX_17 = 17;
uint256 internal constant UNIQUE_TOTAL_INDEX_18 = 18;
/* PACK PVP DATA LOGIC */
//pvp data
uint256 internal constant CLASS_PACK_0 = 1;
uint256 internal constant RARITY_BONUS_PACK_1 = CLASS_PACK_0 * 10;
uint256 internal constant RARITY_PACK_2 = RARITY_BONUS_PACK_1 * 1000;
uint256 internal constant EXPERIENCE_PACK_3 = RARITY_PACK_2 * 10;
uint256 internal constant INTELLIGENCE_PACK_4 = EXPERIENCE_PACK_3 * 1000;
uint256 internal constant AGILITY_PACK_5 = INTELLIGENCE_PACK_4 * 100;
uint256 internal constant STRENGTH_PACK_6 = AGILITY_PACK_5 * 100;
uint256 internal constant BASE_DAMAGE_PACK_7 = STRENGTH_PACK_6 * 100;
uint256 internal constant PET_PACK_8 = BASE_DAMAGE_PACK_7 * 100;
uint256 internal constant AURA_PACK_9 = PET_PACK_8 * 100;
uint256 internal constant WARRIOR_ID_PACK_10 = AURA_PACK_9 * 100;
uint256 internal constant PVP_CYCLE_PACK_11 = WARRIOR_ID_PACK_10 * 10**10;
uint256 internal constant RATING_PACK_12 = PVP_CYCLE_PACK_11 * 10**10;
uint256 internal constant PVP_BASE_PACK_13 = RATING_PACK_12 * 10**10;//NB rating must be at the END!
//tournament data
uint256 internal constant HP_PACK_0 = 1;
uint256 internal constant DAMAGE_PACK_1 = HP_PACK_0 * 10**12;
uint256 internal constant ARMOR_PACK_2 = DAMAGE_PACK_1 * 10**12;
uint256 internal constant DODGE_PACK_3 = ARMOR_PACK_2 * 10**12;
uint256 internal constant PENETRATION_PACK_4 = DODGE_PACK_3 * 10**12;
uint256 internal constant COMBINE_BASE_PACK_5 = PENETRATION_PACK_4 * 10**12;
/* MISC CONSTANTS */
uint256 internal constant MAX_ID_SIZE = 10000000000;
int256 internal constant PRECISION = 1000000;
uint256 internal constant BATTLES_PER_CONTENDER = 10;//10x100
uint256 internal constant BATTLES_PER_CONTENDER_SUM = BATTLES_PER_CONTENDER * 100;//10x100
uint256 internal constant LEVEL_BONUSES = 98898174676155504541373431282523211917151413121110;
//ucommon bonuses
uint256 internal constant BONUS_NONE = 0;
uint256 internal constant BONUS_HP = 1;
uint256 internal constant BONUS_ARMOR = 2;
uint256 internal constant BONUS_CRIT_CHANCE = 3;
uint256 internal constant BONUS_CRIT_MULT = 4;
uint256 internal constant BONUS_PENETRATION = 5;
//rare bonuses
uint256 internal constant BONUS_STR = 6;
uint256 internal constant BONUS_AGI = 7;
uint256 internal constant BONUS_INT = 8;
uint256 internal constant BONUS_DAMAGE = 9;
//bonus value database,
uint256 internal constant BONUS_DATA = 16060606140107152000;
//pets database
uint256 internal constant PETS_DATA = 287164235573728325842459981692000;
uint256 internal constant PET_AURA = 2;
uint256 internal constant PET_PARAM_1 = 1;
uint256 internal constant PET_PARAM_2 = 0;
/* GETTERS */
function getUniqueValue(uint256 identity) internal pure returns(uint256){
return identity % RARITY_MASK_1;
}
function getRarityValue(uint256 identity) internal pure returns(uint256){
return (identity % CLASS_VIEW_MASK_2) / RARITY_MASK_1;
}
function getClassViewValue(uint256 identity) internal pure returns(uint256){
return (identity % BODY_COLOR_MASK_3) / CLASS_VIEW_MASK_2;
}
function getBodyColorValue(uint256 identity) internal pure returns(uint256){
return (identity % EYES_MASK_4) / BODY_COLOR_MASK_3;
}
function getEyesValue(uint256 identity) internal pure returns(uint256){
return (identity % MOUTH_MASK_5) / EYES_MASK_4;
}
function getMouthValue(uint256 identity) internal pure returns(uint256){
return (identity % HEIR_MASK_6) / MOUTH_MASK_5;
}
function getHairValue(uint256 identity) internal pure returns(uint256){
return (identity % HEIR_COLOR_MASK_7) / HEIR_MASK_6;
}
function getHairColorValue(uint256 identity) internal pure returns(uint256){
return (identity % ARMOR_MASK_8) / HEIR_COLOR_MASK_7;
}
function getArmorValue(uint256 identity) internal pure returns(uint256){
return (identity % WEAPON_MASK_9) / ARMOR_MASK_8;
}
function getWeaponValue(uint256 identity) internal pure returns(uint256){
return (identity % HAT_MASK_10) / WEAPON_MASK_9;
}
function getHatValue(uint256 identity) internal pure returns(uint256){
return (identity % RUNES_MASK_11) / HAT_MASK_10;
}
function getRunesValue(uint256 identity) internal pure returns(uint256){
return (identity % WINGS_MASK_12) / RUNES_MASK_11;
}
function getWingsValue(uint256 identity) internal pure returns(uint256){
return (identity % PET_MASK_13) / WINGS_MASK_12;
}
function getPetValue(uint256 identity) internal pure returns(uint256){
return (identity % BORDER_MASK_14) / PET_MASK_13;
}
function getBorderValue(uint256 identity) internal pure returns(uint256){
return (identity % BACKGROUND_MASK_15) / BORDER_MASK_14;
}
function getBackgroundValue(uint256 identity) internal pure returns(uint256){
return (identity % INTELLIGENCE_MASK_16) / BACKGROUND_MASK_15;
}
function getIntelligenceValue(uint256 identity) internal pure returns(uint256){
return (identity % AGILITY_MASK_17) / INTELLIGENCE_MASK_16;
}
function getAgilityValue(uint256 identity) internal pure returns(uint256){
return ((identity % STRENGTH_MASK_18) / AGILITY_MASK_17);
}
function getStrengthValue(uint256 identity) internal pure returns(uint256){
return ((identity % CLASS_MECH_MASK_19) / STRENGTH_MASK_18);
}
function getClassMechValue(uint256 identity) internal pure returns(uint256){
return (identity % RARITY_BONUS_MASK_20) / CLASS_MECH_MASK_19;
}
function getRarityBonusValue(uint256 identity) internal pure returns(uint256){
return (identity % SPECIALITY_MASK_21) / RARITY_BONUS_MASK_20;
}
function getSpecialityValue(uint256 identity) internal pure returns(uint256){
return (identity % DAMAGE_MASK_22) / SPECIALITY_MASK_21;
}
function getDamageValue(uint256 identity) internal pure returns(uint256){
return (identity % AURA_MASK_23) / DAMAGE_MASK_22;
}
function getAuraValue(uint256 identity) internal pure returns(uint256){
return ((identity % BASE_MASK_24) / AURA_MASK_23);
}
/* SETTERS */
function _setUniqueValue0(uint256 value) internal pure returns(uint256){
require(value < RARITY_MASK_1);
return value * UNIQUE_MASK_0;
}
function _setRarityValue1(uint256 value) internal pure returns(uint256){
require(value < (CLASS_VIEW_MASK_2 / RARITY_MASK_1));
return value * RARITY_MASK_1;
}
function _setClassViewValue2(uint256 value) internal pure returns(uint256){
require(value < (BODY_COLOR_MASK_3 / CLASS_VIEW_MASK_2));
return value * CLASS_VIEW_MASK_2;
}
function _setBodyColorValue3(uint256 value) internal pure returns(uint256){
require(value < (EYES_MASK_4 / BODY_COLOR_MASK_3));
return value * BODY_COLOR_MASK_3;
}
function _setEyesValue4(uint256 value) internal pure returns(uint256){
require(value < (MOUTH_MASK_5 / EYES_MASK_4));
return value * EYES_MASK_4;
}
function _setMouthValue5(uint256 value) internal pure returns(uint256){
require(value < (HEIR_MASK_6 / MOUTH_MASK_5));
return value * MOUTH_MASK_5;
}
function _setHairValue6(uint256 value) internal pure returns(uint256){
require(value < (HEIR_COLOR_MASK_7 / HEIR_MASK_6));
return value * HEIR_MASK_6;
}
function _setHairColorValue7(uint256 value) internal pure returns(uint256){
require(value < (ARMOR_MASK_8 / HEIR_COLOR_MASK_7));
return value * HEIR_COLOR_MASK_7;
}
function _setArmorValue8(uint256 value) internal pure returns(uint256){
require(value < (WEAPON_MASK_9 / ARMOR_MASK_8));
return value * ARMOR_MASK_8;
}
function _setWeaponValue9(uint256 value) internal pure returns(uint256){
require(value < (HAT_MASK_10 / WEAPON_MASK_9));
return value * WEAPON_MASK_9;
}
function _setHatValue10(uint256 value) internal pure returns(uint256){
require(value < (RUNES_MASK_11 / HAT_MASK_10));
return value * HAT_MASK_10;
}
function _setRunesValue11(uint256 value) internal pure returns(uint256){
require(value < (WINGS_MASK_12 / RUNES_MASK_11));
return value * RUNES_MASK_11;
}
function _setWingsValue12(uint256 value) internal pure returns(uint256){
require(value < (PET_MASK_13 / WINGS_MASK_12));
return value * WINGS_MASK_12;
}
function _setPetValue13(uint256 value) internal pure returns(uint256){
require(value < (BORDER_MASK_14 / PET_MASK_13));
return value * PET_MASK_13;
}
function _setBorderValue14(uint256 value) internal pure returns(uint256){
require(value < (BACKGROUND_MASK_15 / BORDER_MASK_14));
return value * BORDER_MASK_14;
}
function _setBackgroundValue15(uint256 value) internal pure returns(uint256){
require(value < (INTELLIGENCE_MASK_16 / BACKGROUND_MASK_15));
return value * BACKGROUND_MASK_15;
}
function _setIntelligenceValue16(uint256 value) internal pure returns(uint256){
require(value < (AGILITY_MASK_17 / INTELLIGENCE_MASK_16));
return value * INTELLIGENCE_MASK_16;
}
function _setAgilityValue17(uint256 value) internal pure returns(uint256){
require(value < (STRENGTH_MASK_18 / AGILITY_MASK_17));
return value * AGILITY_MASK_17;
}
function _setStrengthValue18(uint256 value) internal pure returns(uint256){
require(value < (CLASS_MECH_MASK_19 / STRENGTH_MASK_18));
return value * STRENGTH_MASK_18;
}
function _setClassMechValue19(uint256 value) internal pure returns(uint256){
require(value < (RARITY_BONUS_MASK_20 / CLASS_MECH_MASK_19));
return value * CLASS_MECH_MASK_19;
}
function _setRarityBonusValue20(uint256 value) internal pure returns(uint256){
require(value < (SPECIALITY_MASK_21 / RARITY_BONUS_MASK_20));
return value * RARITY_BONUS_MASK_20;
}
function _setSpecialityValue21(uint256 value) internal pure returns(uint256){
require(value < (DAMAGE_MASK_22 / SPECIALITY_MASK_21));
return value * SPECIALITY_MASK_21;
}
function _setDamgeValue22(uint256 value) internal pure returns(uint256){
require(value < (AURA_MASK_23 / DAMAGE_MASK_22));
return value * DAMAGE_MASK_22;
}
function _setAuraValue23(uint256 value) internal pure returns(uint256){
require(value < (BASE_MASK_24 / AURA_MASK_23));
return value * AURA_MASK_23;
}
/* WARRIOR IDENTITY GENERATION */
function _computeRunes(uint256 _rarity) internal pure returns (uint256){
return _rarity > UNCOMMON ? _rarity - UNCOMMON : 0;// 1 + _random(0, max, hash, WINGS_MASK_12, RUNES_MASK_11) : 0;
}
function _computeWings(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){
return _rarity > RARE ? 1 + _random(0, max, hash, PET_MASK_13, WINGS_MASK_12) : 0;
}
function _computePet(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){
return _rarity > MYTHIC ? 1 + _random(0, max, hash, BORDER_MASK_14, PET_MASK_13) : 0;
}
function _computeBorder(uint256 _rarity) internal pure returns (uint256){
return _rarity >= COMMON ? _rarity - 1 : 0;
}
function _computeBackground(uint256 _rarity) internal pure returns (uint256){
return _rarity;
}
function _unpackPetData(uint256 index) internal pure returns(uint256){
return (PETS_DATA % (1000 ** (index + 1)) / (1000 ** index));
}
function _getPetBonus1(uint256 _pet) internal pure returns(uint256) {
return (_pet % (10 ** (PET_PARAM_1 + 1)) / (10 ** PET_PARAM_1));
}
function _getPetBonus2(uint256 _pet) internal pure returns(uint256) {
return (_pet % (10 ** (PET_PARAM_2 + 1)) / (10 ** PET_PARAM_2));
}
function _getPetAura(uint256 _pet) internal pure returns(uint256) {
return (_pet % (10 ** (PET_AURA + 1)) / (10 ** PET_AURA));
}
function _getBattleBonus(uint256 _setBonusIndex, uint256 _currentBonusIndex, uint256 _petData, uint256 _warriorAuras, uint256 _petAuras) internal pure returns(int256) {
int256 bonus = 0;
if (_setBonusIndex == _currentBonusIndex) {
bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION;
}
//add pet bonuses
if (_setBonusIndex == _getPetBonus1(_petData)) {
bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2;
}
if (_setBonusIndex == _getPetBonus2(_petData)) {
bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2;
}
//add warrior aura bonuses
if (isAuraSet(_warriorAuras, uint8(_setBonusIndex))) {//warriors receive half bonuses from auras
bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2;
}
//add pet aura bonuses
if (isAuraSet(_petAuras, uint8(_setBonusIndex))) {//pets receive full bonues from auras
bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION;
}
return bonus;
}
function _computeRarityBonus(uint256 _rarity, uint256 hash) internal pure returns (uint256){
if (_rarity == UNCOMMON) {
return 1 + _random(0, BONUS_PENETRATION, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20);
}
if (_rarity == RARE) {
return 1 + _random(BONUS_PENETRATION, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20);
}
if (_rarity >= MYTHIC) {
return 1 + _random(0, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20);
}
return BONUS_NONE;
}
function _computeAura(uint256 _rarity, uint256 hash) internal pure returns (uint256){
if (_rarity >= MYTHIC) {
return 1 + _random(0, BONUS_DAMAGE, hash, BASE_MASK_24, AURA_MASK_23);
}
return BONUS_NONE;
}
function _computeRarity(uint256 _reward, uint256 _unique, uint256 _legendary,
uint256 _mythic, uint256 _rare, uint256 _uncommon) internal pure returns(uint256){
uint256 range = _unique + _legendary + _mythic + _rare + _uncommon;
if (_reward >= range) return COMMON; // common
if (_reward >= (range = (range - _uncommon))) return UNCOMMON;
if (_reward >= (range = (range - _rare))) return RARE;
if (_reward >= (range = (range - _mythic))) return MYTHIC;
if (_reward >= (range = (range - _legendary))) return LEGENDARY;
if (_reward < range) return UNIQUE;
return COMMON;
}
function _computeUniqueness(uint256 _rarity, uint256 nextUnique) internal pure returns (uint256){
return _rarity == UNIQUE ? nextUnique : 0;
}
/* identity packing */
/* @returns bonus value which depends on speciality value,
* if speciality == 1 (miner), then bonus value will be equal 4,
* otherwise 1
*/
function _getBonus(uint256 identity) internal pure returns(uint256){
return getSpecialityValue(identity) == MINER_PERK ? 4 : 1;
}
function _computeAndSetBaseParameters16_18_22(uint256 _hash) internal pure returns (uint256, uint256){
uint256 identity = 0;
uint256 damage = 35 + _random(0, 21, _hash, AURA_MASK_23, DAMAGE_MASK_22);
uint256 strength = 45 + _random(0, 26, _hash, CLASS_MECH_MASK_19, STRENGTH_MASK_18);
uint256 agility = 15 + (125 - damage - strength);
uint256 intelligence = 155 - strength - agility - damage;
(strength, agility, intelligence) = _shuffleParams(strength, agility, intelligence, _hash);
identity += _setStrengthValue18(strength);
identity += _setAgilityValue17(agility);
identity += _setIntelligenceValue16(intelligence);
identity += _setDamgeValue22(damage);
uint256 classMech = strength > agility ? (strength > intelligence ? WARRIOR : MAGE) : (agility > intelligence ? ARCHER : MAGE);
return (identity, classMech);
}
function _shuffleParams(uint256 param1, uint256 param2, uint256 param3, uint256 _hash) internal pure returns(uint256, uint256, uint256) {
uint256 temp = param1;
if (_hash % 2 == 0) {
temp = param1;
param1 = param2;
param2 = temp;
}
if ((_hash / 10 % 2) == 0) {
temp = param2;
param2 = param3;
param3 = temp;
}
if ((_hash / 100 % 2) == 0) {
temp = param1;
param1 = param2;
param2 = temp;
}
return (param1, param2, param3);
}
/* RANDOM */
function _random(uint256 _min, uint256 _max, uint256 _hash, uint256 _reminder, uint256 _devider) internal pure returns (uint256){
return ((_hash % _reminder) / _devider) % (_max - _min) + _min;
}
function _random(uint256 _min, uint256 _max, uint256 _hash) internal pure returns (uint256){
return _hash % (_max - _min) + _min;
}
function _getTargetBlock(uint256 _targetBlock) internal view returns(uint256){
uint256 currentBlock = block.number;
uint256 target = currentBlock - (currentBlock % 256) + (_targetBlock % 256);
if (target >= currentBlock) {
return (target - 256);
}
return target;
}
function _getMaxRarityChance() internal pure returns(uint256){
return RARITY_CHANCE_RANGE;
}
function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 specialPerc, uint32[19] memory params) internal view returns (uint256) {
_targetBlock = _getTargetBlock(_targetBlock);
uint256 identity;
uint256 hash = uint256(keccak256(block.blockhash(_targetBlock), _heroIdentity, block.coinbase, block.difficulty));
//0 _heroLevel produces warriors of COMMON rarity
uint256 rarityChance = _heroLevel == 0 ? RARITY_CHANCE_RANGE :
_random(0, RARITY_CHANCE_RANGE, hash) / (_heroLevel * _getBonus(_heroIdentity)); // 0 - 10 000 000
uint256 rarity = _computeRarity(rarityChance,
params[UNIQUE_INDEX_13],params[LEGENDARY_INDEX_14], params[MYTHIC_INDEX_15], params[RARE_INDEX_16], params[UNCOMMON_INDEX_17]);
uint256 classMech;
// start
(identity, classMech) = _computeAndSetBaseParameters16_18_22(hash);
identity += _setUniqueValue0(_computeUniqueness(rarity, params[UNIQUE_TOTAL_INDEX_18] + 1));
identity += _setRarityValue1(rarity);
identity += _setClassViewValue2(classMech); // 1 to 1 with classMech
identity += _setBodyColorValue3(1 + _random(0, params[BODY_COLOR_MAX_INDEX_0], hash, EYES_MASK_4, BODY_COLOR_MASK_3));
identity += _setEyesValue4(1 + _random(0, params[EYES_MAX_INDEX_1], hash, MOUTH_MASK_5, EYES_MASK_4));
identity += _setMouthValue5(1 + _random(0, params[MOUTH_MAX_2], hash, HEIR_MASK_6, MOUTH_MASK_5));
identity += _setHairValue6(1 + _random(0, params[HAIR_MAX_3], hash, HEIR_COLOR_MASK_7, HEIR_MASK_6));
identity += _setHairColorValue7(1 + _random(0, params[HEIR_COLOR_MAX_4], hash, ARMOR_MASK_8, HEIR_COLOR_MASK_7));
identity += _setArmorValue8(1 + _random(0, params[ARMOR_MAX_5], hash, WEAPON_MASK_9, ARMOR_MASK_8));
identity += _setWeaponValue9(1 + _random(0, params[WEAPON_MAX_6], hash, HAT_MASK_10, WEAPON_MASK_9));
identity += _setHatValue10(_random(0, params[HAT_MAX_7], hash, RUNES_MASK_11, HAT_MASK_10));//removed +1
identity += _setRunesValue11(_computeRunes(rarity));
identity += _setWingsValue12(_computeWings(rarity, params[WINGS_MAX_9], hash));
identity += _setPetValue13(_computePet(rarity, params[PET_MAX_10], hash));
identity += _setBorderValue14(_computeBorder(rarity)); // 1 to 1 with rarity
identity += _setBackgroundValue15(_computeBackground(rarity)); // 1 to 1 with rarity
identity += _setClassMechValue19(classMech);
identity += _setRarityBonusValue20(_computeRarityBonus(rarity, hash));
identity += _setSpecialityValue21(specialPerc); // currently only miner (1)
identity += _setAuraValue23(_computeAura(rarity, hash));
// end
return identity;
}
function _changeParameter(uint256 _paramIndex, uint32 _value, uint32[19] storage parameters) internal {
//we can change only view parameters, and unique count in max range <= 100
require(_paramIndex >= BODY_COLOR_MAX_INDEX_0 && _paramIndex <= UNIQUE_INDEX_13);
//we can NOT set pet, border and background values,
//those values have special logic behind them
require(
_paramIndex != RUNES_MAX_8 &&
_paramIndex != PET_MAX_10 &&
_paramIndex != BORDER_MAX_11 &&
_paramIndex != BACKGROUND_MAX_12
);
//value of bodyColor, eyes, mouth, hair, hairColor, armor, weapon, hat must be < 1000
require(_paramIndex > HAT_MAX_7 || _value < 1000);
//value of wings, must be < 100
require(_paramIndex > BACKGROUND_MAX_12 || _value < 100);
//check that max total number of UNIQUE warriors that we can emit is not > 100
require(_paramIndex != UNIQUE_INDEX_13 || (_value + parameters[UNIQUE_TOTAL_INDEX_18]) <= 100);
parameters[_paramIndex] = _value;
}
function _recordWarriorData(uint256 identity, uint32[19] storage parameters) internal {
uint256 rarity = getRarityValue(identity);
if (rarity == UNCOMMON) { // uncommon
parameters[UNCOMMON_INDEX_17]--;
return;
}
if (rarity == RARE) { // rare
parameters[RARE_INDEX_16]--;
return;
}
if (rarity == MYTHIC) { // mythic
parameters[MYTHIC_INDEX_15]--;
return;
}
if (rarity == LEGENDARY) { // legendary
parameters[LEGENDARY_INDEX_14]--;
return;
}
if (rarity == UNIQUE) { // unique
parameters[UNIQUE_INDEX_13]--;
parameters[UNIQUE_TOTAL_INDEX_18] ++;
return;
}
}
function _validateIdentity(uint256 _identity, uint32[19] memory params) internal pure returns(bool){
uint256 rarity = getRarityValue(_identity);
require(rarity <= UNIQUE);
require(
rarity <= COMMON ||//common
(rarity == UNCOMMON && params[UNCOMMON_INDEX_17] > 0) ||//uncommon
(rarity == RARE && params[RARE_INDEX_16] > 0) ||//rare
(rarity == MYTHIC && params[MYTHIC_INDEX_15] > 0) ||//mythic
(rarity == LEGENDARY && params[LEGENDARY_INDEX_14] > 0) ||//legendary
(rarity == UNIQUE && params[UNIQUE_INDEX_13] > 0)//unique
);
require(rarity != UNIQUE || getUniqueValue(_identity) > params[UNIQUE_TOTAL_INDEX_18]);
//check battle parameters
require(
getStrengthValue(_identity) < 100 &&
getAgilityValue(_identity) < 100 &&
getIntelligenceValue(_identity) < 100 &&
getDamageValue(_identity) <= 55
);
require(getClassMechValue(_identity) <= MAGE);
require(getClassMechValue(_identity) == getClassViewValue(_identity));
require(getSpecialityValue(_identity) <= MINER_PERK);
require(getRarityBonusValue(_identity) <= BONUS_DAMAGE);
require(getAuraValue(_identity) <= BONUS_DAMAGE);
//check view
require(getBodyColorValue(_identity) <= params[BODY_COLOR_MAX_INDEX_0]);
require(getEyesValue(_identity) <= params[EYES_MAX_INDEX_1]);
require(getMouthValue(_identity) <= params[MOUTH_MAX_2]);
require(getHairValue(_identity) <= params[HAIR_MAX_3]);
require(getHairColorValue(_identity) <= params[HEIR_COLOR_MAX_4]);
require(getArmorValue(_identity) <= params[ARMOR_MAX_5]);
require(getWeaponValue(_identity) <= params[WEAPON_MAX_6]);
require(getHatValue(_identity) <= params[HAT_MAX_7]);
require(getRunesValue(_identity) <= params[RUNES_MAX_8]);
require(getWingsValue(_identity) <= params[WINGS_MAX_9]);
require(getPetValue(_identity) <= params[PET_MAX_10]);
require(getBorderValue(_identity) <= params[BORDER_MAX_11]);
require(getBackgroundValue(_identity) <= params[BACKGROUND_MAX_12]);
return true;
}
/* UNPACK METHODS */
//common
function _unpackClassValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % RARITY_PACK_2 / CLASS_PACK_0);
}
function _unpackRarityBonusValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % RARITY_PACK_2 / RARITY_BONUS_PACK_1);
}
function _unpackRarityValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % EXPERIENCE_PACK_3 / RARITY_PACK_2);
}
function _unpackExpValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % INTELLIGENCE_PACK_4 / EXPERIENCE_PACK_3);
}
function _unpackLevelValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % INTELLIGENCE_PACK_4) / (EXPERIENCE_PACK_3 * POINTS_TO_LEVEL);
}
function _unpackIntelligenceValue(uint256 packedValue) internal pure returns(int256){
return int256(packedValue % AGILITY_PACK_5 / INTELLIGENCE_PACK_4);
}
function _unpackAgilityValue(uint256 packedValue) internal pure returns(int256){
return int256(packedValue % STRENGTH_PACK_6 / AGILITY_PACK_5);
}
function _unpackStrengthValue(uint256 packedValue) internal pure returns(int256){
return int256(packedValue % BASE_DAMAGE_PACK_7 / STRENGTH_PACK_6);
}
function _unpackBaseDamageValue(uint256 packedValue) internal pure returns(int256){
return int256(packedValue % PET_PACK_8 / BASE_DAMAGE_PACK_7);
}
function _unpackPetValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % AURA_PACK_9 / PET_PACK_8);
}
function _unpackAuraValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % WARRIOR_ID_PACK_10 / AURA_PACK_9);
}
//
//pvp unpack
function _unpackIdValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % PVP_CYCLE_PACK_11 / WARRIOR_ID_PACK_10);
}
function _unpackCycleValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % RATING_PACK_12 / PVP_CYCLE_PACK_11);
}
function _unpackRatingValue(uint256 packedValue) internal pure returns(uint256){
return (packedValue % PVP_BASE_PACK_13 / RATING_PACK_12);
}
//max cycle skip value cant be more than 1000000000
function _changeCycleValue(uint256 packedValue, uint256 newValue) internal pure returns(uint256){
newValue = newValue > 1000000000 ? 1000000000 : newValue;
return packedValue - (_unpackCycleValue(packedValue) * PVP_CYCLE_PACK_11) + newValue * PVP_CYCLE_PACK_11;
}
function _packWarriorCommonData(uint256 _identity, uint256 _experience) internal pure returns(uint256){
uint256 packedData = 0;
packedData += getClassMechValue(_identity) * CLASS_PACK_0;
packedData += getRarityBonusValue(_identity) * RARITY_BONUS_PACK_1;
packedData += getRarityValue(_identity) * RARITY_PACK_2;
packedData += _experience * EXPERIENCE_PACK_3;
packedData += getIntelligenceValue(_identity) * INTELLIGENCE_PACK_4;
packedData += getAgilityValue(_identity) * AGILITY_PACK_5;
packedData += getStrengthValue(_identity) * STRENGTH_PACK_6;
packedData += getDamageValue(_identity) * BASE_DAMAGE_PACK_7;
packedData += getPetValue(_identity) * PET_PACK_8;
return packedData;
}
function _packWarriorPvpData(uint256 _identity, uint256 _rating, uint256 _pvpCycle, uint256 _warriorId, uint256 _experience) internal pure returns(uint256){
uint256 packedData = _packWarriorCommonData(_identity, _experience);
packedData += _warriorId * WARRIOR_ID_PACK_10;
packedData += _pvpCycle * PVP_CYCLE_PACK_11;
//rating MUST have most significant value!
packedData += _rating * RATING_PACK_12;
return packedData;
}
/* TOURNAMENT BATTLES */
function _packWarriorIds(uint256[] memory packedWarriors) internal pure returns(uint256){
uint256 packedIds = 0;
uint256 length = packedWarriors.length;
for(uint256 i = 0; i < length; i ++) {
packedIds += (MAX_ID_SIZE ** i) * _unpackIdValue(packedWarriors[i]);
}
return packedIds;
}
function _unpackWarriorId(uint256 packedIds, uint256 index) internal pure returns(uint256){
return (packedIds % (MAX_ID_SIZE ** (index + 1)) / (MAX_ID_SIZE ** index));
}
function _packCombinedParams(int256 hp, int256 damage, int256 armor, int256 dodge, int256 penetration) internal pure returns(uint256) {
uint256 combinedWarrior = 0;
combinedWarrior += uint256(hp) * HP_PACK_0;
combinedWarrior += uint256(damage) * DAMAGE_PACK_1;
combinedWarrior += uint256(armor) * ARMOR_PACK_2;
combinedWarrior += uint256(dodge) * DODGE_PACK_3;
combinedWarrior += uint256(penetration) * PENETRATION_PACK_4;
return combinedWarrior;
}
function _unpackProtectionParams(uint256 combinedWarrior) internal pure returns
(int256 hp, int256 armor, int256 dodge){
hp = int256(combinedWarrior % DAMAGE_PACK_1 / HP_PACK_0);
armor = int256(combinedWarrior % DODGE_PACK_3 / ARMOR_PACK_2);
dodge = int256(combinedWarrior % PENETRATION_PACK_4 / DODGE_PACK_3);
}
function _unpackAttackParams(uint256 combinedWarrior) internal pure returns(int256 damage, int256 penetration) {
damage = int256(combinedWarrior % ARMOR_PACK_2 / DAMAGE_PACK_1);
penetration = int256(combinedWarrior % COMBINE_BASE_PACK_5 / PENETRATION_PACK_4);
}
function _combineWarriors(uint256[] memory packedWarriors) internal pure returns (uint256) {
int256 hp;
int256 damage;
int256 armor;
int256 dodge;
int256 penetration;
(hp, damage, armor, dodge, penetration) = _computeCombinedParams(packedWarriors);
return _packCombinedParams(hp, damage, armor, dodge, penetration);
}
function _computeCombinedParams(uint256[] memory packedWarriors) internal pure returns
(int256 totalHp, int256 totalDamage, int256 maxArmor, int256 maxDodge, int256 maxPenetration){
uint256 length = packedWarriors.length;
int256 hp;
int256 armor;
int256 dodge;
int256 penetration;
uint256 warriorAuras;
uint256 petAuras;
(warriorAuras, petAuras) = _getAurasData(packedWarriors);
uint256 packedWarrior;
for(uint256 i = 0; i < length; i ++) {
packedWarrior = packedWarriors[i];
totalDamage += getDamage(packedWarrior, warriorAuras, petAuras);
penetration = getPenetration(packedWarrior, warriorAuras, petAuras);
maxPenetration = maxPenetration > penetration ? maxPenetration : penetration;
(hp, armor, dodge) = _getProtectionParams(packedWarrior, warriorAuras, petAuras);
totalHp += hp;
maxArmor = maxArmor > armor ? maxArmor : armor;
maxDodge = maxDodge > dodge ? maxDodge : dodge;
}
}
function _getAurasData(uint256[] memory packedWarriors) internal pure returns(uint256 warriorAuras, uint256 petAuras) {
uint256 length = packedWarriors.length;
warriorAuras = 0;
petAuras = 0;
uint256 packedWarrior;
for(uint256 i = 0; i < length; i ++) {
packedWarrior = packedWarriors[i];
warriorAuras = enableAura(warriorAuras, (_unpackAuraValue(packedWarrior)));
petAuras = enableAura(petAuras, (_getPetAura(_unpackPetData(_unpackPetValue(packedWarrior)))));
}
warriorAuras = filterWarriorAuras(warriorAuras, petAuras);
return (warriorAuras, petAuras);
}
// Get bit value at position
function isAuraSet(uint256 aura, uint256 auraIndex) internal pure returns (bool) {
return aura & (uint256(0x01) << auraIndex) != 0;
}
// Set bit value at position
function enableAura(uint256 a, uint256 n) internal pure returns (uint256) {
return a | (uint256(0x01) << n);
}
//switch off warrior auras that are enabled in pets auras, pet aura have priority
function filterWarriorAuras(uint256 _warriorAuras, uint256 _petAuras) internal pure returns(uint256) {
return (_warriorAuras & _petAuras) ^ _warriorAuras;
}
function _getTournamentBattles(uint256 _numberOfContenders) internal pure returns(uint256) {
return (_numberOfContenders * BATTLES_PER_CONTENDER / 2);
}
function getTournamentBattleResults(uint256[] memory combinedWarriors, uint256 _targetBlock) internal view returns (uint32[] memory results){
uint256 length = combinedWarriors.length;
results = new uint32[](length);
int256 damage1;
int256 penetration1;
uint256 hash;
uint256 randomIndex;
uint256 exp = 0;
uint256 i;
uint256 result;
for(i = 0; i < length; i ++) {
(damage1, penetration1) = _unpackAttackParams(combinedWarriors[i]);
while(results[i] < BATTLES_PER_CONTENDER_SUM) {
//if we just started generate new random source
//or regenerate if we used all data from it
if (exp == 0 || exp > 73) {
hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock - i)), uint256(damage1) + now));
exp = 0;
}
//we do not fight with self if there are other warriors
randomIndex = (_random(i + 1 < length ? i + 1 : i, length, hash, 1000 * 10**exp, 10**exp));
result = getTournamentBattleResult(damage1, penetration1, combinedWarriors[i],
combinedWarriors[randomIndex], hash % (1000 * 10**exp) / 10**exp);
results[result == 1 ? i : randomIndex] += 101;//icrement battle count 100 and +1 win
results[result == 1 ? randomIndex : i] += 100;//increment only battle count 100 for loser
if (results[randomIndex] >= BATTLES_PER_CONTENDER_SUM) {
if (randomIndex < length - 1) {
_swapValues(combinedWarriors, results, randomIndex, length - 1);
}
length --;
}
exp++;
}
}
//filter battle count from results
length = combinedWarriors.length;
for(i = 0; i < length; i ++) {
results[i] = results[i] % 100;
}
return results;
}
function _swapValues(uint256[] memory combinedWarriors, uint32[] memory results, uint256 id1, uint256 id2) internal pure {
uint256 temp = combinedWarriors[id1];
combinedWarriors[id1] = combinedWarriors[id2];
combinedWarriors[id2] = temp;
temp = results[id1];
results[id1] = results[id2];
results[id2] = uint32(temp);
}
function getTournamentBattleResult(int256 damage1, int256 penetration1, uint256 combinedWarrior1,
uint256 combinedWarrior2, uint256 randomSource) internal pure returns (uint256)
{
int256 damage2;
int256 penetration2;
(damage2, penetration2) = _unpackAttackParams(combinedWarrior1);
int256 totalHp1 = getCombinedTotalHP(combinedWarrior1, penetration2);
int256 totalHp2 = getCombinedTotalHP(combinedWarrior2, penetration1);
return _getBattleResult(damage1 * getBattleRandom(randomSource, 1) / 100, damage2 * getBattleRandom(randomSource, 10) / 100, totalHp1, totalHp2, randomSource);
}
/* COMMON BATTLE */
function _getBattleResult(int256 damage1, int256 damage2, int256 totalHp1, int256 totalHp2, uint256 randomSource) internal pure returns (uint256){
totalHp1 = (totalHp1 * (PRECISION * PRECISION) / damage2);
totalHp2 = (totalHp2 * (PRECISION * PRECISION) / damage1);
//if draw, let the coin decide who wins
if (totalHp1 == totalHp2) return randomSource % 2 + 1;
return totalHp1 > totalHp2 ? 1 : 2;
}
function getCombinedTotalHP(uint256 combinedData, int256 enemyPenetration) internal pure returns(int256) {
int256 hp;
int256 armor;
int256 dodge;
(hp, armor, dodge) = _unpackProtectionParams(combinedData);
return _getTotalHp(hp, armor, dodge, enemyPenetration);
}
function getTotalHP(uint256 packedData, uint256 warriorAuras, uint256 petAuras, int256 enemyPenetration) internal pure returns(int256) {
int256 hp;
int256 armor;
int256 dodge;
(hp, armor, dodge) = _getProtectionParams(packedData, warriorAuras, petAuras);
return _getTotalHp(hp, armor, dodge, enemyPenetration);
}
function _getTotalHp(int256 hp, int256 armor, int256 dodge, int256 enemyPenetration) internal pure returns(int256) {
int256 piercingResult = (armor - enemyPenetration) < -(75 * PRECISION) ? -(75 * PRECISION) : (armor - enemyPenetration);
int256 mitigation = (PRECISION - piercingResult * PRECISION / (PRECISION + piercingResult / 100) / 100);
return (hp * PRECISION / mitigation + (hp * dodge / (100 * PRECISION)));
}
function _applyLevelBonus(int256 _value, uint256 _level) internal pure returns(int256) {
_level -= 1;
return int256(uint256(_value) * (LEVEL_BONUSES % (100 ** (_level + 1)) / (100 ** _level)) / 10);
}
function _getProtectionParams(uint256 packedData, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256 hp, int256 armor, int256 dodge) {
uint256 rarityBonus = _unpackRarityBonusValue(packedData);
uint256 petData = _unpackPetData(_unpackPetValue(packedData));
int256 strength = _unpackStrengthValue(packedData) * PRECISION + _getBattleBonus(BONUS_STR, rarityBonus, petData, warriorAuras, petAuras);
int256 agility = _unpackAgilityValue(packedData) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras);
hp = 100 * PRECISION + strength + 7 * strength / 10 + _getBattleBonus(BONUS_HP, rarityBonus, petData, warriorAuras, petAuras);//add bonus hp
hp = _applyLevelBonus(hp, _unpackLevelValue(packedData));
armor = (strength + 8 * strength / 10 + agility + _getBattleBonus(BONUS_ARMOR, rarityBonus, petData, warriorAuras, petAuras));//add bonus armor
dodge = (2 * agility / 3);
}
function getDamage(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) {
uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior);
uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior));
int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras);
int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras);
int256 crit = (agility / 5 + intelligence / 4) + _getBattleBonus(BONUS_CRIT_CHANCE, rarityBonus, petData, warriorAuras, petAuras);
int256 critMultiplier = (PRECISION + intelligence / 25) + _getBattleBonus(BONUS_CRIT_MULT, rarityBonus, petData, warriorAuras, petAuras);
int256 damage = int256(_unpackBaseDamageValue(packedWarrior) * 3 * PRECISION / 2) + _getBattleBonus(BONUS_DAMAGE, rarityBonus, petData, warriorAuras, petAuras);
return (_applyLevelBonus(damage, _unpackLevelValue(packedWarrior)) * (PRECISION + crit * critMultiplier / (100 * PRECISION))) / PRECISION;
}
function getPenetration(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) {
uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior);
uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior));
int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras);
int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras);
return (intelligence * 2 + agility + _getBattleBonus(BONUS_PENETRATION, rarityBonus, petData, warriorAuras, petAuras));
}
/* BATTLE PVP */
//@param randomSource must be >= 1000
function getBattleRandom(uint256 randmSource, uint256 _step) internal pure returns(int256){
return int256(100 + _random(0, 11, randmSource, 100 * _step, _step));
}
uint256 internal constant NO_AURA = 0;
function getPVPBattleResult(uint256 packedData1, uint256 packedData2, uint256 randmSource) internal pure returns (uint256){
uint256 petAura1 = _computePVPPetAura(packedData1);
uint256 petAura2 = _computePVPPetAura(packedData2);
uint256 warriorAura1 = _computePVPWarriorAura(packedData1, petAura1);
uint256 warriorAura2 = _computePVPWarriorAura(packedData2, petAura2);
int256 damage1 = getDamage(packedData1, warriorAura1, petAura1) * getBattleRandom(randmSource, 1) / 100;
int256 damage2 = getDamage(packedData2, warriorAura2, petAura2) * getBattleRandom(randmSource, 10) / 100;
int256 totalHp1;
int256 totalHp2;
(totalHp1, totalHp2) = _computeContendersTotalHp(packedData1, warriorAura1, petAura1, packedData2, warriorAura1, petAura1);
return _getBattleResult(damage1, damage2, totalHp1, totalHp2, randmSource);
}
function _computePVPPetAura(uint256 packedData) internal pure returns(uint256) {
return enableAura(NO_AURA, _getPetAura(_unpackPetData(_unpackPetValue(packedData))));
}
function _computePVPWarriorAura(uint256 packedData, uint256 petAuras) internal pure returns(uint256) {
return filterWarriorAuras(enableAura(NO_AURA, _unpackAuraValue(packedData)), petAuras);
}
function _computeContendersTotalHp(uint256 packedData1, uint256 warriorAura1, uint256 petAura1, uint256 packedData2, uint256 warriorAura2, uint256 petAura2)
internal pure returns(int256 totalHp1, int256 totalHp2) {
int256 enemyPenetration = getPenetration(packedData2, warriorAura2, petAura2);
totalHp1 = getTotalHP(packedData1, warriorAura1, petAura1, enemyPenetration);
enemyPenetration = getPenetration(packedData1, warriorAura1, petAura1);
totalHp2 = getTotalHP(packedData2, warriorAura1, petAura1, enemyPenetration);
}
function getRatingRange(uint256 _pvpCycle, uint256 _pvpInterval, uint256 _expandInterval) internal pure returns (uint256){
return 50 + (_pvpCycle * _pvpInterval / _expandInterval * 25);
}
function isMatching(int256 evenRating, int256 oddRating, int256 ratingGap) internal pure returns(bool) {
return evenRating <= (oddRating + ratingGap) && evenRating >= (oddRating - ratingGap);
}
function sort(uint256[] memory data) internal pure {
quickSort(data, int(0), int(data.length - 1));
}
function quickSort(uint256[] memory arr, int256 left, int256 right) internal pure {
int256 i = left;
int256 j = right;
if(i==j) return;
uint256 pivot = arr[uint256(left + (right - left) / 2)];
while (i <= j) {
while (arr[uint256(i)] < pivot) i++;
while (pivot < arr[uint256(j)]) j--;
if (i <= j) {
(arr[uint256(i)], arr[uint256(j)]) = (arr[uint256(j)], arr[uint256(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
function _swapPair(uint256[] memory matchingIds, uint256 id1, uint256 id2, uint256 id3, uint256 id4) internal pure {
uint256 temp = matchingIds[id1];
matchingIds[id1] = matchingIds[id2];
matchingIds[id2] = temp;
temp = matchingIds[id3];
matchingIds[id3] = matchingIds[id4];
matchingIds[id4] = temp;
}
function _swapValues(uint256[] memory matchingIds, uint256 id1, uint256 id2) internal pure {
uint256 temp = matchingIds[id1];
matchingIds[id1] = matchingIds[id2];
matchingIds[id2] = temp;
}
function _getMatchingIds(uint256[] memory matchingIds, uint256 _pvpInterval, uint256 _skipCycles, uint256 _expandInterval)
internal pure returns(uint256 matchingCount)
{
matchingCount = matchingIds.length;
if (matchingCount == 0) return 0;
uint256 warriorId;
uint256 index;
//sort matching ids
quickSort(matchingIds, int256(0), int256(matchingCount - 1));
//find pairs
int256 rating1;
uint256 pairIndex = 0;
int256 ratingRange;
for(index = 0; index < matchingCount; index++) {
//get packed value
warriorId = matchingIds[index];
//unpack rating 1
rating1 = int256(_unpackRatingValue(warriorId));
ratingRange = int256(getRatingRange(_unpackCycleValue(warriorId) + _skipCycles, _pvpInterval, _expandInterval));
if (index > pairIndex && //check left neighbor
isMatching(rating1, int256(_unpackRatingValue(matchingIds[index - 1])), ratingRange)) {
//move matched pairs to the left
//swap pairs
_swapPair(matchingIds, pairIndex, index - 1, pairIndex + 1, index);
//mark last pair position
pairIndex += 2;
} else if (index + 1 < matchingCount && //check right neighbor
isMatching(rating1, int256(_unpackRatingValue(matchingIds[index + 1])), ratingRange)) {
//move matched pairs to the left
//swap pairs
_swapPair(matchingIds, pairIndex, index, pairIndex + 1, index + 1);
//mark last pair position
pairIndex += 2;
//skip next iteration
index++;
}
}
matchingCount = pairIndex;
}
function _getPVPBattleResults(uint256[] memory matchingIds, uint256 matchingCount, uint256 _targetBlock) internal view {
uint256 exp = 0;
uint256 hash = 0;
uint256 result = 0;
for (uint256 even = 0; even < matchingCount; even += 2) {
if (exp == 0 || exp > 73) {
hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock)), hash));
exp = 0;
}
//compute battle result 1 = even(left) id won, 2 - odd(right) id won
result = getPVPBattleResult(matchingIds[even], matchingIds[even + 1], hash % (1000 * 10**exp) / 10**exp);
require(result > 0 && result < 3);
exp++;
//if odd warrior won, swap his id with even warrior,
//otherwise do nothing,
//even ids are winning ids! odds suck!
if (result == 2) {
_swapValues(matchingIds, even, even + 1);
}
}
}
function _getLevel(uint256 _levelPoints) internal pure returns(uint256) {
return _levelPoints / POINTS_TO_LEVEL;
}
}
library DataTypes {
// / @dev The main Warrior struct. Every warrior in CryptoWarriors is represented by a copy
// / of this structure, so great care was taken to ensure that it fits neatly into
// / exactly two 256-bit words. Note that the order of the members in this structure
// / is important because of the byte-packing rules used by Ethereum.
// / Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Warrior{
// The Warrior's identity code is packed into these 256-bits
uint256 identity;
uint64 cooldownEndBlock;
/** every warriors starts from 1 lv (10 level points per level) */
uint64 level;
/** PVP rating, every warrior starts with 100 rating */
int64 rating;
// 0 - idle
uint32 action;
/** Set to the index in the levelRequirements array (see CryptoWarriorBase.levelRequirements) that represents
* the current dungeon level requirement for warrior. This starts at zero. */
uint32 dungeonIndex;
}
}
contract CryptoWarriorBase is PermissionControll, PVPListenerInterface {
/*** EVENTS ***/
/// @dev The Arise event is fired whenever a new warrior comes into existence. This obviously
/// includes any time a warrior is created through the ariseWarrior method, but it is also called
/// when a new miner warrior is created.
event Arise(address owner, uint256 warriorId, uint256 identity);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a warrior
/// ownership is assigned, including dungeon rewards.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
uint256 public constant IDLE = 0;
uint256 public constant PVE_BATTLE = 1;
uint256 public constant PVP_BATTLE = 2;
uint256 public constant TOURNAMENT_BATTLE = 3;
//max pve dungeon level
uint256 public constant MAX_LEVEL = 25;
//how many points is needed to get 1 level
uint256 public constant POINTS_TO_LEVEL = 10;
/// @dev A lookup table contains PVE dungeon level requirements, each time warrior
/// completes dungeon, next level requirement is set, until 25lv (250points) is reached.
uint32[6] public dungeonRequirements = [
uint32(10),
uint32(30),
uint32(60),
uint32(100),
uint32(150),
uint32(250)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Warrior struct for all Warriors in existence. The ID
/// of each warrior is actually an index of this array.
DataTypes.Warrior[] warriors;
/// @dev A mapping from warrior IDs to the address that owns them. All warriors have
/// some valid owner address, even miner warriors are created with a non-zero owner.
mapping (uint256 => address) public warriorToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownersTokenCount;
/// @dev A mapping from warrior IDs to an address that has been approved to call
/// transferFrom(). Each Warrior can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public warriorToApproved;
// 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;
/// @dev The address of the ClockAuction contract that handles sales of warriors. This
/// same contract handles both peer-to-peer sales as well as the miner sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev Assigns ownership of a specific warrior to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// When creating new warriors _from is 0x0, but we can't account that address.
if (_from != address(0)) {
_clearApproval(_tokenId);
_removeTokenFrom(_from, _tokenId);
}
_addTokenTo(_to, _tokenId);
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
function _addTokenTo(address _to, uint256 _tokenId) internal {
// Since the number of warriors is capped to '1 000 000' we can't overflow this
ownersTokenCount[_to]++;
// transfer ownership
warriorToOwner[_tokenId] = _to;
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
function _removeTokenFrom(address _from, uint256 _tokenId) internal {
//
ownersTokenCount[_from]--;
warriorToOwner[_tokenId] = address(0);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length - 1;
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// 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
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
function _clearApproval(uint256 _tokenId) internal {
if (warriorToApproved[_tokenId] != address(0)) {
// clear any previously approved ownership exchange
warriorToApproved[_tokenId] = address(0);
}
}
function _createWarrior(uint256 _identity, address _owner, uint256 _cooldown, uint256 _level, uint256 _rating, uint256 _dungeonIndex)
internal
returns (uint256) {
DataTypes.Warrior memory _warrior = DataTypes.Warrior({
identity : _identity,
cooldownEndBlock : uint64(_cooldown),
level : uint64(_level),//uint64(10),
rating : int64(_rating),//int64(100),
action : uint32(IDLE),
dungeonIndex : uint32(_dungeonIndex)//uint32(0)
});
uint256 newWarriorId = warriors.push(_warrior) - 1;
// let's just be 100% sure we never let this happen.
require(newWarriorId == uint256(uint32(newWarriorId)));
// emit the arise event
Arise(_owner, newWarriorId, _identity);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newWarriorId);
return newWarriorId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyAuthorized {
secondsPerBlock = secs;
}
}
contract WarriorTokenImpl is CryptoWarriorBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CryptoWarriors";
string public constant symbol = "CW";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9f40b779));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/** @dev Checks if a given address is the current owner of the specified Warrior tokenId.
* @param _claimant the address we are validating against.
* @param _tokenId warrior id
*/
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return _claimant != address(0) && warriorToOwner[_tokenId] == _claimant;
}
function _ownerApproved(address _claimant, uint256 _tokenId) internal view returns (bool) {
return _claimant != address(0) &&//0 address means token is burned
warriorToOwner[_tokenId] == _claimant && warriorToApproved[_tokenId] == address(0);
}
/// @dev Checks if a given address currently has transferApproval for a particular Warrior.
/// @param _claimant the address we are confirming warrior is approved for.
/// @param _tokenId warrior id
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return warriorToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Warriors on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
warriorToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of Warriors(tokens) owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownersTokenCount[_owner];
}
/// @notice Transfers a Warrior to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoWarriors specifically) or your Warrior may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Warrior to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any warriors (except very briefly
// after a miner warrior is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of warriors
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own warrior.
require(_owns(msg.sender, _tokenId));
// Only idle warriors are allowed
require(warriors[_tokenId].action == IDLE);
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/// @notice Grant another address the right to transfer a specific Warrior via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Warrior that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _tokenId) external whenNotPaused {
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Only idle warriors are allowed
require(warriors[_tokenId].action == IDLE);
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Warrior owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Warrior to be transfered.
/// @param _to The address that should take ownership of the Warrior. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Warrior to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any warriors (except very briefly
// after a miner warrior is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Only idle warriors are allowed
require(warriors[_tokenId].action == IDLE);
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Warriors currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return warriors.length;
}
/// @notice Returns the address currently assigned ownership of a given Warrior.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
require(_tokenId < warriors.length);
owner = warriorToOwner[_tokenId];
}
/// @notice Returns a list of all Warrior IDs assigned to an address.
/// @param _owner The owner whose Warriors we are interested in.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
return ownedTokens[_owner];
}
function tokensOfOwnerFromIndex(address _owner, uint256 _fromIndex, uint256 _count) external view returns(uint256[] memory ownerTokens) {
require(_fromIndex < balanceOf(_owner));
uint256[] storage tokens = ownedTokens[_owner];
//
uint256 ownerBalance = ownersTokenCount[_owner];
uint256 lenght = (ownerBalance - _fromIndex >= _count ? _count : ownerBalance - _fromIndex);
//
ownerTokens = new uint256[](lenght);
for(uint256 i = 0; i < lenght; i ++) {
ownerTokens[i] = tokens[_fromIndex + i];
}
return ownerTokens;
}
/**
* @dev Internal function to burn a specific token
* @dev 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 {
_clearApproval(_tokenId);
_removeTokenFrom(_owner, _tokenId);
Transfer(_owner, address(0), _tokenId);
}
}
contract CryptoWarriorPVE is WarriorTokenImpl {
uint256 internal constant MINER_PERK = 1;
uint256 internal constant SUMMONING_SICKENESS = 12;
uint256 internal constant PVE_COOLDOWN = 1 hours;
uint256 internal constant PVE_DURATION = 15 minutes;
/// @notice The payment required to use startPVEBattle().
uint256 public pveBattleFee = 10 finney;
uint256 public constant PVE_COMPENSATION = 2 finney;
/// @dev The address of the sibling contract that is used to implement warrior generation algorithm.
SanctuaryInterface public sanctuary;
/** @dev PVEStarted event. Emitted every time a warrior enters pve battle
* @param owner Warrior owner
* @param dungeonIndex Started dungeon index
* @param warriorId Warrior ID that started PVE dungeon
* @param battleEndBlock Block number, when started PVE dungeon will be completed
*/
event PVEStarted(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 battleEndBlock);
/** @dev PVEFinished event. Emitted every time a warrior finishes pve battle
* @param owner Warrior owner
* @param dungeonIndex Finished dungeon index
* @param warriorId Warrior ID that completed dungeon
* @param cooldownEndBlock Block number, when cooldown on PVE battle entrance will be over
* @param rewardId Warrior ID which was granted to the owner as battle reward
*/
event PVEFinished(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 cooldownEndBlock, uint256 rewardId);
/// @dev Update the address of the sanctuary contract, can only be called by the Admin.
/// @param _address An address of a sanctuary contract instance to be used from this point forward.
function setSanctuaryAddress(address _address) external onlyAdmin {
SanctuaryInterface candidateContract = SanctuaryInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSanctuary());
// Set the new contract address
sanctuary = candidateContract;
}
function areUnique(uint256[] memory _warriorIds) internal pure returns(bool) {
uint256 length = _warriorIds.length;
uint256 j;
for(uint256 i = 0; i < length; i++) {
for(j = i + 1; j < length; j++) {
if (_warriorIds[i] == _warriorIds[j]) return false;
}
}
return true;
}
/// @dev Updates the minimum payment required for calling startPVE(). Can only
/// be called by the COO address.
function setPVEBattleFee(uint256 _pveBattleFee) external onlyAdmin {
require(_pveBattleFee > PVE_COMPENSATION);
pveBattleFee = _pveBattleFee;
}
/** @dev Returns PVE cooldown, after each battle, the warrior receives a
* cooldown on the next entrance to the battle, cooldown depends on current warrior level,
* which is multiplied by 1h. Special case: after receiving 25 lv, the cooldwon will be 14 days.
* @param _levelPoints warrior level */
function getPVECooldown(uint256 _levelPoints) public pure returns (uint256) {
uint256 level = CryptoUtils._getLevel(_levelPoints);
if (level >= MAX_LEVEL) return (14 * 24 * PVE_COOLDOWN);//14 days
return (PVE_COOLDOWN * level);
}
/** @dev Returns PVE duration, each battle have a duration, which depends on current warrior level,
* which is multiplied by 15 min. At the end of the duration, warrior is becoming eligible to receive
* battle reward (new warrior in shiny armor)
* @param _levelPoints warrior level points
*/
function getPVEDuration(uint256 _levelPoints) public pure returns (uint256) {
return CryptoUtils._getLevel(_levelPoints) * PVE_DURATION;
}
/// @dev Checks that a given warrior can participate in PVE battle. Requires that the
/// current cooldown is finished and also checks that warrior is idle (does not participate in any action)
/// and dungeon level requirement is satisfied
function _isReadyToPVE(DataTypes.Warrior _warrior) internal view returns (bool) {
return (_warrior.action == IDLE) && //is idle
(_warrior.cooldownEndBlock <= uint64(block.number)) && //no cooldown
(_warrior.level >= dungeonRequirements[_warrior.dungeonIndex]);//dungeon level requirement is satisfied
}
/// @dev Internal utility function to initiate pve battle, assumes that all battle
/// requirements have been checked.
function _triggerPVEStart(uint256 _warriorId) internal {
// Grab a reference to the warrior from storage.
DataTypes.Warrior storage warrior = warriors[_warriorId];
// Set warrior current action to pve battle
warrior.action = uint16(PVE_BATTLE);
// Set battle duration
warrior.cooldownEndBlock = uint64((getPVEDuration(warrior.level) / secondsPerBlock) + block.number);
// Emit the pve battle start event.
PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock);
}
/// @dev Starts PVE battle for specified warrior,
/// after battle, warrior owner will receive reward (Warrior)
/// @param _warriorId A Warrior ready to PVE battle.
function startPVE(uint256 _warriorId) external payable whenNotPaused {
// Checks for payment.
require(msg.value >= pveBattleFee);
// Caller must own the warrior.
require(_ownerApproved(msg.sender, _warriorId));
// Grab a reference to the warrior in storage.
DataTypes.Warrior storage warrior = warriors[_warriorId];
// Check that the warrior exists.
require(warrior.identity != 0);
// Check that the warrior is ready to battle
require(_isReadyToPVE(warrior));
// All checks passed, let the battle begin!
_triggerPVEStart(_warriorId);
// Calculate any excess funds included in msg.value. If the excess
// is anything worth worrying about, transfer it back to message owner.
// NOTE: We checked above that the msg.value is greater than or
// equal to the price so this cannot underflow.
uint256 feeExcess = msg.value - pveBattleFee;
// Return the funds. This is not susceptible
// to a re-entry attack because of _isReadyToPVE check
// will fail
msg.sender.transfer(feeExcess);
//send battle fee to beneficiary
bankAddress.transfer(pveBattleFee - PVE_COMPENSATION);
}
function _ariseWarrior(address _owner, DataTypes.Warrior storage _warrior) internal returns(uint256) {
uint256 identity = sanctuary.generateWarrior(_warrior.identity, CryptoUtils._getLevel(_warrior.level), _warrior.cooldownEndBlock - 1, 0);
return _createWarrior(identity, _owner, block.number + (PVE_COOLDOWN * SUMMONING_SICKENESS / secondsPerBlock), 10, 100, 0);
}
/// @dev Internal utility function to finish pve battle, assumes that all battle
/// finish requirements have been checked.
function _triggerPVEFinish(uint256 _warriorId) internal {
// Grab a reference to the warrior in storage.
DataTypes.Warrior storage warrior = warriors[_warriorId];
// Set warrior current action to idle
warrior.action = uint16(IDLE);
// Compute an estimation of the cooldown time in blocks (based on current level).
// and miner perc also reduces cooldown time by 4 times
warrior.cooldownEndBlock = uint64((getPVECooldown(warrior.level) /
CryptoUtils._getBonus(warrior.identity) / secondsPerBlock) + block.number);
// cash completed dungeon index before increment
uint256 dungeonIndex = warrior.dungeonIndex;
// Increment the dungeon index, clamping it at 5, which is the length of the
// dungeonRequirements array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas.
if (dungeonIndex < 5) {
warrior.dungeonIndex += 1;
}
address owner = warriorToOwner[_warriorId];
// generate reward
uint256 arisenWarriorId = _ariseWarrior(owner, warrior);
//Emit event
PVEFinished(owner, dungeonIndex, _warriorId, warrior.cooldownEndBlock, arisenWarriorId);
}
/**
* @dev finishPVE can be called after battle time is over,
* if checks are passed then battle result is computed,
* and new warrior is awarded to owner of specified _warriord ID.
* NB anyone can call this method, if they willing to pay the gas price
*/
function finishPVE(uint256 _warriorId) external whenNotPaused {
// Grab a reference to the warrior in storage.
DataTypes.Warrior storage warrior = warriors[_warriorId];
// Check that the warrior exists.
require(warrior.identity != 0);
// Check that warrior participated in PVE battle action
require(warrior.action == PVE_BATTLE);
// And the battle time is over
require(warrior.cooldownEndBlock <= uint64(block.number));
// When the all checks done, calculate actual battle result
_triggerPVEFinish(_warriorId);
//not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE)
//and require(warrior.cooldownEndBlock <= uint64(block.number));
msg.sender.transfer(PVE_COMPENSATION);
}
/**
* @dev finishPVEBatch same as finishPVE but for multiple warrior ids.
* NB anyone can call this method, if they willing to pay the gas price
*/
function finishPVEBatch(uint256[] _warriorIds) external whenNotPaused {
uint256 length = _warriorIds.length;
//check max number of bach finish pve
require(length <= 20);
uint256 blockNumber = block.number;
uint256 index;
//all warrior ids must be unique
require(areUnique(_warriorIds));
//check prerequisites
for(index = 0; index < length; index ++) {
DataTypes.Warrior storage warrior = warriors[_warriorIds[index]];
require(
// Check that the warrior exists.
warrior.identity != 0 &&
// Check that warrior participated in PVE battle action
warrior.action == PVE_BATTLE &&
// And the battle time is over
warrior.cooldownEndBlock <= blockNumber
);
}
// When the all checks done, calculate actual battle result
for(index = 0; index < length; index ++) {
_triggerPVEFinish(_warriorIds[index]);
}
//not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE)
//and require(warrior.cooldownEndBlock <= uint64(block.number));
msg.sender.transfer(PVE_COMPENSATION * length);
}
}
contract CryptoWarriorSanctuary is CryptoWarriorPVE {
uint256 internal constant RARE = 3;
function burnWarrior(uint256 _warriorId, address _owner) whenNotPaused external {
require(msg.sender == address(sanctuary));
// Caller must own the warrior.
require(_ownerApproved(_owner, _warriorId));
// Grab a reference to the warrior in storage.
DataTypes.Warrior storage warrior = warriors[_warriorId];
// Check that the warrior exists.
require(warrior.identity != 0);
// Check that the warrior is ready to battle
require(warrior.action == IDLE);//is idle
// Rarity of burned warrior must be less or equal RARE (3)
require(CryptoUtils.getRarityValue(warrior.identity) <= RARE);
// Warriors with MINER perc are not allowed to be berned
require(CryptoUtils.getSpecialityValue(warrior.identity) < MINER_PERK);
_burn(_owner, _warriorId);
}
function ariseWarrior(uint256 _identity, address _owner, uint256 _cooldown) whenNotPaused external returns(uint256){
require(msg.sender == address(sanctuary));
return _createWarrior(_identity, _owner, _cooldown, 10, 100, 0);
}
}
contract CryptoWarriorPVP is CryptoWarriorSanctuary {
PVPInterface public battleProvider;
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setBattleProviderAddress(address _address) external onlyAdmin {
PVPInterface candidateContract = PVPInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isPVPProvider());
// Set the new contract address
battleProvider = candidateContract;
}
function _packPVPData(uint256 _warriorId, DataTypes.Warrior storage warrior) internal view returns(uint256){
return CryptoUtils._packWarriorPvpData(warrior.identity, uint256(warrior.rating), 0, _warriorId, warrior.level);
}
function _triggerPVPSignUp(uint256 _warriorId, uint256 fee) internal {
DataTypes.Warrior storage warrior = warriors[_warriorId];
uint256 packedWarrior = _packPVPData(_warriorId, warrior);
// addPVPContender will throw if fee fails.
battleProvider.addPVPContender.value(fee)(msg.sender, packedWarrior);
warrior.action = uint16(PVP_BATTLE);
}
/*
* @title signUpForPVP enqueues specified warrior to PVP
*
* @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room.
* Once every 15 minutes, we check the warriors in the room and select pairs.
* For those warriors to whom we found couples, fighting is conducted and the results
* are recorded in the profile of the warrior.
*/
function signUpForPVP(uint256 _warriorId) public payable whenNotPaused {//done
// Caller must own the warrior.
require(_ownerApproved(msg.sender, _warriorId));
// Grab a reference to the warrior in storage.
DataTypes.Warrior storage warrior = warriors[_warriorId];
// sanity check
require(warrior.identity != 0);
// Check that the warrior is ready to battle
require(warrior.action == IDLE);
// Define the current price of the auction.
uint256 fee = battleProvider.getPVPEntranceFee(warrior.level);
// Checks for payment.
require(msg.value >= fee);
// All checks passed, put the warrior to the queue!
_triggerPVPSignUp(_warriorId, fee);
// Calculate any excess funds included in msg.value. If the excess
// is anything worth worrying about, transfer it back to message owner.
// NOTE: We checked above that the msg.value is greater than or
// equal to the price so this cannot underflow.
uint256 feeExcess = msg.value - fee;
// Return the funds. This is not susceptible
// to a re-entry attack because of warrior.action == IDLE check
// will fail
msg.sender.transfer(feeExcess);
}
function _grandPVPWinnerReward(uint256 _warriorId) internal {
DataTypes.Warrior storage warrior = warriors[_warriorId];
// reward 1 level, add 10 level points
uint256 level = warrior.level;
if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) {
level = level + POINTS_TO_LEVEL;
warrior.level = uint64(level > (MAX_LEVEL * POINTS_TO_LEVEL) ? (MAX_LEVEL * POINTS_TO_LEVEL) : level);
}
// give 100 rating for levelUp and 30 for win
warrior.rating += 130;
// mark warrior idle, so it can participate
// in another actions
warrior.action = uint16(IDLE);
}
function _grandPVPLoserReward(uint256 _warriorId) internal {
DataTypes.Warrior storage warrior = warriors[_warriorId];
// reward 0.5 level
uint256 oldLevel = warrior.level;
uint256 level = oldLevel;
if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) {
level += (POINTS_TO_LEVEL / 2);
warrior.level = uint64(level);
}
// give 100 rating for levelUp if happens and -30 for lose
int256 newRating = warrior.rating + (CryptoUtils._getLevel(level) > CryptoUtils._getLevel(oldLevel) ? int256(100 - 30) : int256(-30));
// rating can't be less than 0 and more than 1000000000
warrior.rating = int64((newRating >= 0) ? (newRating > 1000000000 ? 1000000000 : newRating) : 0);
// mark warrior idle, so it can participate
// in another actions
warrior.action = uint16(IDLE);
}
function _grandPVPRewards(uint256[] memory warriorsData, uint256 matchingCount) internal {
for(uint256 id = 0; id < matchingCount; id += 2){
//
// winner, even ids are winners!
_grandPVPWinnerReward(CryptoUtils._unpackIdValue(warriorsData[id]));
//
// loser, they are odd...
_grandPVPLoserReward(CryptoUtils._unpackIdValue(warriorsData[id + 1]));
}
}
// @dev Internal utility function to initiate pvp battle, assumes that all battle
/// requirements have been checked.
function pvpFinished(uint256[] warriorsData, uint256 matchingCount) public {
//this method can be invoked only by battleProvider contract
require(msg.sender == address(battleProvider));
_grandPVPRewards(warriorsData, matchingCount);
}
function pvpContenderRemoved(uint256 _warriorId) public {
//this method can be invoked only by battleProvider contract
require(msg.sender == address(battleProvider));
//grab warrior storage reference
DataTypes.Warrior storage warrior = warriors[_warriorId];
//specified warrior must be in pvp state
require(warrior.action == PVP_BATTLE);
//all checks done
//set warrior state to IDLE
warrior.action = uint16(IDLE);
}
}
contract CryptoWarriorTournament is CryptoWarriorPVP {
uint256 internal constant GROUP_SIZE = 5;
function _ownsAll(address _claimant, uint256[] memory _warriorIds) internal view returns (bool) {
uint256 length = _warriorIds.length;
for(uint256 i = 0; i < length; i++) {
if (!_ownerApproved(_claimant, _warriorIds[i])) return false;
}
return true;
}
function _isReadyToTournament(DataTypes.Warrior storage _warrior) internal view returns(bool){
return _warrior.level >= 50 && _warrior.action == IDLE;//must not participate in any action
}
function _packTournamentData(uint256[] memory _warriorIds) internal view returns(uint256[] memory tournamentData) {
tournamentData = new uint256[](GROUP_SIZE);
uint256 warriorId;
for(uint256 i = 0; i < GROUP_SIZE; i++) {
warriorId = _warriorIds[i];
tournamentData[i] = _packPVPData(warriorId, warriors[warriorId]);
}
return tournamentData;
}
// @dev Internal utility function to sign up to tournament,
// assumes that all battle requirements have been checked.
function _triggerTournamentSignUp(uint256[] memory _warriorIds, uint256 fee) internal {
//pack warrior ids into into uint256
uint256[] memory tournamentData = _packTournamentData(_warriorIds);
for(uint256 i = 0; i < GROUP_SIZE; i++) {
// Set warrior current action to tournament battle
warriors[_warriorIds[i]].action = uint16(TOURNAMENT_BATTLE);
}
battleProvider.addTournamentContender.value(fee)(msg.sender, tournamentData);
}
function signUpForTournament(uint256[] _warriorIds) public payable {
//
//check that there is enough funds to pay entrance fee
uint256 fee = battleProvider.getTournamentThresholdFee();
require(msg.value >= fee);
//
//check that warriors group is exactly of allowed size
require(_warriorIds.length == GROUP_SIZE);
//
//message sender must own all the specified warrior IDs
require(_ownsAll(msg.sender, _warriorIds));
//
//check all warriors are unique
require(areUnique(_warriorIds));
//
//check that all warriors are 25 lv and IDLE
for(uint256 i = 0; i < GROUP_SIZE; i ++) {
// Grab a reference to the warrior in storage.
require(_isReadyToTournament(warriors[_warriorIds[i]]));
}
//all checks passed, trigger sign up
_triggerTournamentSignUp(_warriorIds, fee);
// Calculate any excess funds included in msg.value. If the excess
// is anything worth worrying about, transfer it back to message owner.
// NOTE: We checked above that the msg.value is greater than or
// equal to the fee so this cannot underflow.
uint256 feeExcess = msg.value - fee;
// Return the funds. This is not susceptible
// to a re-entry attack because of _isReadyToTournament check
// will fail
msg.sender.transfer(feeExcess);
}
function _setIDLE(uint256 warriorIds) internal {
for(uint256 i = 0; i < GROUP_SIZE; i ++) {
warriors[CryptoUtils._unpackWarriorId(warriorIds, i)].action = uint16(IDLE);
}
}
function _freeWarriors(uint256[] memory packedContenders) internal {
uint256 length = packedContenders.length;
for(uint256 i = 0; i < length; i ++) {
//set participants action to IDLE
_setIDLE(packedContenders[i]);
}
}
function tournamentFinished(uint256[] packedContenders) public {
//this method can be invoked only by battleProvider contract
require(msg.sender == address(battleProvider));
//grad rewards and set IDLE action
_freeWarriors(packedContenders);
}
}
contract CryptoWarriorAuction is CryptoWarriorTournament {
// @notice The auction contract variables are defined in CryptoWarriorBase to allow
// us to refer to them in WarriorTokenImpl to prevent accidental transfers.
// `saleAuction` refers to the auction for miner and p2p sale of warriors.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyAdmin {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a warrior up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _warriorId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If warrior is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_ownerApproved(msg.sender, _warriorId));
// Ensure the warrior is not busy to prevent the auction
// contract creation while warrior is in any kind of battle (PVE, PVP, TOURNAMENT).
require(warriors[_warriorId].action == IDLE);
_approve(_warriorId, address(saleAuction));
// Sale auction throws if inputs are invalid and clears
// transfer approval after escrowing the warrior.
saleAuction.createAuction(
_warriorId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
}
contract CryptoWarriorIssuer is CryptoWarriorAuction {
// Limits the number of warriors the contract owner can ever create
uint256 public constant MINER_CREATION_LIMIT = 2880;//issue every 15min for one month
// Constants for miner auctions.
uint256 public constant MINER_STARTING_PRICE = 100 finney;
uint256 public constant MINER_END_PRICE = 50 finney;
uint256 public constant MINER_AUCTION_DURATION = 1 days;
uint256 public minerCreatedCount;
/// @dev Generates a new miner warrior with MINER perk of COMMON rarity
/// creates an auction for it.
function createMinerAuction() external onlyIssuer {
require(minerCreatedCount < MINER_CREATION_LIMIT);
minerCreatedCount++;
uint256 identity = sanctuary.generateWarrior(minerCreatedCount, 0, block.number - 1, MINER_PERK);
uint256 warriorId = _createWarrior(identity, bankAddress, 0, 10, 100, 0);
_approve(warriorId, address(saleAuction));
saleAuction.createAuction(
warriorId,
_computeNextMinerPrice(),
MINER_END_PRICE,
MINER_AUCTION_DURATION,
bankAddress
);
}
/// @dev Computes the next miner auction starting price, given
/// the average of the past 5 prices * 2.
function _computeNextMinerPrice() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageMinerSalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice * 3 / 2;//confirmed
// We never auction for less than starting price
if (nextPrice < MINER_STARTING_PRICE) {
nextPrice = MINER_STARTING_PRICE;
}
return nextPrice;
}
}
contract CoreRecovery is CryptoWarriorIssuer {
bool public allowRecovery = true;
//data model
//0 - identity
//1 - cooldownEndBlock
//2 - level
//3 - rating
//4 - index
function recoverWarriors(uint256[] recoveryData, address[] owners) external onlyAdmin whenPaused {
//check that recory action is allowed
require(allowRecovery);
uint256 length = owners.length;
//check that number of owners corresponds to recover data length
require(length == recoveryData.length / 5);
for(uint256 i = 0; i < length; i++) {
_createWarrior(recoveryData[i * 5], owners[i], recoveryData[i * 5 + 1],
recoveryData[i * 5 + 2], recoveryData[i * 5 + 3], recoveryData[i * 5 + 4]);
}
}
//recovery is a one time action, once it is done no more recovery actions allowed
function recoveryDone() external onlyAdmin {
allowRecovery = false;
}
}
contract CryptoWarriorCore is CoreRecovery {
/// @notice Creates the main CryptoWarrior smart contract instance.
function CryptoWarriorCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial Admin
adminAddress = msg.sender;
// the creator of the contract is also the initial COO
issuerAddress = msg.sender;
// the creator of the contract is also the initial Bank
bankAddress = msg.sender;
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here
/// (Hopefully, we can prevent user accidents.)
function() external payable {
require(false);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyAdmin whenPaused {
require(address(saleAuction) != address(0));
require(address(sanctuary) != address(0));
require(address(battleProvider) != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
function getBeneficiary() external view returns(address) {
return bankAddress;
}
function isPVPListener() public pure returns (bool) {
return true;
}
/**
*@param _warriorIds array of warriorIds,
* for those IDs warrior data will be packed into warriorsData array
*@return warriorsData packed warrior data
*@return stepSize number of fields in single warrior data */
function getWarriors(uint256[] _warriorIds) external view returns (uint256[] memory warriorsData, uint256 stepSize) {
stepSize = 6;
warriorsData = new uint256[](_warriorIds.length * stepSize);
for(uint256 i = 0; i < _warriorIds.length; i++) {
_setWarriorData(warriorsData, warriors[_warriorIds[i]], i * stepSize);
}
}
/**
*@param indexFrom index in global warrior storage (aka warriorId),
* from this index(including), warriors data will be gathered
*@param count Number of warriors to include in packed data
*@return warriorsData packed warrior data
*@return stepSize number of fields in single warrior data */
function getWarriorsFromIndex(uint256 indexFrom, uint256 count) external view returns (uint256[] memory warriorsData, uint256 stepSize) {
stepSize = 6;
//check length
uint256 lenght = (warriors.length - indexFrom >= count ? count : warriors.length - indexFrom);
warriorsData = new uint256[](lenght * stepSize);
for(uint256 i = 0; i < lenght; i ++) {
_setWarriorData(warriorsData, warriors[indexFrom + i], i * stepSize);
}
}
function getWarriorOwners(uint256[] _warriorIds) external view returns (address[] memory owners) {
uint256 lenght = _warriorIds.length;
owners = new address[](lenght);
for(uint256 i = 0; i < lenght; i ++) {
owners[i] = warriorToOwner[_warriorIds[i]];
}
}
function _setWarriorData(uint256[] memory warriorsData, DataTypes.Warrior storage warrior, uint256 id) internal view {
warriorsData[id] = uint256(warrior.identity);//0
warriorsData[id + 1] = uint256(warrior.cooldownEndBlock);//1
warriorsData[id + 2] = uint256(warrior.level);//2
warriorsData[id + 3] = uint256(warrior.rating);//3
warriorsData[id + 4] = uint256(warrior.action);//4
warriorsData[id + 5] = uint256(warrior.dungeonIndex);//5
}
function getWarrior(uint256 _id) external view returns
(
uint256 identity,
uint256 cooldownEndBlock,
uint256 level,
uint256 rating,
uint256 action,
uint256 dungeonIndex
) {
DataTypes.Warrior storage warrior = warriors[_id];
identity = uint256(warrior.identity);
cooldownEndBlock = uint256(warrior.cooldownEndBlock);
level = uint256(warrior.level);
rating = uint256(warrior.rating);
action = uint256(warrior.action);
dungeonIndex = uint256(warrior.dungeonIndex);
}
}
/* @title Handles creating pvp battles every 15 min.*/
contract PVP is PausableBattle, PVPInterface {
/* PVP BATLE */
/** list of packed warrior data that will participate in next PVP session.
* Fixed size arry, to evade constant remove and push operations,
* this approach reduces transaction costs involving queue modification. */
uint256[100] public pvpQueue;
//
//queue size
uint256 public pvpQueueSize = 0;
// @dev A mapping from owner address to booty in WEI
// booty is acquired in PVP and Tournament battles and can be
// withdrawn with grabBooty method by the owner of the loot
mapping (address => uint256) public ownerToBooty;
// @dev A mapping from warrior id to owners address
mapping (uint256 => address) internal warriorToOwner;
// An approximation of currently how many seconds are in between blocks.
uint256 internal secondsPerBlock = 15;
// Cut owner takes from, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public pvpOwnerCut;
// Values 0-10,000 map to 0%-100%
//this % of the total bets will be sent as
//a reward to address, that triggered finishPVP method
uint256 public pvpMaxIncentiveCut;
/// @notice The payment base required to use startPVP().
// pvpBattleFee * (warrior.level / POINTS_TO_LEVEL)
uint256 internal pvpBattleFee = 10 finney;
uint256 public constant PVP_INTERVAL = 15 minutes;
uint256 public nextPVPBatleBlock = 0;
//number of WEI in hands of warrior owners
uint256 public totalBooty = 0;
/* TOURNAMENT */
uint256 public constant FUND_GATHERING_TIME = 24 hours;
uint256 public constant ADMISSION_TIME = 12 hours;
uint256 public constant RATING_EXPAND_INTERVAL = 1 hours;
uint256 internal constant SAFETY_GAP = 5;
uint256 internal constant MAX_INCENTIVE_REWARD = 200 finney;
//tournamentContenders size
uint256 public tournamentQueueSize = 0;
// Values 0-10,000 map to 0%-100%
uint256 public tournamentBankCut;
/** tournamentEndBlock, tournament is eligible to be finished only
* after block.number >= tournamentEndBlock
* it depends on FUND_GATHERING_TIME and ADMISSION_TIME */
uint256 public tournamentEndBlock;
//number of WEI in tournament bank
uint256 public currentTournamentBank = 0;
uint256 public nextTournamentBank = 0;
PVPListenerInterface internal pvpListener;
/* EVENTS */
/** @dev TournamentScheduled event. Emitted every time a tournament is scheduled
* @param tournamentEndBlock when block.number > tournamentEndBlock, then tournament
* is eligible to be finished or rescheduled */
event TournamentScheduled(uint256 tournamentEndBlock);
/** @dev PVPScheduled event. Emitted every time a tournament is scheduled
* @param nextPVPBatleBlock when block.number > nextPVPBatleBlock, then pvp battle
* is eligible to be finished or rescheduled */
event PVPScheduled(uint256 nextPVPBatleBlock);
/** @dev PVPNewContender event. Emitted every time a warrior enqueues pvp battle
* @param owner Warrior owner
* @param warriorId Warrior ID that entered PVP queue
* @param entranceFee fee in WEI warrior owner payed to enter PVP
*/
event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee);
/** @dev PVPFinished event. Emitted every time a pvp battle is finished
* @param warriorsData array of pairs of pvp warriors packed to uint256, even => winners, odd => losers
* @param owners array of warrior owners, 1 to 1 with warriorsData, even => winners, odd => losers
* @param matchingCount total number of warriors that fought in current pvp session and got rewards,
* if matchingCount < participants.length then all IDs that are >= matchingCount will
* remain in waiting room, until they are matched.
*/
event PVPFinished(uint256[] warriorsData, address[] owners, uint256 matchingCount);
/** @dev BootySendFailed event. Emitted every time address.send() function failed to transfer Ether to recipient
* in this case recipient Ether is recorded to ownerToBooty mapping, so recipient can withdraw their booty manually
* @param recipient address for whom send failed
* @param amount number of WEI we failed to send
*/
event BootySendFailed(address recipient, uint256 amount);
/** @dev BootyGrabbed event
* @param receiver address who grabbed his booty
* @param amount number of WEI
*/
event BootyGrabbed(address receiver, uint256 amount);
/** @dev PVPContenderRemoved event. Emitted every time warrior is removed from pvp queue by its owner.
* @param warriorId id of the removed warrior
*/
event PVPContenderRemoved(uint256 warriorId, address owner);
function PVP(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut) public {
require((_tournamentBankCut + _pvpCut + _pvpMaxIncentiveCut) <= 10000);
pvpOwnerCut = _pvpCut;
tournamentBankCut = _tournamentBankCut;
pvpMaxIncentiveCut = _pvpMaxIncentiveCut;
}
/** @dev grabBooty sends to message sender his booty in WEI
*/
function grabBooty() external {
uint256 booty = ownerToBooty[msg.sender];
require(booty > 0);
require(totalBooty >= booty);
ownerToBooty[msg.sender] = 0;
totalBooty -= booty;
msg.sender.transfer(booty);
//emit event
BootyGrabbed(msg.sender, booty);
}
function safeSend(address _recipient, uint256 _amaunt) internal {
uint256 failedBooty = sendBooty(_recipient, _amaunt);
if (failedBooty > 0) {
totalBooty += failedBooty;
}
}
function sendBooty(address _recipient, uint256 _amaunt) internal returns(uint256) {
bool success = _recipient.send(_amaunt);
if (!success && _amaunt > 0) {
ownerToBooty[_recipient] += _amaunt;
BootySendFailed(_recipient, _amaunt);
return _amaunt;
}
return 0;
}
//@returns block number, after this block tournament is opened for admission
function getTournamentAdmissionBlock() public view returns(uint256) {
uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock);
return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval;
}
//schedules next turnament time(block)
function _scheduleTournament() internal {
//we can chedule only if there is nobody in tournament queue and
//time of tournament battle have passed
if (tournamentQueueSize == 0 && tournamentEndBlock <= block.number) {
tournamentEndBlock = ((FUND_GATHERING_TIME / 2 + ADMISSION_TIME) / secondsPerBlock) + block.number;
TournamentScheduled(tournamentEndBlock);
}
}
/// @dev Updates the minimum payment required for calling startPVP(). Can only
/// be called by the COO address, and only if pvp queue is empty.
function setPVPEntranceFee(uint256 value) external onlyOwner {
require(pvpQueueSize == 0);
pvpBattleFee = value;
}
//@returns PVP entrance fee for specified warrior level
//@param _levelPoints NB!
function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256) {
return pvpBattleFee * CryptoUtils._getLevel(_levelPoints);
}
//level can only be > 0 and <= 25
function _getPVPFeeByLevel(uint256 _level) internal view returns(uint256) {
return pvpBattleFee * _level;
}
// @dev Computes warrior pvp reward
// @param _totalBet - total bet from both competitors.
function _computePVPReward(uint256 _totalBet, uint256 _contendersCut) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalBet max value is 1000 finney, and _contendersCut aka
// (10000 - pvpOwnerCut - tournamentBankCut - incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalBet.
return _totalBet * _contendersCut / 10000;
}
function _getPVPContendersCut(uint256 _incentiveCut) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// (pvpOwnerCut + tournamentBankCut + pvpMaxIncentiveCut) <= 10000 (see the require()
// statement in the BattleProvider constructor).
// _incentiveCut is guaranteed to be >= 1 and <= pvpMaxIncentiveCut
return (10000 - pvpOwnerCut - tournamentBankCut - _incentiveCut);
}
// @dev Computes warrior pvp reward
// @param _totalSessionLoot - total bets from all competitors.
function _computeIncentiveReward(uint256 _totalSessionLoot, uint256 _incentiveCut) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * _incentiveCut / 10000;
}
///@dev computes incentive cut for specified loot,
/// Values 0-10,000 map to 0%-100%
/// max incentive reward cut is 5%, if it exceeds MAX_INCENTIVE_REWARD,
/// then cut is lowered to be equal to MAX_INCENTIVE_REWARD.
/// minimum cut is 0.01%
/// this % of the total bets will be sent as
/// a reward to address, that triggered finishPVP method
function _computeIncentiveCut(uint256 _totalSessionLoot, uint256 maxIncentiveCut) internal pure returns(uint256) {
uint256 result = _totalSessionLoot * maxIncentiveCut / 10000;
result = result <= MAX_INCENTIVE_REWARD ? maxIncentiveCut : MAX_INCENTIVE_REWARD * 10000 / _totalSessionLoot;
//min cut is 0.01%
return result > 0 ? result : 1;
}
// @dev Computes warrior pvp reward
// @param _totalSessionLoot - total bets from all competitors.
function _computePVPBeneficiaryFee(uint256 _totalSessionLoot) internal view returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * pvpOwnerCut / 10000;
}
// @dev Computes tournament bank cut
// @param _totalSessionLoot - total session loot.
function _computeTournamentCut(uint256 _totalSessionLoot) internal view returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * tournamentBankCut / 10000;
}
function indexOf(uint256 _warriorId) internal view returns(int256) {
uint256 length = uint256(pvpQueueSize);
for(uint256 i = 0; i < length; i ++) {
if(CryptoUtils._unpackIdValue(pvpQueue[i]) == _warriorId) return int256(i);
}
return -1;
}
function getPVPIncentiveReward(uint256[] memory matchingIds, uint256 matchingCount) internal view returns(uint256) {
uint256 sessionLoot = _computeTotalBooty(matchingIds, matchingCount);
return _computeIncentiveReward(sessionLoot, _computeIncentiveCut(sessionLoot, pvpMaxIncentiveCut));
}
function maxPVPContenders() external view returns(uint256){
return pvpQueue.length;
}
function getPVPState() external view returns
(uint256 contendersCount, uint256 matchingCount, uint256 endBlock, uint256 incentiveReward)
{
uint256[] memory pvpData = _packPVPData();
contendersCount = pvpQueueSize;
matchingCount = CryptoUtils._getMatchingIds(pvpData, PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL);
endBlock = nextPVPBatleBlock;
incentiveReward = getPVPIncentiveReward(pvpData, matchingCount);
}
function canFinishPVP() external view returns(bool) {
return nextPVPBatleBlock <= block.number &&
CryptoUtils._getMatchingIds(_packPVPData(), PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL) > 1;
}
function _clarifyPVPSchedule() internal {
uint256 length = pvpQueueSize;
uint256 currentBlock = block.number;
uint256 nextBattleBlock = nextPVPBatleBlock;
//if battle not scheduled, schedule battle
if (nextBattleBlock <= currentBlock) {
//if queue not empty update cycles
if (length > 0) {
uint256 packedWarrior;
uint256 cycleSkip = _computeCycleSkip();
for(uint256 i = 0; i < length; i++) {
packedWarrior = pvpQueue[i];
//increase warrior iteration cycle
pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + cycleSkip);
}
}
nextBattleBlock = (PVP_INTERVAL / secondsPerBlock) + currentBlock;
nextPVPBatleBlock = nextBattleBlock;
PVPScheduled(nextBattleBlock);
//if pvp queue will be full and there is still too much time left, then let the battle begin!
} else if (length + 1 == pvpQueue.length && (currentBlock + SAFETY_GAP * 2) < nextBattleBlock) {
nextBattleBlock = currentBlock + SAFETY_GAP;
nextPVPBatleBlock = nextBattleBlock;
PVPScheduled(nextBattleBlock);
}
}
/// @dev Internal utility function to initiate pvp battle, assumes that all battle
/// requirements have been checked.
function _triggerNewPVPContender(address _owner, uint256 _packedWarrior, uint256 fee) internal {
_clarifyPVPSchedule();
//number of pvp cycles the warrior is waiting for suitable enemy match
//increment every time when finishPVP is called and no suitable enemy match was found
_packedWarrior = CryptoUtils._changeCycleValue(_packedWarrior, 0);
//record contender data
pvpQueue[pvpQueueSize++] = _packedWarrior;
warriorToOwner[CryptoUtils._unpackIdValue(_packedWarrior)] = _owner;
//Emit event
PVPNewContender(_owner, CryptoUtils._unpackIdValue(_packedWarrior), fee);
}
function _noMatchingPairs() internal view returns(bool) {
uint256 matchingCount = CryptoUtils._getMatchingIds(_packPVPData(), uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL));
return matchingCount == 0;
}
/*
* @title startPVP enqueues specified warrior to PVP
*
* @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room.
* Once every 15 minutes, we check the warriors in the room and select pairs.
* For those warriors to whom we found couples, fighting is conducted and the results
* are recorded in the profile of the warrior.
*/
function addPVPContender(address _owner, uint256 _packedWarrior) external payable PVPNotPaused {
// Caller must be pvpListener contract
require(msg.sender == address(pvpListener));
require(_owner != address(0));
//contender can be added only while PVP is scheduled in future
//or no matching warrior pairs found
require(nextPVPBatleBlock > block.number || _noMatchingPairs());
// Check that the warrior exists.
require(_packedWarrior != 0);
//owner must withdraw all loot before contending pvp
require(ownerToBooty[_owner] == 0);
//check that there is enough room for new participants
require(pvpQueueSize < pvpQueue.length);
// Checks for payment.
uint256 fee = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarrior));
require(msg.value >= fee);
//
// All checks passed, put the warrior to the queue!
_triggerNewPVPContender(_owner, _packedWarrior, fee);
}
function _packPVPData() internal view returns(uint256[] memory matchingIds) {
uint256 length = pvpQueueSize;
matchingIds = new uint256[](length);
for(uint256 i = 0; i < length; i++) {
matchingIds[i] = pvpQueue[i];
}
return matchingIds;
}
function _computeTotalBooty(uint256[] memory _packedWarriors, uint256 matchingCount) internal view returns(uint256) {
//compute session booty
uint256 sessionLoot = 0;
for(uint256 i = 0; i < matchingCount; i++) {
sessionLoot += _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[i]));
}
return sessionLoot;
}
function _grandPVPRewards(uint256[] memory _packedWarriors, uint256 matchingCount)
internal returns(uint256)
{
uint256 booty = 0;
uint256 packedWarrior;
uint256 failedBooty = 0;
uint256 sessionBooty = _computeTotalBooty(_packedWarriors, matchingCount);
uint256 incentiveCut = _computeIncentiveCut(sessionBooty, pvpMaxIncentiveCut);
uint256 contendersCut = _getPVPContendersCut(incentiveCut);
for(uint256 id = 0; id < matchingCount; id++) {
//give reward to warriors that fought hard
//winner, even ids are winners!
packedWarrior = _packedWarriors[id];
//
//give winner deserved booty 80% from both bets
//must be computed before level reward!
booty = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(packedWarrior)) +
_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[id + 1]));
//
//send reward to warrior owner
failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut));
//loser, they are odd...
//skip them, as they deserve none!
id ++;
}
failedBooty += sendBooty(pvpListener.getBeneficiary(), _computePVPBeneficiaryFee(sessionBooty));
if (failedBooty > 0) {
totalBooty += failedBooty;
}
//if tournament admission start time not passed
//add tournament cut to current tournament bank,
//otherwise to next tournament bank
if (getTournamentAdmissionBlock() > block.number) {
currentTournamentBank += _computeTournamentCut(sessionBooty);
} else {
nextTournamentBank += _computeTournamentCut(sessionBooty);
}
//compute incentive reward
return _computeIncentiveReward(sessionBooty, incentiveCut);
}
function _increaseCycleAndTrimQueue(uint256[] memory matchingIds, uint256 matchingCount) internal {
uint32 length = uint32(matchingIds.length - matchingCount);
uint256 packedWarrior;
uint256 skipCycles = _computeCycleSkip();
for(uint256 i = 0; i < length; i++) {
packedWarrior = matchingIds[matchingCount + i];
//increase warrior iteration cycle
pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + skipCycles);
}
//trim queue
pvpQueueSize = length;
}
function _computeCycleSkip() internal view returns(uint256) {
uint256 number = block.number;
return nextPVPBatleBlock > number ? 0 : (number - nextPVPBatleBlock) * secondsPerBlock / PVP_INTERVAL + 1;
}
function _getWarriorOwners(uint256[] memory pvpData) internal view returns (address[] memory owners){
uint256 length = pvpData.length;
owners = new address[](length);
for(uint256 i = 0; i < length; i ++) {
owners[i] = warriorToOwner[CryptoUtils._unpackIdValue(pvpData[i])];
}
}
// @dev Internal utility function to initiate pvp battle, assumes that all battle
/// requirements have been checked.
function _triggerPVPFinish(uint256[] memory pvpData, uint256 matchingCount) internal returns(uint256){
//
//compute battle results
CryptoUtils._getPVPBattleResults(pvpData, matchingCount, nextPVPBatleBlock);
//
//mark not fought warriors and trim queue
_increaseCycleAndTrimQueue(pvpData, matchingCount);
//
//schedule next battle time
nextPVPBatleBlock = (PVP_INTERVAL / secondsPerBlock) + block.number;
//
//schedule tournament
//if contendersCount is 0 and tournament not scheduled, schedule tournament
//NB MUST be before _grandPVPRewards()
_scheduleTournament();
// compute and grand rewards to warriors,
// put tournament cut to bank, not susceptible to reentry attack because of require(nextPVPBatleBlock <= block.number);
// and require(number of pairs > 1);
uint256 incentiveReward = _grandPVPRewards(pvpData, matchingCount);
//
//notify pvp listener contract
pvpListener.pvpFinished(pvpData, matchingCount);
//
//fire event
PVPFinished(pvpData, _getWarriorOwners(pvpData), matchingCount);
PVPScheduled(nextPVPBatleBlock);
return incentiveReward;
}
/**
* @dev finishPVP this method finds matches of warrior pairs
* in waiting room and computes result of their fights.
*
* The winner gets +1 level, the loser gets +0.5 level
* The winning player gets +130 rating
* The losing player gets -30 or 70 rating (if warrior levelUps after battle) .
* can be called once in 15min.
* NB If the warrior is not picked up in an hour, then we expand the range
* of selection by 25 rating each hour.
*/
function finishPVP() public PVPNotPaused {
// battle interval is over
require(nextPVPBatleBlock <= block.number);
//
//match warriors
uint256[] memory pvpData = _packPVPData();
//match ids and sort them according to matching
uint256 matchingCount = CryptoUtils._getMatchingIds(pvpData, uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL));
// we have at least 1 matching battle pair
require(matchingCount > 1);
// When the all checks done, calculate actual battle result
uint256 incentiveReward = _triggerPVPFinish(pvpData, matchingCount);
//give reward for incentive
safeSend(msg.sender, incentiveReward);
}
// @dev Removes specified warrior from PVP queue
// sets warrior free (IDLE) and returns pvp entrance fee to owner
// @notice This is a state-modifying function that can
// be called while the contract is paused.
// @param _warriorId - ID of warrior in PVP queue
function removePVPContender(uint256 _warriorId) external{
uint256 queueSize = pvpQueueSize;
require(queueSize > 0);
// Caller must be owner of the specified warrior
require(warriorToOwner[_warriorId] == msg.sender);
//warrior must be in pvp queue
int256 warriorIndex = indexOf(_warriorId);
require(warriorIndex >= 0);
//grab warrior data
uint256 warriorData = pvpQueue[uint32(warriorIndex)];
//warrior cycle must be >= 4 (> than 1 hour)
require((CryptoUtils._unpackCycleValue(warriorData) + _computeCycleSkip()) >= 4);
//remove from queue
if (uint256(warriorIndex) < queueSize - 1) {
pvpQueue[uint32(warriorIndex)] = pvpQueue[pvpQueueSize - 1];
}
pvpQueueSize --;
//notify battle listener
pvpListener.pvpContenderRemoved(_warriorId);
//return pvp bet
msg.sender.transfer(_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData)));
//Emit event
PVPContenderRemoved(_warriorId, msg.sender);
}
function getPVPCycles(uint32[] warriorIds) external view returns(uint32[]){
uint256 length = warriorIds.length;
uint32[] memory cycles = new uint32[](length);
int256 index;
uint256 skipCycles = _computeCycleSkip();
for(uint256 i = 0; i < length; i ++) {
index = indexOf(warriorIds[i]);
cycles[i] = index >= 0 ? uint32(CryptoUtils._unpackCycleValue(pvpQueue[uint32(index)]) + skipCycles) : 0;
}
return cycles;
}
// @dev Remove all PVP contenders from PVP queue
// and return all bets to warrior owners.
// NB: this is emergency method, used only in f%#^@up situation
function removeAllPVPContenders() external onlyOwner PVPPaused {
//remove all pvp contenders
uint256 length = pvpQueueSize;
uint256 warriorData;
uint256 warriorId;
uint256 failedBooty;
address owner;
pvpQueueSize = 0;
for(uint256 i = 0; i < length; i++) {
//grab warrior data
warriorData = pvpQueue[i];
warriorId = CryptoUtils._unpackIdValue(warriorData);
//notify battle listener
pvpListener.pvpContenderRemoved(uint32(warriorId));
owner = warriorToOwner[warriorId];
//return pvp bet
failedBooty += sendBooty(owner, _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData)));
}
totalBooty += failedBooty;
}
}
contract Tournament is PVP {
uint256 internal constant GROUP_SIZE = 5;
uint256 internal constant DATA_SIZE = 2;
uint256 internal constant THRESHOLD = 300;
/** list of warrior IDs that will participate in next tournament.
* Fixed size arry, to evade constant remove and push operations,
* this approach reduces transaction costs involving array modification. */
uint256[160] public tournamentQueue;
/**The cost of participation in the tournament is 1% of its current prize fund,
* money is added to the prize fund. measured in basis points (1/100 of a percent).
* Values 0-10,000 map to 0%-100% */
uint256 internal tournamentEntranceFeeCut = 100;
// Values 0-10,000 map to 0%-100% => 20%
uint256 public tournamentOwnersCut;
uint256 public tournamentIncentiveCut;
/** @dev TournamentNewContender event. Emitted every time a warrior enters tournament
* @param owner Warrior owner
* @param warriorIds 5 Warrior IDs that entered tournament, packed into one uint256
* see CryptoUtils._packWarriorIds
*/
event TournamentNewContender(address owner, uint256 warriorIds, uint256 entranceFee);
/** @dev TournamentFinished event. Emitted every time a tournament is finished
* @param owners array of warrior group owners packed to uint256
* @param results number of wins for each group
* @param tournamentBank current tournament bank
* see CryptoUtils._packWarriorIds
*/
event TournamentFinished(uint256[] owners, uint32[] results, uint256 tournamentBank);
function Tournament(uint256 _pvpCut, uint256 _tournamentBankCut,
uint256 _pvpMaxIncentiveCut, uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public
PVP(_pvpCut, _tournamentBankCut, _pvpMaxIncentiveCut)
{
require((_tournamentOwnersCut + _tournamentIncentiveCut) <= 10000);
tournamentOwnersCut = _tournamentOwnersCut;
tournamentIncentiveCut = _tournamentIncentiveCut;
}
// @dev Computes incentive reward for launching tournament finishTournament()
// @param _tournamentBank
function _computeTournamentIncentiveReward(uint256 _currentBank, uint256 _incentiveCut) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney,
// and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require()
// statement in the Tournament constructor). The result of this
// function is always guaranteed to be <= _currentBank.
return _currentBank * _incentiveCut / 10000;
}
function _computeTournamentContenderCut(uint256 _incentiveCut) internal view returns (uint256) {
// NOTE: (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require()
// statement in the Tournament constructor). The result of this
// function is always guaranteed to be <= _reward.
return 10000 - tournamentOwnersCut - _incentiveCut;
}
function _computeTournamentBeneficiaryFee(uint256 _currentBank) internal view returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney,
// and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require()
// statement in the Tournament constructor). The result of this
// function is always guaranteed to be <= _currentBank.
return _currentBank * tournamentOwnersCut / 10000;
}
// @dev set tournament entrance fee cut, can be set only if
// tournament queue is empty
// @param _cut range from 0 - 10000, mapped to 0-100%
function setTournamentEntranceFeeCut(uint256 _cut) external onlyOwner {
//cut must be less or equal 100&
require(_cut <= 10000);
//tournament queue must be empty
require(tournamentQueueSize == 0);
//checks passed, set cut
tournamentEntranceFeeCut = _cut;
}
function getTournamentEntranceFee() external view returns(uint256) {
return currentTournamentBank * tournamentEntranceFeeCut / 10000;
}
//@dev returns tournament entrance fee - 3% threshold
function getTournamentThresholdFee() public view returns(uint256) {
return currentTournamentBank * tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 / 10000;
}
//@dev returns max allowed tournament contenders, public because of internal use
function maxTournamentContenders() public view returns(uint256){
return tournamentQueue.length / DATA_SIZE;
}
function canFinishTournament() external view returns(bool) {
return tournamentEndBlock <= block.number && tournamentQueueSize > 0;
}
// @dev Internal utility function to sigin up to tournament,
// assumes that all battle requirements have been checked.
function _triggerNewTournamentContender(address _owner, uint256[] memory _tournamentData, uint256 _fee) internal {
//pack warrior ids into uint256
currentTournamentBank += _fee;
uint256 packedWarriorIds = CryptoUtils._packWarriorIds(_tournamentData);
//make composite warrior out of 5 warriors
uint256 combinedWarrior = CryptoUtils._combineWarriors(_tournamentData);
//add to queue
//icrement tournament queue
uint256 size = tournamentQueueSize++ * DATA_SIZE;
//record tournament data
tournamentQueue[size++] = packedWarriorIds;
tournamentQueue[size++] = combinedWarrior;
warriorToOwner[CryptoUtils._unpackWarriorId(packedWarriorIds, 0)] = _owner;
//
//Emit event
TournamentNewContender(_owner, packedWarriorIds, _fee);
}
function addTournamentContender(address _owner, uint256[] _tournamentData) external payable TournamentNotPaused{
// Caller must be pvpListener contract
require(msg.sender == address(pvpListener));
require(_owner != address(0));
//
//check current tournament bank > 0
require(pvpBattleFee == 0 || currentTournamentBank > 0);
//
//check that there is enough funds to pay entrance fee
uint256 fee = getTournamentThresholdFee();
require(msg.value >= fee);
//owner must withdraw all booty before contending pvp
require(ownerToBooty[_owner] == 0);
//
//check that warriors group is exactly of allowed size
require(_tournamentData.length == GROUP_SIZE);
//
//check that there is enough room for new participants
require(tournamentQueueSize < maxTournamentContenders());
//
//check that admission started
require(block.number >= getTournamentAdmissionBlock());
//check that admission not ended
require(block.number <= tournamentEndBlock);
//all checks passed, trigger sign up
_triggerNewTournamentContender(_owner, _tournamentData, fee);
}
//@dev collect all combined warriors data
function getCombinedWarriors() internal view returns(uint256[] memory warriorsData) {
uint256 length = tournamentQueueSize;
warriorsData = new uint256[](length);
for(uint256 i = 0; i < length; i ++) {
// Grab the combined warrior data in storage.
warriorsData[i] = tournamentQueue[i * DATA_SIZE + 1];
}
return warriorsData;
}
function getTournamentState() external view returns
(uint256 contendersCount, uint256 bank, uint256 admissionStartBlock, uint256 endBlock, uint256 incentiveReward)
{
contendersCount = tournamentQueueSize;
bank = currentTournamentBank;
admissionStartBlock = getTournamentAdmissionBlock();
endBlock = tournamentEndBlock;
incentiveReward = _computeTournamentIncentiveReward(bank, _computeIncentiveCut(bank, tournamentIncentiveCut));
}
function _repackToCombinedIds(uint256[] memory _warriorsData) internal view {
uint256 length = _warriorsData.length;
for(uint256 i = 0; i < length; i ++) {
_warriorsData[i] = tournamentQueue[i * DATA_SIZE];
}
}
// @dev Computes warrior pvp reward
// @param _totalBet - total bet from both competitors.
function _computeTournamentBooty(uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney,
// _totalBattles is guaranteed to be > 0 and <= 400, and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require()
// statement in the Tournament constructor). The result of this
// function is always guaranteed to be <= _reward.
// return _currentBank * (10000 - tournamentOwnersCut - _incentiveCut) * _result / 10000 / _totalBattles;
return _currentBank * _contenderResult / _totalBattles;
}
function _grandTournamentBooty(uint256 _warriorIds, uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles)
internal returns (uint256)
{
uint256 warriorId = CryptoUtils._unpackWarriorId(_warriorIds, 0);
address owner = warriorToOwner[warriorId];
uint256 booty = _computeTournamentBooty(_currentBank, _contenderResult, _totalBattles);
return sendBooty(owner, booty);
}
function _grandTournamentRewards(uint256 _currentBank, uint256[] memory _warriorsData, uint32[] memory _results) internal returns (uint256){
uint256 length = _warriorsData.length;
uint256 totalBattles = CryptoUtils._getTournamentBattles(length) * 10000;//*10000 required for booty computation
uint256 incentiveCut = _computeIncentiveCut(_currentBank, tournamentIncentiveCut);
uint256 contenderCut = _computeTournamentContenderCut(incentiveCut);
uint256 failedBooty = 0;
for(uint256 i = 0; i < length; i ++) {
//grand rewards
failedBooty += _grandTournamentBooty(_warriorsData[i], _currentBank, _results[i] * contenderCut, totalBattles);
}
//send beneficiary fee
failedBooty += sendBooty(pvpListener.getBeneficiary(), _computeTournamentBeneficiaryFee(_currentBank));
if (failedBooty > 0) {
totalBooty += failedBooty;
}
return _computeTournamentIncentiveReward(_currentBank, incentiveCut);
}
function _repackToWarriorOwners(uint256[] memory warriorsData) internal view {
uint256 length = warriorsData.length;
for (uint256 i = 0; i < length; i ++) {
warriorsData[i] = uint256(warriorToOwner[CryptoUtils._unpackWarriorId(warriorsData[i], 0)]);
}
}
function _triggerFinishTournament() internal returns(uint256){
//hold 10 random battles for each composite warrior
uint256[] memory warriorsData = getCombinedWarriors();
uint32[] memory results = CryptoUtils.getTournamentBattleResults(warriorsData, tournamentEndBlock - 1);
//repack combined warriors id
_repackToCombinedIds(warriorsData);
//notify pvp listener
pvpListener.tournamentFinished(warriorsData);
//reschedule
//clear tournament
tournamentQueueSize = 0;
//schedule new tournament
_scheduleTournament();
uint256 currentBank = currentTournamentBank;
currentTournamentBank = 0;//nullify before sending to users
//grand rewards, not susceptible to reentry attack
//because of require(tournamentEndBlock <= block.number)
//and require(tournamentQueueSize > 0) and currentTournamentBank == 0
uint256 incentiveReward = _grandTournamentRewards(currentBank, warriorsData, results);
currentTournamentBank = nextTournamentBank;
nextTournamentBank = 0;
_repackToWarriorOwners(warriorsData);
//emit event
TournamentFinished(warriorsData, results, currentBank);
return incentiveReward;
}
function finishTournament() external TournamentNotPaused {
//make all the checks
// tournament is ready to be executed
require(tournamentEndBlock <= block.number);
// we have participants
require(tournamentQueueSize > 0);
uint256 incentiveReward = _triggerFinishTournament();
//give reward for incentive
safeSend(msg.sender, incentiveReward);
}
// @dev Remove all PVP contenders from PVP queue
// and return all entrance fees to warrior owners.
// NB: this is emergency method, used only in f%#^@up situation
function removeAllTournamentContenders() external onlyOwner TournamentPaused {
//remove all pvp contenders
uint256 length = tournamentQueueSize;
uint256 warriorId;
uint256 failedBooty;
uint256 i;
uint256 fee;
uint256 bank = currentTournamentBank;
uint256[] memory warriorsData = new uint256[](length);
//get tournament warriors
for(i = 0; i < length; i ++) {
warriorsData[i] = tournamentQueue[i * DATA_SIZE];
}
//notify pvp listener
pvpListener.tournamentFinished(warriorsData);
//return entrance fee to warrior owners
currentTournamentBank = 0;
tournamentQueueSize = 0;
for(i = length - 1; i >= 0; i --) {
//return entrance fee
warriorId = CryptoUtils._unpackWarriorId(warriorsData[i], 0);
//compute contender entrance fee
fee = bank - (bank * 10000 / (tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 + 10000));
//return entrance fee to owner
failedBooty += sendBooty(warriorToOwner[warriorId], fee);
//subtract fee from bank, for next use
bank -= fee;
}
currentTournamentBank = bank;
totalBooty += failedBooty;
}
}
contract BattleProvider is Tournament {
function BattleProvider(address _pvpListener, uint256 _pvpCut, uint256 _tournamentCut, uint256 _incentiveCut,
uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public
Tournament(_pvpCut, _tournamentCut, _incentiveCut, _tournamentOwnersCut, _tournamentIncentiveCut)
{
PVPListenerInterface candidateContract = PVPListenerInterface(_pvpListener);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isPVPListener());
// Set the new contract address
pvpListener = candidateContract;
// the creator of the contract is the initial owner
owner = msg.sender;
}
// @dev Sanity check that allows us to ensure that we are pointing to the
// right BattleProvider in our setBattleProviderAddress() call.
function isPVPProvider() external pure returns (bool) {
return true;
}
function setSecondsPerBlock(uint256 secs) external onlyOwner {
secondsPerBlock = secs;
}
}
/* warrior identity generator*/
contract WarriorGenerator is Pausable, SanctuaryInterface {
CryptoWarriorCore public coreContract;
/* LIMITS */
uint32[19] public parameters;/* = [
uint32(10),//0_bodyColorMax3
uint32(10),//1_eyeshMax4
uint32(10),//2_mouthMax5
uint32(20),//3_heirMax6
uint32(10),//4_heirColorMax7
uint32(3),//5_armorMax8
uint32(3),//6_weaponMax9
uint32(3),//7_hatMax10
uint32(4),//8_runesMax11
uint32(1),//9_wingsMax12
uint32(10),//10_petMax13
uint32(6),//11_borderMax14
uint32(6),//12_backgroundMax15
uint32(10),//13_unique
uint32(900),//14_legendary
uint32(9000),//15_mythic
uint32(90000),//16_rare
uint32(900000),//17_uncommon
uint32(0)//18_uniqueTotal
];*/
function changeParameter(uint32 _paramIndex, uint32 _value) external onlyOwner {
CryptoUtils._changeParameter(_paramIndex, _value, parameters);
}
// / @dev simply a boolean to indicate this is the contract we expect to be
function isSanctuary() public pure returns (bool){
return true;
}
// / @dev generate new warrior identity
// / @param _heroIdentity Genes of warrior that invoked resurrection, if 0 => Demigod gene that signals to generate unique warrior
// / @param _heroLevel Level of the warrior
// / @_targetBlock block number from which hash will be taken
// / @_perkId special perk id, like MINER(1)
// / @return the identity that are supposed to be passed down to newly arisen warrior
function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId)
public returns (uint256)
{
//only core contract can call this method
require(msg.sender == address(coreContract));
return _generateIdentity(_heroIdentity, _heroLevel, _targetBlock, _perkId);
}
function _generateIdentity(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) internal returns(uint256){
//get memory copy, to reduce storage read requests
uint32[19] memory memoryParams = parameters;
//generate warrior identity
uint256 identity = CryptoUtils.generateWarrior(_heroIdentity, _heroLevel, _targetBlock, _perkId, memoryParams);
//validate before pushing changes to storage
CryptoUtils._validateIdentity(identity, memoryParams);
//push changes to storage
CryptoUtils._recordWarriorData(identity, parameters);
return identity;
}
}
contract WarriorSanctuary is WarriorGenerator {
uint256 internal constant SUMMONING_SICKENESS = 12 hours;
uint256 internal constant RITUAL_DURATION = 15 minutes;
/// @notice The payment required to use startRitual().
uint256 public ritualFee = 10 finney;
uint256 public constant RITUAL_COMPENSATION = 2 finney;
mapping(address => uint256) public soulCounter;
//
mapping(address => uint256) public ritualTimeBlock;
bool public recoveryAllowed = true;
event WarriorBurned(uint256 warriorId, address owner);
event RitualStarted(address owner, uint256 numberOfSouls);
event RitualFinished(address owner, uint256 numberOfSouls, uint256 newWarriorId);
function WarriorSanctuary(address _coreContract, uint32[] _settings) public {
uint256 length = _settings.length;
require(length == 18);
require(_settings[8] == 4);//check runes max
require(_settings[10] == 10);//check pets max
require(_settings[11] == 5);//check border max
require(_settings[12] == 6);//check background max
//setup parameters
for(uint256 i = 0; i < length; i ++) {
parameters[i] = _settings[i];
}
//set core
CryptoWarriorCore coreCondidat = CryptoWarriorCore(_coreContract);
require(coreCondidat.isPVPListener());
coreContract = coreCondidat;
}
function recoverSouls(address[] owners, uint256[] souls, uint256[] blocks) external onlyOwner {
require(recoveryAllowed);
uint256 length = owners.length;
require(length == souls.length && length == blocks.length);
for(uint256 i = 0; i < length; i ++) {
soulCounter[owners[i]] = souls[i];
ritualTimeBlock[owners[i]] = blocks[i];
}
recoveryAllowed = false;
}
//burn warrior
function burnWarrior(uint256 _warriorId) whenNotPaused external {
coreContract.burnWarrior(_warriorId, msg.sender);
soulCounter[msg.sender] ++;
WarriorBurned(_warriorId, msg.sender);
}
function startRitual() whenNotPaused external payable {
// Checks for payment.
require(msg.value >= ritualFee);
uint256 souls = soulCounter[msg.sender];
// Check that address has at least 10 burned souls
require(souls >= 10);
//
//Check that no rituals are in progress
require(ritualTimeBlock[msg.sender] == 0);
ritualTimeBlock[msg.sender] = RITUAL_DURATION / coreContract.secondsPerBlock() + block.number;
// Calculate any excess funds included in msg.value. If the excess
// is anything worth worrying about, transfer it back to message owner.
// NOTE: We checked above that the msg.value is greater than or
// equal to the price so this cannot underflow.
uint256 feeExcess = msg.value - ritualFee;
// Return the funds. This is not susceptible
// to a re-entry attack because of _isReadyToPVE check
// will fail
if (feeExcess > 0) {
msg.sender.transfer(feeExcess);
}
//send battle fee to beneficiary
coreContract.getBeneficiary().transfer(ritualFee - RITUAL_COMPENSATION);
RitualStarted(msg.sender, souls);
}
//arise warrior
function finishRitual(address _owner) whenNotPaused external {
// Check ritual time is over
uint256 timeBlock = ritualTimeBlock[_owner];
require(timeBlock > 0 && timeBlock <= block.number);
uint256 souls = soulCounter[_owner];
require(souls >= 10);
uint256 identity = _generateIdentity(uint256(_owner), souls, timeBlock - 1, 0);
uint256 warriorId = coreContract.ariseWarrior(identity, _owner, block.number + (SUMMONING_SICKENESS / coreContract.secondsPerBlock()));
soulCounter[_owner] = 0;
ritualTimeBlock[_owner] = 0;
//send compensation
msg.sender.transfer(RITUAL_COMPENSATION);
RitualFinished(_owner, 10, warriorId);
}
function setRitualFee(uint256 _pveRitualFee) external onlyOwner {
require(_pveRitualFee > RITUAL_COMPENSATION);
ritualFee = _pveRitualFee;
}
}
contract AuctionBase {
uint256 public constant PRICE_CHANGE_TIME_STEP = 15 minutes;
//
struct Auction{
address seller;
uint128 startingPrice;
uint128 endingPrice;
uint64 duration;
uint64 startedAt;
}
mapping (uint256 => Auction) internal tokenIdToAuction;
uint256 public ownerCut;
ERC721 public nonFungibleContract;
event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller);
event AuctionCancelled(uint256 tokenId, address seller);
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool){
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
function _escrow(address _owner, uint256 _tokenId) internal{
nonFungibleContract.transferFrom(_owner, address(this), _tokenId);
}
function _transfer(address _receiver, uint256 _tokenId) internal{
nonFungibleContract.transfer(_receiver, _tokenId);
}
function _addAuction(uint256 _tokenId, Auction _auction) internal{
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(uint256(_tokenId), _auction.seller, _auction.startingPrice);
}
function _cancelAuction(uint256 _tokenId, address _seller) internal{
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId, _seller);
}
function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256){
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
address seller = auction.seller;
_removeAuction(_tokenId);
if (price > 0) {
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
nonFungibleContract.getBeneficiary().transfer(auctioneerCut);
}
uint256 bidExcess = _bidAmount - price;
msg.sender.transfer(bidExcess);
AuctionSuccessful(_tokenId, price, msg.sender, seller);
return price;
}
function _removeAuction(uint256 _tokenId) internal{
delete tokenIdToAuction[_tokenId];
}
function _isOnAuction(Auction storage _auction) internal view returns (bool){
return (_auction.startedAt > 0);
}
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256){
uint256 secondsPassed = 0;
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed);
}
function _computeCurrentPrice(uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed)
internal
pure
returns (uint256){
if (_secondsPassed >= _duration) {
return _endingPrice;
} else {
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed / PRICE_CHANGE_TIME_STEP * PRICE_CHANGE_TIME_STEP) / int256(_duration);
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
function _computeCut(uint256 _price) internal view returns (uint256){
return _price * ownerCut / 10000;
}
}
contract SaleClockAuction is Pausable, AuctionBase {
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9f40b779);
bool public isSaleClockAuction = true;
uint256 public minerSaleCount;
uint256[5] public lastMinerSalePrices;
function SaleClockAuction(address _nftAddress, uint256 _cut) public{
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
require(candidateContract.getBeneficiary() != address(0));
nonFungibleContract = candidateContract;
}
function cancelAuction(uint256 _tokenId)
external{
AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external{
AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256){
AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
function createAuction(uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller)
whenNotPaused
external{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
AuctionBase.Auction memory auction = Auction(_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now));
_addAuction(_tokenId, auction);
}
function bid(uint256 _tokenId)
whenNotPaused
external
payable{
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
if (seller == nonFungibleContract.getBeneficiary()) {
lastMinerSalePrices[minerSaleCount % 5] = price;
minerSaleCount++;
}
}
function averageMinerSalePrice() external view returns (uint256){
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++){
sum += lastMinerSalePrices[i];
}
return sum / 5;
}
/**getAuctionsById returns packed actions data
* @param tokenIds ids of tokens, whose auction's must be active
* @return auctionData as uint256 array
* @return stepSize number of fields describing auction
*/
function getAuctionsById(uint32[] tokenIds) external view returns(uint256[] memory auctionData, uint32 stepSize) {
stepSize = 6;
auctionData = new uint256[](tokenIds.length * stepSize);
uint32 tokenId;
for(uint32 i = 0; i < tokenIds.length; i ++) {
tokenId = tokenIds[i];
AuctionBase.Auction storage auction = tokenIdToAuction[tokenId];
require(_isOnAuction(auction));
_setTokenData(auctionData, auction, tokenId, i * stepSize);
}
}
/**getAuctions returns packed actions data
* @param fromIndex warrior index from global warrior storage (aka warriorId)
* @param count Number of auction's to find, if count == 0, then exact warriorId(fromIndex) will be searched
* @return auctionData as uint256 array
* @return stepSize number of fields describing auction
*/
function getAuctions(uint32 fromIndex, uint32 count) external view returns(uint256[] memory auctionData, uint32 stepSize) {
stepSize = 6;
if (count == 0) {
AuctionBase.Auction storage auction = tokenIdToAuction[fromIndex];
require(_isOnAuction(auction));
auctionData = new uint256[](1 * stepSize);
_setTokenData(auctionData, auction, fromIndex, count);
return (auctionData, stepSize);
} else {
uint256 totalWarriors = nonFungibleContract.totalSupply();
if (totalWarriors == 0) {
// Return an empty array
return (new uint256[](0), stepSize);
} else {
uint32 totalSize = 0;
uint32 tokenId;
uint32 size = 0;
auctionData = new uint256[](count * stepSize);
for (tokenId = 0; tokenId < totalWarriors && size < count; tokenId++) {
AuctionBase.Auction storage auction1 = tokenIdToAuction[tokenId];
if (_isOnAuction(auction1)) {
totalSize ++;
if (totalSize > fromIndex) {
_setTokenData(auctionData, auction1, tokenId, size++ * stepSize);//warriorId;
}
}
}
if (size < count) {
size *= stepSize;
uint256[] memory repack = new uint256[](size);
for(tokenId = 0; tokenId < size; tokenId++) {
repack[tokenId] = auctionData[tokenId];
}
return (repack, stepSize);
}
return (auctionData, stepSize);
}
}
}
// @dev Returns auction info for an NFT on auction.
// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId) external view returns(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
){
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt);
}
//pack NFT data into specified array
function _setTokenData(uint256[] memory auctionData,
AuctionBase.Auction storage auction, uint32 tokenId, uint32 index
) internal view {
auctionData[index] = uint256(tokenId);//0
auctionData[index + 1] = uint256(auction.seller);//1
auctionData[index + 2] = uint256(auction.startingPrice);//2
auctionData[index + 3] = uint256(auction.endingPrice);//3
auctionData[index + 4] = uint256(auction.duration);//4
auctionData[index + 5] = uint256(auction.startedAt);//5
}
} | arise warrior Check ritual time is oversend compensation | function finishRitual(address _owner) whenNotPaused external {
uint256 timeBlock = ritualTimeBlock[_owner];
require(timeBlock > 0 && timeBlock <= block.number);
uint256 souls = soulCounter[_owner];
require(souls >= 10);
uint256 identity = _generateIdentity(uint256(_owner), souls, timeBlock - 1, 0);
uint256 warriorId = coreContract.ariseWarrior(identity, _owner, block.number + (SUMMONING_SICKENESS / coreContract.secondsPerBlock()));
soulCounter[_owner] = 0;
ritualTimeBlock[_owner] = 0;
msg.sender.transfer(RITUAL_COMPENSATION);
RitualFinished(_owner, 10, warriorId);
}
| 5,942,480 |
./partial_match/42/0x142201C24af5095EDED6D6A8F500B2f05E08f523/sources/Depot.sol | Fallback function (exchanges ETH to xUSD)/ | function() external payable {
exchangeEtherForSynths();
}
| 3,468,490 |
./full_match/43114/0xCCB8aDAFfF911be27E51c6CCB03fae041d391454/sources/contracts/avaxsnob.sol | Anyone can harvest it at any given time. I understand the possibility of being frontrun But AVAX is a dark forest, and I wanna see how this plays out i.e. will be be heavily frontrunned? if so, a new strategy will be deployed. Collects Joe tokens 10% is sent to treasury Donates DUST | function harvest() public override onlyBenevolent {
IMasterChefJoeV2(masterChefJoeV3).deposit(poolId, 0);
uint256 _joe = IERC20(joe).balanceOf(address(this));
if (_joe > 0) {
uint256 _keep = _joe.mul(keep).div(keepMax);
uint256 _amount = _joe.sub(_keep).div(2);
if (_keep > 0) {
_takeFeeJoeToSnob(_keep);
}
IERC20(joe).safeApprove(joeRouter, 0);
IERC20(joe).safeApprove(joeRouter, _joe.sub(_keep));
_swapTraderJoe(joe, wavax, _amount);
_swapTraderJoe(joe, snob, _amount);
}
uint256 _snob = IERC20(snob).balanceOf(address(this));
if (_wavax > 0 && _snob > 0) {
IERC20(wavax).safeApprove(joeRouter, 0);
IERC20(wavax).safeApprove(joeRouter, _wavax);
IERC20(snob).safeApprove(joeRouter, 0);
IERC20(snob).safeApprove(joeRouter, _snob);
IJoeRouter(joeRouter).addLiquidity(
wavax,
snob,
_wavax,
_snob,
0,
0,
address(this),
now + 60
);
IERC20(wavax).transfer(
IController(controller).treasury(),
IERC20(wavax).balanceOf(address(this))
);
IERC20(snob).safeTransfer(
IController(controller).treasury(),
IERC20(snob).balanceOf(address(this))
);
}
_distributePerformanceFeesAndDeposit();
}
| 4,511,960 |
./partial_match/1/0x47B0f414d5298CFFF5E043767d6715E2a5D92CC6/sources/BoiChillClub.sol | Returns the total number of tokens minted. return The total number of tokens minted./ | function totalMinted() external view returns (uint256) {
return _idCounter - 1;
}
| 4,455,950 |
pragma solidity ^0.4.18; // solhint-disable-line
contract VerifyToken {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
bool public activated;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract EthVerifyCore{
mapping (address => bool) public verifiedUsers;
}
contract ShrimpFarmer is ApproveAndCallFallBack{
using SafeMath for uint;
address vrfAddress=0x5BD574410F3A2dA202bABBa1609330Db02aD64C2;
VerifyToken vrfcontract=VerifyToken(vrfAddress);
//257977574257854071311765966
// 10000000000
//uint256 EGGS_PER_SHRIMP_PER_SECOND=1;
uint256 public EGGS_TO_HATCH_1SHRIMP=86400;//86400
uint public VRF_EGG_COST=(1000000000000000000*300)/EGGS_TO_HATCH_1SHRIMP;
uint256 public STARTING_SHRIMP=300;
uint256 PSN=100000000000000;
uint256 PSNH=50000000000000;
uint public potDrainTime=2 hours;//
uint public POT_DRAIN_INCREMENT=1 hours;
uint public POT_DRAIN_MAX=3 days;
uint public HATCH_COOLDOWN_MAX=6 hours;//6 hours;
bool public initialized=false;
//bool public completed=false;
address public ceoAddress;
address public dev2;
mapping (address => uint256) public hatchCooldown;//the amount of time you must wait now varies per user
mapping (address => uint256) public hatcheryShrimp;
mapping (address => uint256) public claimedEggs;
mapping (address => uint256) public lastHatch;
mapping (address => bool) public hasClaimedFree;
uint256 public marketEggs;
EthVerifyCore public ethVerify=EthVerifyCore(0x1c307A39511C16F74783fCd0091a921ec29A0b51);
uint public lastBidTime;//last time someone bid for the pot
address public currentWinner;
uint public potEth=0;//eth specifically set aside for the pot
uint public totalHatcheryShrimp=0;
uint public prizeEth=0;
function ShrimpFarmer() public{
ceoAddress=msg.sender;
dev2=address(0x95096780Efd48FA66483Bc197677e89f37Ca0CB5);
lastBidTime=now;
currentWinner=msg.sender;
}
function finalizeIfNecessary() public{
if(lastBidTime.add(potDrainTime)<now){
currentWinner.transfer(this.balance);//winner gets everything
initialized=false;
//completed=true;
}
}
function getPotCost() public view returns(uint){
return totalHatcheryShrimp.div(100);
}
function stealPot() public {
if(initialized){
_hatchEggs(0);
uint cost=getPotCost();
hatcheryShrimp[msg.sender]=hatcheryShrimp[msg.sender].sub(cost);//cost is 1% of total shrimp
totalHatcheryShrimp=totalHatcheryShrimp.sub(cost);
setNewPotWinner();
hatchCooldown[msg.sender]=0;
}
}
function setNewPotWinner() private {
finalizeIfNecessary();
if(initialized && msg.sender!=currentWinner){
potDrainTime=lastBidTime.add(potDrainTime).sub(now).add(POT_DRAIN_INCREMENT);//time left plus one hour
if(potDrainTime>POT_DRAIN_MAX){
potDrainTime=POT_DRAIN_MAX;
}
lastBidTime=now;
currentWinner=msg.sender;
}
}
function isHatchOnCooldown() public view returns(bool){
return lastHatch[msg.sender].add(hatchCooldown[msg.sender])<now;
}
function hatchEggs(address ref) public{
require(isHatchOnCooldown());
_hatchEggs(ref);
}
function _hatchEggs(address ref) private{
require(initialized);
uint256 eggsUsed=getMyEggs();
uint256 newShrimp=SafeMath.div(eggsUsed,EGGS_TO_HATCH_1SHRIMP);
hatcheryShrimp[msg.sender]=SafeMath.add(hatcheryShrimp[msg.sender],newShrimp);
totalHatcheryShrimp=totalHatcheryShrimp.add(newShrimp);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
hatchCooldown[msg.sender]=HATCH_COOLDOWN_MAX;
//send referral eggs
require(ref!=msg.sender);
if(ref!=0){
claimedEggs[ref]=claimedEggs[ref].add(eggsUsed.div(7));
}
//boost market to nerf shrimp hoarding
marketEggs=SafeMath.add(marketEggs,SafeMath.div(eggsUsed,7));
}
function getHatchCooldown(uint eggs) public view returns(uint){
uint targetEggs=marketEggs.div(50);
if(eggs>=targetEggs){
return HATCH_COOLDOWN_MAX;
}
return (HATCH_COOLDOWN_MAX.mul(eggs)).div(targetEggs);
}
function reduceHatchCooldown(address addr,uint eggs) private{
uint reduction=getHatchCooldown(eggs);
if(reduction>=hatchCooldown[addr]){
hatchCooldown[addr]=0;
}
else{
hatchCooldown[addr]=hatchCooldown[addr].sub(reduction);
}
}
function sellEggs() public{
require(initialized);
finalizeIfNecessary();
uint256 hasEggs=getMyEggs();
uint256 eggValue=calculateEggSell(hasEggs);
//uint256 fee=devFee(eggValue);
uint potfee=potFee(eggValue);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
marketEggs=SafeMath.add(marketEggs,hasEggs);
//ceoAddress.transfer(fee);
prizeEth=prizeEth.add(potfee);
msg.sender.transfer(eggValue.sub(potfee));
}
function buyEggs() public payable{
require(initialized);
uint256 eggsBought=calculateEggBuy(msg.value,SafeMath.sub(this.balance,msg.value));
eggsBought=eggsBought.sub(devFee(eggsBought));
eggsBought=eggsBought.sub(devFee2(eggsBought));
ceoAddress.transfer(devFee(msg.value));
dev2.transfer(devFee2(msg.value));
claimedEggs[msg.sender]=SafeMath.add(claimedEggs[msg.sender],eggsBought);
reduceHatchCooldown(msg.sender,eggsBought); //reduce the hatching cooldown based on eggs bought
//steal the pot if bought enough
uint potEggCost=getPotCost().mul(EGGS_TO_HATCH_1SHRIMP);//the equivalent number of eggs to the pot cost in shrimp
if(eggsBought>potEggCost){
//hatcheryShrimp[msg.sender]=hatcheryShrimp[msg.sender].add(getPotCost());//to compensate for the shrimp that will be lost when calling the following
//stealPot();
setNewPotWinner();
}
}
//magic trade balancing algorithm
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
//(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt));
return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt)));
}
function calculateEggSell(uint256 eggs) public view returns(uint256){
return calculateTrade(eggs,marketEggs,this.balance.sub(prizeEth));
}
function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth,contractBalance.sub(prizeEth),marketEggs);
}
function calculateEggBuySimple(uint256 eth) public view returns(uint256){
return calculateEggBuy(eth,this.balance);
}
function potFee(uint amount) public view returns(uint){
return SafeMath.div(SafeMath.mul(amount,20),100);
}
function devFee(uint256 amount) public view returns(uint256){
return SafeMath.div(SafeMath.mul(amount,4),100);
}
function devFee2(uint256 amount) public view returns(uint256){
return SafeMath.div(amount,100);
}
function seedMarket(uint256 eggs) public payable{
require(msg.sender==ceoAddress);
require(!initialized);
//require(marketEggs==0);
initialized=true;
marketEggs=eggs;
lastBidTime=now;
}
//Tokens are exchanged for shrimp by sending them to this contract with ApproveAndCall
function receiveApproval(address from, uint256 tokens, address token, bytes data) public{
require(!initialized);
require(msg.sender==vrfAddress);
require(ethVerify.verifiedUsers(from));//you must now be verified for this
require(claimedEggs[from].add(tokens.div(VRF_EGG_COST))<=1001*EGGS_TO_HATCH_1SHRIMP);//you may now trade for a max of 1000 eggs
vrfcontract.transferFrom(from,this,tokens);
claimedEggs[from]=claimedEggs[from].add(tokens.div(VRF_EGG_COST));
}
//allow sending eth to the contract
function () public payable {}
function claimFreeEggs() public{
// RE ENABLE THIS BEFORE DEPLOYING MAINNET
require(ethVerify.verifiedUsers(msg.sender));
require(initialized);
require(!hasClaimedFree[msg.sender]);
claimedEggs[msg.sender]=claimedEggs[msg.sender].add(getFreeEggs());
_hatchEggs(0);
hatchCooldown[msg.sender]=0;
hasClaimedFree[msg.sender]=true;
//require(hatcheryShrimp[msg.sender]==0);
//lastHatch[msg.sender]=now;
//hatcheryShrimp[msg.sender]=hatcheryShrimp[msg.sender].add(STARTING_SHRIMP);
}
function getFreeEggs() public view returns(uint){
return min(calculateEggBuySimple(this.balance.div(400)),calculateEggBuySimple(0.01 ether));
}
function getBalance() public view returns(uint256){
return this.balance;
}
function getMyShrimp() public view returns(uint256){
return hatcheryShrimp[msg.sender];
}
function getMyEggs() public view returns(uint256){
return SafeMath.add(claimedEggs[msg.sender],getEggsSinceLastHatch(msg.sender));
}
function getEggsSinceLastHatch(address adr) public view returns(uint256){
uint256 secondsPassed=min(EGGS_TO_HATCH_1SHRIMP,SafeMath.sub(now,lastHatch[adr]));
return SafeMath.mul(secondsPassed,hatcheryShrimp[adr]);
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
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;
}
} | RE ENABLE THIS BEFORE DEPLOYING MAINNETrequire(hatcheryShrimp[msg.sender]==0);lastHatch[msg.sender]=now;hatcheryShrimp[msg.sender]=hatcheryShrimp[msg.sender].add(STARTING_SHRIMP); | function claimFreeEggs() public{
require(ethVerify.verifiedUsers(msg.sender));
require(initialized);
require(!hasClaimedFree[msg.sender]);
claimedEggs[msg.sender]=claimedEggs[msg.sender].add(getFreeEggs());
_hatchEggs(0);
hatchCooldown[msg.sender]=0;
hasClaimedFree[msg.sender]=true;
}
| 1,755,102 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./DelicateDinosBaseIntegration.t.sol";
contract DelicateDinosIntegrationTest is DelicateDinosBaseIntegrationTest {
function setUp() external {
init();
}
// ============ WHITELISTED MINT ============= //
function testCanMintWhitelisted() external {
delicateDinosMinter.startWhitelistMint(MERKLE_ROOT, DEFAULT_MINT_FEE, 1);
assertTrue(delicateDinos.supply() == 0);
delicateDinosMinter.mintDinoWhitelisted{value: DEFAULT_MINT_FEE}(address(this), oneName, merkleProof, 1);
assertTrue(delicateDinos.supply() == 1);
bytes32 requestId = delicateDinos.getTokenIdToMintRequestId(1);
_vrfRespondMint(RANDOM_NUMBER, requestId);
assertTrue(delicateDinos.ownerOf(1) == address(this));
// emit log_string(delicateDinos.tokenURI(1));
}
function testCanMintMultipleAtOnceWhitelisted() external {
delicateDinosMinter.startWhitelistMint(MERKLE_ROOT, DEFAULT_MINT_FEE, 2);
assertTrue(delicateDinos.supply() == 0);
delicateDinosMinter.mintDinoWhitelisted{value: DEFAULT_MINT_FEE}(address(this), twoNames, merkleProof, 2);
assertTrue(delicateDinos.supply() == 2);
bytes32 requestId = delicateDinos.getTokenIdToMintRequestId(1);
_vrfRespondMint(RANDOM_NUMBER, requestId);
assertTrue(delicateDinos.ownerOf(1) == address(this));
assertTrue(delicateDinos.ownerOf(2) == address(this));
assertTrue(delicateDinos.supply() == 2);
}
/// @notice Whitelisted account can receive multiple minted tokens, but all must be minted at once
function testCannotMintTwiceWhitelisted() external {
delicateDinosMinter.startWhitelistMint(MERKLE_ROOT, DEFAULT_MINT_FEE, 2); // we allow for max 2, but only mint 1
delicateDinosMinter.mintDinoWhitelisted{value: DEFAULT_MINT_FEE}(address(this), oneName, merkleProof, 1);
bytes32 requestId = delicateDinos.getTokenIdToMintRequestId(1);
_vrfRespondMint(RANDOM_NUMBER, requestId);
assertTrue(delicateDinosMinter.hasClaimed(address(this)));
HEVM.expectRevert(abi.encodeWithSelector(WhitelistManager.AlreadyClaimed.selector));
delicateDinosMinter.mintDinoWhitelisted{value: DEFAULT_MINT_FEE}(address(this), oneName2, merkleProof, 1);
}
// ================ MINT PUBLIC SALE ================= //
// TODO can mint public sale
// TODO can mint repeatedly during public sale
// TODO cannot mint more than maxLimit at once
// TODO Cannot mint more than maxLimit overall
// TODO cannot mint with wrong fee
// ================ MINT DROP ================= //
// TODO drop lottery - only while no whitelist or public sale is happening
// TODO drop lottery - new tokens are indeed minted
// TODO drop lottery - fuzz - higher chances for favoured tokenIds
// =============== ARTWORK & STATS ================ //
// TODO random token stats in correct range (0..255)
// TODO name is set correctly
// TODO tokenURI displays correctly if no name is set
// TODO placeholder artwork (tokenURI with placeholder)
// TODO artwork can be updated (baseuri changes, tokenURI correct)
// =============== UPGRADER =================== //
// TODO can upgrade features
// TODO upgrade fails when insufficient DNOUP paid
// TODO upgrade fails when not the owner of the token
// =============== RENAMING ================== //
// TODO can rename
// TODO can only rename once
// TODO cannot rename if locked
} | Whitelisted account can receive multiple minted tokens, but all must be minted at once | function testCannotMintTwiceWhitelisted() external {
bytes32 requestId = delicateDinos.getTokenIdToMintRequestId(1);
_vrfRespondMint(RANDOM_NUMBER, requestId);
assertTrue(delicateDinosMinter.hasClaimed(address(this)));
HEVM.expectRevert(abi.encodeWithSelector(WhitelistManager.AlreadyClaimed.selector));
}
| 6,413,760 |
./partial_match/1/0xCb4cCC716ABE1b5be15870E2bfa12BF5F0b501e6/sources/Verifier.sol | return the product of a point on G1 and a scalar, i.e. p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p. Use "invalid" to make gas estimation work | function scalar_mul(G1Point p, uint s) internal returns (G1Point r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := call(sub(gas, 2000), 7, 0, input, 0x80, r, 0x60)
}
require (success);
}
| 4,401,868 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../libraries/tokens/ERC20/ERC20.sol";
contract MockERC20 is ERC20 {
uint256 public totalSupply;
constructor(
string memory _name,
string memory _symbol,
uint256 _initialAmount
) public ERC20(_name, _symbol) {
// Give the creator all initial tokens
balanceOf[msg.sender] = _initialAmount;
// Update total supply
totalSupply = _initialAmount;
}
function mint(address account, uint256 amount) external {
require(account != address(0), "MockERC20::mint: mint to the zero address");
totalSupply += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../../Domain.sol";
import "../../../interfaces/token/ERC20/IDetailedERC20.sol";
import "hardhat/console.sol";
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// Data part taken out for building of contracts that receive delegate calls
contract ERC20Data {
/// @notice owner > balance mapping.
mapping(address => uint256) public balanceOf;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
string public name;
string public symbol;
uint256 public decimals;
}
contract ERC20 is ERC20Data, Domain {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut 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(string memory name_, string memory symbol_) public {
name = name_;
symbol = symbol_;
decimals = 18;
}
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) public returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "ERC20::transfer: balance too low");
if (msg.sender != to) {
require(to != address(0), "ERC20::transfer: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20::transferFrom: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "ERC20::transferFrom: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "ERC20::transferFrom: no zero address"); // Moved down so other failed calls safe some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20::permit: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(
_getDigest(
keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))
),
v,
r,
s
) == owner_,
"ERC20::permit: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
// SPDX-License-Identifier: MIT
// Based on code and smartness by Ross Campbell and Keno
// Uses immutable to store the domain separator to reduce gas usage
// If the chain id changes due to a fork, the forked chain will calculate on the fly.
pragma solidity 0.6.12;
// solhint-disable no-inline-assembly
contract Domain {
bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH =
keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01";
// solhint-disable var-name-mixedcase
bytes32 private immutable _DOMAIN_SEPARATOR;
uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;
/// @dev Calculate the DOMAIN_SEPARATOR
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this)));
}
constructor() public {
uint256 chainId;
assembly {
chainId := chainid()
}
_DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId);
}
/// @dev Return the DOMAIN_SEPARATOR
// It's named internal to allow making it public from the contract that uses it by creating a simple view function
// with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator.
// solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId);
}
function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) {
digest = keccak256(abi.encodePacked(EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 is IERC20 {
function name() external returns (string memory);
function symbol() external returns (string memory);
function decimals() external returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// 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);
}
| Return the DOMAIN_SEPARATOR It's named internal to allow making it public from the contract that uses it by creating a simple view function with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. solhint-disable-next-line func-name-mixedcase | function _domainSeparator() internal view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId);
}
| 13,681,544 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.6.12;
//
// _βββββββββ
// βββββββββββ
// βββββ__βββββ___ββββββ
// βββββ____ββββββ__βββββ
// βββββ___βββββ_____βββββ
// βββββ_______________βββββ
// _βββββ______________βββββ
// __βββββ____________βββββ
// ___βββββ__________βββββ
// ____βββββ________βββββ
// _____βββββ_____βββββ
//γγββββββββββββββββββββββ_βββββ__βββββ
//γγββββββββββββββββββββββ__βββββββββ
//γγββββββββββββββββββββββ____βββββ
//γγββββββββββββββββββββββ__βββββ
//γγβββββββββββββββββββββββββββ
//γ ββββββββββββββββββββββββ
//γ ββββββββββββββββββββββββ
//γ ββββββββββββββββββββββββ
//γγββββββββββββββββββββββ
//γγββββββββββββββββββββββ
//γγββββββββββββ΄ββββββββββ
//γγββββββββββββββββββββββ
//γγββββββββββββββββββββββ
//γγββββββββββββββββββββββ
//γγββββββββββββ₯ββββββββββ
//γγββββββββββββββββββββββ
//γγβββββββββ΄β΄ββ§β§ββ§β§ββ΄β΄βββ
//γγββββββββββββββββββββββ
//
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// ERC721
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// ERC20
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// For safe maths operations
import "@openzeppelin/contracts/math/SafeMath.sol";
// Utils only
import "./StringsUtil.sol";
interface IERC20Burnable {
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function burnAmount() external view returns (uint256 _amount);
}
/**
* @title NotRealDigitalAsset - V2
*
* http://www.notreal.ai/
*
* ERC721 compliant digital assets for real-world artwork.
*
* Base NFT Issuance Contract
*
* AMPLIFY ART.
*
*/
contract NotRealDigitalAssetV2 is
AccessControl,
Ownable,
ERC721,
Pausable,
ReentrancyGuard
{
bytes32 public constant ROLE_NOT_REAL = keccak256('ROLE_NOT_REAL');
bytes32 public constant ROLE_MINTER = keccak256('ROLE_MINTER');
bytes32 public constant ROLE_MARKET = keccak256('ROLE_MARKET');
///////////////
// Modifiers //
///////////////
// Modifiers are wrapped around functions because it shaves off contract size
modifier onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) {
_onlyAvailableEdition(_editionNumber, _numTokens);
_;
}
modifier onlyActiveEdition(uint256 _editionNumber) {
_onlyActiveEdition(_editionNumber);
_;
}
modifier onlyRealEdition(uint256 _editionNumber) {
_onlyRealEdition(_editionNumber);
_;
}
modifier onlyValidTokenId(uint256 _tokenId) {
_onlyValidTokenId(_tokenId);
_;
}
modifier onlyPurchaseDuringWindow(uint256 _editionNumber) {
_onlyPurchaseDuringWindow(_editionNumber);
_;
}
function _onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) internal view {
require(editionNumberToEditionDetails[_editionNumber].totalSupply.add(_numTokens) <= editionNumberToEditionDetails[_editionNumber].totalAvailable);
}
function _onlyActiveEdition(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].active);
}
function _onlyRealEdition(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].editionNumber > 0);
}
function _onlyValidTokenId(uint256 _tokenId) internal view {
require(_exists(_tokenId));
}
function _onlyPurchaseDuringWindow(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].startDate <= block.timestamp);
require(editionNumberToEditionDetails[_editionNumber].endDate >= block.timestamp);
}
modifier onlyIfNotReal() {
_onlyIfNotReal();
_;
}
modifier onlyIfMinter() {
_onlyIfMinter();
_;
}
function _onlyIfNotReal() internal view {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()));
}
function _onlyIfMinter() internal view {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MINTER, _msgSender()));
}
using SafeMath for uint256;
using SafeERC20 for IERC20;
////////////
// Events //
////////////
// Emitted on purchases from within this contract
event Purchase(
uint256 indexed _tokenId,
uint256 indexed _editionNumber,
address indexed _buyer,
uint256 _priceInWei,
uint256 _numTokens
);
// Emitted on every mint
event Minted(
uint256 indexed _tokenId,
uint256 indexed _editionNumber,
address indexed _buyer,
uint256 _numTokens
);
// Emitted on every edition created
event EditionCreated(
uint256 indexed _editionNumber,
bytes32 indexed _editionData,
uint256 indexed _editionType
);
event NameChange(uint256 indexed _tokenId, string _newName);
////////////////
// Properties //
////////////////
uint256 constant internal MAX_UINT32 = ~uint32(0);
string public tokenBaseURI = "https://ipfs.infura.io/ipfs/";
// simple counter to keep track of the highest edition number used
uint256 public highestEditionNumber;
// number of assets minted of any type
uint256 public totalNumberMinted;
// number of assets minted of any type
uint256 public totalPurchaseValueInWei;
// number of assets available of any type
uint256 public totalNumberAvailable;
// Max number of tokens that can be minted/purchased in a batch
uint256 public maxBatch = 100;
uint256 public maxGas = 100000000000;
// the NR account which can receive commission
address public nrCommissionAccount;
// Accepted ERC20 token
IERC20 public acceptedToken;
IERC20Burnable public nameToken;
// Optional commission split can be defined per edition
mapping(uint256 => CommissionSplit) internal editionNumberToOptionalCommissionSplit;
// Simple structure providing an optional commission split per edition purchase
struct CommissionSplit {
uint256 rate;
address recipient;
}
// Object for edition details
struct EditionDetails {
// Identifiers
uint256 editionNumber; // the range e.g. 10000
bytes32 editionData; // some data about the edition
uint256 editionType; // e.g. 1 = NRDA, 4 = Deactivated
// Config
uint256 startDate; // date when the edition goes on sale
uint256 endDate; // date when the edition is available until
address artistAccount; // artists account
uint256 artistCommission; // base artists commission, could be overridden by external contracts
uint256 priceInWei; // base price for edition, could be overridden by external contracts
string tokenURI; // IPFS hash - see base URI
bool active; // Root control - on/off for the edition
// Counters
uint256 totalSupply; // Total purchases or mints
uint256 totalAvailable; // Total number available to be purchased
}
// _editionNumber : EditionDetails
mapping(uint256 => EditionDetails) internal editionNumberToEditionDetails;
// _tokenId : _editionNumber
mapping(uint256 => uint256) internal tokenIdToEditionNumber;
// _editionNumber : [_tokenId, _tokenId]
mapping(uint256 => uint256[]) internal editionNumberToTokenIds;
mapping(uint256 => uint256[]) internal editionNumberToBurnedTokenIds;
// _artistAccount : [_editionNumber, _editionNumber]
mapping(address => uint256[]) internal artistToEditionNumbers;
mapping(uint256 => uint256) internal editionNumberToArtistIndex;
// _editionType : [_editionNumber, _editionNumber]
mapping(uint256 => uint256[]) internal editionTypeToEditionNumber;
mapping(uint256 => uint256) internal editionNumberToTypeIndex;
mapping (uint256 => string) public tokenName;
mapping (string => bool) internal reservedName;
/*
* Constructor
*/
constructor (IERC20 _acceptedToken) public payable ERC721("NotRealDigitalAsset", "NRDA") {
// set commission account to contract creator
nrCommissionAccount = _msgSender();
acceptedToken = _acceptedToken;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setBaseURI(tokenBaseURI);
}
// Function wrapper for using native Ether or ERC20
function _acceptedTokenSafeTransferFrom(address _from, address _to, uint256 _msgValue) internal {
require(tx.gasprice <= maxGas, "Gas price too high");
if(address(acceptedToken) == address(0)) {
require(msg.value == _msgValue);
require(_from == _msgSender());
require(_to == address(this));
} else {
acceptedToken.safeTransferFrom(_from, _to, _msgValue);
}
}
function _acceptedTokenSafeTransfer(address _to, uint256 _msgValue) internal {
if(address(acceptedToken) == address(0)) {
payable(_to).transfer(_msgValue);
} else {
acceptedToken.safeTransfer(_to, _msgValue);
}
}
function pause() public onlyIfNotReal {
_pause();
}
function unpause() public onlyIfNotReal {
_unpause();
}
function setNameToken(address _nameToken) external onlyOwner {
nameToken = IERC20Burnable(_nameToken);
}
// Spend name tokens to give this ERC721 a unique name
function changeName(uint256 _tokenId, string memory _newName) public onlyValidTokenId(_tokenId) {
string memory _newNameLower = StringsUtil.toLower(_newName);
require(_msgSender() == ownerOf(_tokenId), "ERC721: caller is not the owner");
require(StringsUtil.validateName(_newName), "Not a valid new name");
require(!reservedName[_newNameLower], "Name already reserved");
reservedName[StringsUtil.toLower(tokenName[_tokenId])] = false;
reservedName[_newNameLower] = true;
nameToken.burnFrom(_msgSender(), nameToken.burnAmount());
tokenName[_tokenId] = _newName;
emit NameChange(_tokenId, _newName);
}
function mint(address _to, uint256 _editionNumber)
public
onlyIfMinter
returns (uint256) {
return mintMany(_to, _editionNumber, 1);
}
/**
* @dev Private (NR only) method for minting editions
* @dev Payment not needed for this method
*/
function mintMany(address _to, uint256 _editionNumber, uint256 _numTokens)
public
onlyIfMinter
onlyRealEdition(_editionNumber)
onlyAvailableEdition(_editionNumber, _numTokens)
returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1);
for (uint256 i = 0; i < _numTokens; i++) {
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
// Create the token
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
}
totalNumberMinted = totalNumberMinted.add(_numTokens);
_editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens);
// Emit minted event
emit Minted(_tokenId, _editionNumber, _to, _numTokens);
return _tokenId;
}
/**
* @dev Internal factory method for building editions
*/
function createEdition(
uint256 _editionNumber,
bytes32 _editionData,
uint256 _editionType,
uint256 _startDate,
uint256 _endDate,
address _artistAccount,
uint256 _artistCommission,
uint256 _priceInWei,
string memory _tokenURI,
uint256 _totalAvailable,
bool _active
)
public
onlyIfNotReal
returns (bool)
{
// Prevent missing edition number
require(_editionNumber != 0);
// Prevent edition number lower than last one used
require(_editionNumber > highestEditionNumber);
// Check previously edition plus total available is less than new edition number
require(highestEditionNumber.add(editionNumberToEditionDetails[highestEditionNumber].totalAvailable) < _editionNumber);
// Prevent missing types
require(_editionType != 0);
// Prevent missing token URI
require(bytes(_tokenURI).length != 0);
// Prevent empty artists address
require(_artistAccount != address(0));
// Prevent invalid commissions
require(_artistCommission <= 100 && _artistCommission >= 0);
// Prevent duplicate editions
require(editionNumberToEditionDetails[_editionNumber].editionNumber == 0);
// Default end date to max uint256
uint256 endDate = _endDate;
if (_endDate == 0) {
endDate = MAX_UINT32;
}
editionNumberToEditionDetails[_editionNumber] = EditionDetails({
editionNumber : _editionNumber,
editionData : _editionData,
editionType : _editionType,
startDate : _startDate,
endDate : endDate,
artistAccount : _artistAccount,
artistCommission : _artistCommission,
priceInWei : _priceInWei,
tokenURI : StringsUtil.strConcat(_tokenURI, "/"),
totalSupply : 0, // default to all available
totalAvailable : _totalAvailable,
active : _active
});
// Add to total available count
totalNumberAvailable = totalNumberAvailable.add(_totalAvailable);
// Update mappings
_updateArtistLookupData(_artistAccount, _editionNumber);
_updateEditionTypeLookupData(_editionType, _editionNumber);
emit EditionCreated(_editionNumber, _editionData, _editionType);
// Update the edition pointer if needs be
highestEditionNumber = _editionNumber;
return true;
}
function _updateEditionTypeLookupData(uint256 _editionType, uint256 _editionNumber) internal {
uint256 typeEditionIndex = editionTypeToEditionNumber[_editionType].length;
editionTypeToEditionNumber[_editionType].push(_editionNumber);
editionNumberToTypeIndex[_editionNumber] = typeEditionIndex;
}
function _updateArtistLookupData(address _artistAccount, uint256 _editionNumber) internal {
uint256 artistEditionIndex = artistToEditionNumbers[_artistAccount].length;
artistToEditionNumbers[_artistAccount].push(_editionNumber);
editionNumberToArtistIndex[_editionNumber] = artistEditionIndex;
}
///**
// * @dev Public entry point for purchasing an edition on behalf of someone else
// * @dev Reverts if edition is invalid
// * @dev Reverts if payment not provided in full
// * @dev Reverts if edition is sold out
// * @dev Reverts if edition is not active or available
// */
function purchaseMany(address _to, uint256 _editionNumber, uint256 _numTokens, uint256 _msgValue)
public
payable
whenNotPaused
nonReentrant
onlyRealEdition(_editionNumber)
onlyActiveEdition(_editionNumber)
onlyAvailableEdition(_editionNumber, _numTokens)
onlyPurchaseDuringWindow(_editionNumber)
returns (uint256) {
require(_numTokens <= maxBatch && _numTokens >= 1);
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
require(_msgValue >= _editionDetails.priceInWei.mul(_numTokens));
_acceptedTokenSafeTransferFrom(_msgSender(), address(this), _msgValue);
uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1);
for (uint256 i = 0; i < _numTokens; i++) {
// Transfer token to this contract
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
// Create the token
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
}
totalNumberMinted = totalNumberMinted.add(_numTokens);
_editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens);
// Splice funds and handle commissions
_handleFunds(_editionNumber, _msgValue, _editionDetails.artistAccount, _editionDetails.artistCommission);
// Emit minted event
emit Minted(_tokenId, _editionNumber, _to, _numTokens);
// Broadcast purchase
emit Purchase(_tokenId, _editionNumber, _to, _editionDetails.priceInWei, _numTokens);
return _tokenId;
}
function _nextTokenId(uint256 _editionNumber) internal returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
// Bump number totalSupply
_editionDetails.totalSupply = _editionDetails.totalSupply.add(1);
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
return _editionDetails.editionNumber.add(_editionDetails.totalSupply);
}
function _mintToken(address _to, uint256 _tokenId, uint256 _editionNumber, string memory _tokenURI) internal {
// Mint new base token
super._mint(_to, _tokenId);
super._setTokenURI(_tokenId, StringsUtil.strConcat(_tokenURI, StringsUtil.uint2str(_tokenId)));
// Maintain mapping for tokenId to edition for lookup
tokenIdToEditionNumber[_tokenId] = _editionNumber;
// Maintain mapping of edition to token array for "edition minted tokens"
editionNumberToTokenIds[_editionNumber].push(_tokenId);
}
function _handleFunds(uint256 _editionNumber, uint256 _priceInWei, address _artistAccount, uint256 _artistCommission) internal {
// Extract the artists commission and send it
uint256 artistPayment = _priceInWei.div(100).mul(_artistCommission);
if (artistPayment > 0) {
_acceptedTokenSafeTransfer(_artistAccount, artistPayment);
}
// Load any commission overrides
CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber];
// Apply optional commission structure
uint256 rateSplit = 0;
if (commission.rate > 0) {
rateSplit = _priceInWei.div(100).mul(commission.rate);
_acceptedTokenSafeTransfer(commission.recipient, rateSplit);
}
// Send remaining eth to NR
uint256 remainingCommission = _priceInWei.sub(artistPayment).sub(rateSplit);
_acceptedTokenSafeTransfer(nrCommissionAccount, remainingCommission);
// Record wei sale value
totalPurchaseValueInWei = totalPurchaseValueInWei.add(_priceInWei);
}
/**
* @dev Private (NR only) method for burning tokens which have been created incorrectly
*/
function burn(uint256 _tokenId) external onlyIfNotReal {
// Clear from parents
super._burn(_tokenId);
// Get hold of the edition for cleanup
uint256 _editionNumber = tokenIdToEditionNumber[_tokenId];
// Delete token ID mapping
delete tokenIdToEditionNumber[_tokenId];
editionNumberToBurnedTokenIds[_editionNumber].push(_tokenId);
}
//////////////////
// Base Updates //
//////////////////
//
function updateTokenBaseURI(string calldata _newBaseURI)
external
onlyIfNotReal {
require(bytes(_newBaseURI).length != 0);
tokenBaseURI = _newBaseURI;
}
function updateNrCommissionAccount(address _nrCommissionAccount)
external
onlyIfNotReal {
require(_nrCommissionAccount != address(0));
nrCommissionAccount = _nrCommissionAccount;
}
function updateMaxBatch(uint256 _maxBatch)
external
onlyIfNotReal {
maxBatch = _maxBatch;
}
function updateMaxGas(uint256 _maxGas)
external
onlyIfNotReal {
maxGas = _maxGas;
}
/////////////////////
// Edition Updates //
/////////////////////
function updateEditionTokenURI(uint256 _editionNumber, string calldata _uri)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].tokenURI = StringsUtil.strConcat(_uri, "/");
}
function updatePriceInWei(uint256 _editionNumber, uint256 _priceInWei)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].priceInWei = _priceInWei;
}
function updateArtistCommission(uint256 _editionNumber, uint256 _rate)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].artistCommission = _rate;
}
function updateEditionType(uint256 _editionNumber, uint256 _editionType)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber];
// Get list of editions for old type
uint256[] storage editionNumbersForType = editionTypeToEditionNumber[_originalEditionDetails.editionType];
// Remove edition from old type list
uint256 editionTypeIndex = editionNumberToTypeIndex[_editionNumber];
delete editionNumbersForType[editionTypeIndex];
// Add new type to the list
uint256 newTypeEditionIndex = editionTypeToEditionNumber[_editionType].length;
editionTypeToEditionNumber[_editionType].push(_editionNumber);
editionNumberToTypeIndex[_editionNumber] = newTypeEditionIndex;
// Update the edition
_originalEditionDetails.editionType = _editionType;
}
function updateTotalSupply(uint256 _editionNumber, uint256 _totalSupply)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
require(editionNumberToTokenIds[_editionNumber].length <= _totalSupply);
editionNumberToEditionDetails[_editionNumber].totalSupply = _totalSupply;
}
function updateTotalAvailable(uint256 _editionNumber, uint256 _totalAvailable)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
require(_editionDetails.totalSupply <= _totalAvailable);
uint256 originalAvailability = _editionDetails.totalAvailable;
_editionDetails.totalAvailable = _totalAvailable;
totalNumberAvailable = totalNumberAvailable.sub(originalAvailability).add(_totalAvailable);
}
function updateActive(uint256 _editionNumber, bool _active)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].active = _active;
}
function updateStartDate(uint256 _editionNumber, uint256 _startDate)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].startDate = _startDate;
}
function updateEndDate(uint256 _editionNumber, uint256 _endDate)
external
onlyRealEdition(_editionNumber) {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MARKET, _msgSender()));
editionNumberToEditionDetails[_editionNumber].endDate = _endDate;
}
function updateArtistsAccount(uint256 _editionNumber, address _artistAccount)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 editionArtistIndex = editionNumberToArtistIndex[_editionNumber];
// Get list of editions old artist works with
uint256[] storage editionNumbersForArtist = artistToEditionNumbers[_originalEditionDetails.artistAccount];
// Remove edition from artists lists
delete editionNumbersForArtist[editionArtistIndex];
// Add new artists to the list
uint256 newArtistsEditionIndex = artistToEditionNumbers[_artistAccount].length;
artistToEditionNumbers[_artistAccount].push(_editionNumber);
editionNumberToArtistIndex[_editionNumber] = newArtistsEditionIndex;
// Update the edition
_originalEditionDetails.artistAccount = _artistAccount;
}
function updateOptionalCommission(uint256 _editionNumber, uint256 _rate, address _recipient)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 artistCommission = _editionDetails.artistCommission;
if (_rate > 0) {
require(_recipient != address(0));
}
require(artistCommission.add(_rate) <= 100);
editionNumberToOptionalCommissionSplit[_editionNumber] = CommissionSplit({rate : _rate, recipient : _recipient});
}
///////////////////
// Token Updates //
///////////////////
function setTokenURI(uint256 _tokenId, string calldata _uri)
external
onlyIfNotReal
onlyValidTokenId(_tokenId) {
_setTokenURI(_tokenId, _uri);
}
///////////////////
// Query Methods //
///////////////////
/**
* @dev Lookup the edition of the provided token ID
* @dev Returns 0 if not valid
*/
function editionOfTokenId(uint256 _tokenId) external view returns (uint256 _editionNumber) {
return tokenIdToEditionNumber[_tokenId];
}
/**
* @dev Lookup all editions added for the given edition type
* @dev Returns array of edition numbers, any zero edition ids can be ignore/stripped
*/
function editionsOfType(uint256 _type) external view returns (uint256[] memory _editionNumbers) {
return editionTypeToEditionNumber[_type];
}
/**
* @dev Lookup all editions for the given artist account
* @dev Returns empty list if not valid
*/
function artistsEditions(address _artistsAccount) external view returns (uint256[] memory _editionNumbers) {
return artistToEditionNumbers[_artistsAccount];
}
/**
* @dev Lookup all tokens minted for the given edition number
* @dev Returns array of token IDs, any zero edition ids can be ignore/stripped
*/
function tokensOfEdition(uint256 _editionNumber) external view returns (uint256[] memory _tokenIds) {
return editionNumberToTokenIds[_editionNumber];
}
/**
* @dev Lookup all owned tokens for the provided address
* @dev Returns array of token IDs
*/
function tokensOf(address _owner) external view returns (uint256[] memory _tokenIds) {
uint256[] memory results = new uint256[](balanceOf(_owner));
for (uint256 idx = 0; idx < results.length; idx++) {
results[idx] = tokenOfOwnerByIndex(_owner, idx);
}
return results;
}
/**
* @dev Checks to see if the edition exists, assumes edition of zero is invalid
*/
function editionExists(uint256 _editionNumber) external view returns (bool) {
if (_editionNumber == 0) {
return false;
}
EditionDetails storage editionNumber = editionNumberToEditionDetails[_editionNumber];
return editionNumber.editionNumber == _editionNumber;
}
/**
* @dev Checks to see if the token exists
*/
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
/**
* @dev Lookup any optional commission split set for the edition
* @dev Both values will be zero if not present
*/
function editionOptionalCommission(uint256 _editionNumber) external view returns (uint256 _rate, address _recipient) {
CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber];
return (commission.rate, commission.recipient);
}
/**
* @dev Main entry point for looking up edition config/metadata
* @dev Reverts if invalid edition number provided
*/
function detailsOfEdition(uint256 editionNumber)
external view
onlyRealEdition(editionNumber)
returns (
bytes32 _editionData,
uint256 _editionType,
uint256 _startDate,
uint256 _endDate,
address _artistAccount,
uint256 _artistCommission,
uint256 _priceInWei,
string memory _tokenURI,
uint256 _totalSupply,
uint256 _totalAvailable,
bool _active
) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[editionNumber];
return (
_editionDetails.editionData,
_editionDetails.editionType,
_editionDetails.startDate,
_editionDetails.endDate,
_editionDetails.artistAccount,
_editionDetails.artistCommission,
_editionDetails.priceInWei,
StringsUtil.strConcat(tokenBaseURI, _editionDetails.tokenURI),
_editionDetails.totalSupply,
_editionDetails.totalAvailable,
_editionDetails.active
);
}
/**
* @dev Lookup a tokens common identifying characteristics
* @dev Reverts if invalid token ID provided
*/
function tokenData(uint256 _tokenId)
external view
onlyValidTokenId(_tokenId)
returns (
uint256 _editionNumber,
uint256 _editionType,
bytes32 _editionData,
string memory _tokenURI,
address _owner
) {
uint256 editionNumber = tokenIdToEditionNumber[_tokenId];
EditionDetails storage editionDetails = editionNumberToEditionDetails[editionNumber];
return (
editionNumber,
editionDetails.editionType,
editionDetails.editionData,
tokenURI(_tokenId),
ownerOf(_tokenId)
);
}
//////////////////////////
// Edition config query //
//////////////////////////
function purchaseDatesEdition(uint256 _editionNumber) public view returns (uint256 _startDate, uint256 _endDate) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return (
_editionDetails.startDate,
_editionDetails.endDate
);
}
function artistCommission(uint256 _editionNumber) external view returns (address _artistAccount, uint256 _artistCommission) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return (
_editionDetails.artistAccount,
_editionDetails.artistCommission
);
}
function priceInWeiEdition(uint256 _editionNumber) public view returns (uint256 _priceInWei) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.priceInWei;
}
function editionActive(uint256 _editionNumber) public view returns (bool) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.active;
}
function totalRemaining(uint256 _editionNumber) external view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalAvailable.sub(_editionDetails.totalSupply);
}
function totalAvailableEdition(uint256 _editionNumber) public view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalAvailable;
}
function totalSupplyEdition(uint256 _editionNumber) public view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalSupply;
}
function reclaimEther() external onlyOwner {
payable(owner()).transfer(address(this).balance);
if (address(acceptedToken) != address(0)) {
acceptedToken.transfer(owner(), acceptedToken.balanceOf(address(this)));
}
}
}
pragma solidity ^0.6.12;
library StringsUtil {
// via https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
function equal(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
// NOTE! If you don't make library functions internal, then you have to do annoying linking steps during migration
/**
* @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) internal pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1 ||
b.length > 25 || // Cannot be longer than 25 characters
b[0] == 0x20 || // Leading space
// Trailing space
b[b.length - 1] == 0x20) {
return false;
}
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
function toLower(string memory str) internal pure returns (string memory){
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
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(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @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());
}
}
}
// 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.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract 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 virtual 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;
}
}
// 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.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
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.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @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 ^ 0xe985e9c5 ^ 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 virtual 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 virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).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(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, 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 virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual 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 virtual 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 = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.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 = ERC721.ownerOf(tokenId); // internal owner
_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(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
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);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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.6.0 <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.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
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 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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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;
// 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];
}
// 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);
}
// 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))));
}
// 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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./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 () internal {
_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
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.6.0 <0.8.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--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
| Lookup all editions added for the given edition type Returns array of edition numbers, any zero edition ids can be ignore/stripped/ | function editionsOfType(uint256 _type) external view returns (uint256[] memory _editionNumbers) {
return editionTypeToEditionNumber[_type];
}
| 6,043,744 |
//Address: 0x320274f5dd332cc3b617b360e8554d95a0b96978
//Contract name: ZillaCrowdsale
//Balance: 0 Ether
//Verification Date: 11/30/2017
//Transacion Count: 3034
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
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;
}
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;
}
}
/**
* @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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
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 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) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev 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);
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;
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];
}
/**
* 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
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract ZillaToken is StandardToken, Ownable {
uint256 constant zilla = 1 ether;
string public name = 'Zilla Token';
string public symbol = 'ZLA';
uint public decimals = 18;
uint256 public initialSupply = 60000000 * zilla;
bool public tradeable;
function ZillaToken() public {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
tradeable = false;
}
/**
* @dev modifier to determine if the token is tradeable
*/
modifier isTradeable() {
require( tradeable == true );
_;
}
/**
* @dev allow the token to be freely tradeable
*/
function allowTrading() public onlyOwner {
require( tradeable == false );
tradeable = true;
}
/**
* @dev allow the token to be freely tradeable
* @param _to the address to transfer ZLA to
* @param _value the amount of ZLA to transfer
*/
function crowdsaleTransfer(address _to, uint256 _value) public onlyOwner returns (bool) {
require( tradeable == false );
return super.transfer(_to, _value);
}
function transfer(address _to, uint256 _value) public isTradeable returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public isTradeable returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public isTradeable returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public isTradeable returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public isTradeable returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @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 ZillaCrowdsale is Ownable {
using SafeMath for uint256;
// public events
event StartCrowdsale();
event FinalizeCrowdsale();
event TokenSold(address recipient, uint eth_amount, uint zla_amount);
// crowdsale constants
uint256 constant presale_eth_to_zilla = 1200;
uint256 constant crowdsale_eth_to_zilla = 750;
// our ZillaToken contract
ZillaToken public token;
// crowdsale token limit
uint256 public zilla_remaining;
// our Zilla multisig vault address
address public vault;
// crowdsale state
enum CrowdsaleState { Waiting, Running, Ended }
CrowdsaleState public state = CrowdsaleState.Waiting;
uint256 public start;
uint256 public unlimited;
uint256 public end;
// participants state
struct Participant {
bool whitelist;
uint256 remaining;
}
mapping (address => Participant) private participants;
/**
* @dev constructs ZillaCrowdsale
*/
function ZillaCrowdsale() public {
token = new ZillaToken();
zilla_remaining = token.totalSupply();
}
/**
* @dev modifier to determine if the crowdsale has been initialized
*/
modifier isStarted() {
require( (state == CrowdsaleState.Running) );
_;
}
/**
* @dev modifier to determine if the crowdsale is active
*/
modifier isRunning() {
require( (state == CrowdsaleState.Running) && (now >= start) && (now < end) );
_;
}
/**
* @dev start the Zilla Crowdsale
* @param _start is the epoch time the crowdsale starts
* @param _end is the epoch time the crowdsale ends
* @param _vault is the multisig wallet the ethereum is transfered to
*/
function startCrowdsale(uint256 _start, uint256 _unlimited, uint256 _end, address _vault) public onlyOwner {
require(state == CrowdsaleState.Waiting);
require(_start >= now);
require(_unlimited > _start);
require(_unlimited < _end);
require(_end > _start);
require(_vault != 0x0);
start = _start;
unlimited = _unlimited;
end = _end;
vault = _vault;
state = CrowdsaleState.Running;
StartCrowdsale();
}
/**
* @dev Finalize the Zilla Crowdsale, unsold tokens are moved to the vault account
*/
function finalizeCrowdsale() public onlyOwner {
require(state == CrowdsaleState.Running);
require(end < now);
// transfer remaining tokens to vault
_transferTokens( vault, 0, zilla_remaining );
// end the crowdsale
state = CrowdsaleState.Ended;
// allow the token to be traded
token.allowTrading();
FinalizeCrowdsale();
}
/**
* @dev Allow owner to increase the end date of the crowdsale as long as the crowdsale is still running
* @param _end the new end date for the crowdsale
*/
function setEndDate(uint256 _end) public onlyOwner {
require(state == CrowdsaleState.Running);
require(_end > now);
require(_end > start);
require(_end > end);
end = _end;
}
/**
* @dev Allow owner to change the multisig wallet
* @param _vault the new address of the multisig wallet
*/
function setVault(address _vault) public onlyOwner {
require(_vault != 0x0);
vault = _vault;
}
/**
* @dev Allow owner to add to the whitelist
* @param _addresses array of addresses to add to the whitelist
*/
function whitelistAdd(address[] _addresses) public onlyOwner {
for (uint i=0; i<_addresses.length; i++) {
Participant storage p = participants[ _addresses[i] ];
p.whitelist = true;
p.remaining = 15 ether;
}
}
/**
* @dev Allow owner to remove from the whitelist
* @param _addresses array of addresses to remove from the whitelist
*/
function whitelistRemove(address[] _addresses) public onlyOwner {
for (uint i=0; i<_addresses.length; i++) {
delete participants[ _addresses[i] ];
}
}
/**
* @dev Fallback function which buys tokens when sent ether
*/
function() external payable {
buyTokens(msg.sender);
}
/**
* @dev Apply our fixed buy rate and verify we are not sold out.
* @param eth the amount of ether being used to purchase tokens.
*/
function _allocateTokens(uint256 eth) private view returns(uint256 tokens) {
tokens = crowdsale_eth_to_zilla.mul(eth);
require( zilla_remaining >= tokens );
}
/**
* @dev Apply our fixed presale rate and verify we are not sold out.
* @param eth the amount of ether used to purchase presale tokens.
*/
function _allocatePresaleTokens(uint256 eth) private view returns(uint256 tokens) {
tokens = presale_eth_to_zilla.mul(eth);
require( zilla_remaining >= tokens );
}
/**
* @dev Transfer tokens to the recipient and update our token availability.
* @param recipient the recipient to receive tokens.
* @param eth the amount of Ethereum spent.
* @param zla the amount of Zilla Tokens received.
*/
function _transferTokens(address recipient, uint256 eth, uint256 zla) private {
require( token.crowdsaleTransfer( recipient, zla ) );
zilla_remaining = zilla_remaining.sub( zla );
TokenSold(recipient, eth, zla);
}
/**
* @dev Allows the owner to grant presale participants their tokens.
* @param recipient the recipient to receive tokens.
* @param eth the amount of ether from the presale.
*/
function _grantPresaleTokens(address recipient, uint256 eth) private {
uint256 tokens = _allocatePresaleTokens(eth);
_transferTokens( recipient, eth, tokens );
}
/**
* @dev Allows anyone to create tokens by depositing ether.
* @param recipient the recipient to receive tokens.
*/
function buyTokens(address recipient) public isRunning payable {
Participant storage p = participants[ recipient ];
require( p.whitelist );
// check for the first session buy limits
if( unlimited > now ) {
require( p.remaining >= msg.value );
p.remaining.sub( msg.value );
}
uint256 tokens = _allocateTokens(msg.value);
require( vault.send(msg.value) );
_transferTokens( recipient, msg.value, tokens );
}
/**
* @dev Allows owner to transfer tokens to any address.
* @param recipient is the address to receive tokens.
* @param zla is the amount of Zilla to transfer
*/
function grantTokens(address recipient, uint256 zla) public isStarted onlyOwner {
require( zilla_remaining >= zla );
_transferTokens( recipient, 0, zla );
}
/**
* @dev Allows the owner to grant presale participants their tokens.
* @param recipients array of recipients to receive tokens.
* @param eths array of ether from the presale.
*/
function grantPresaleTokens(address[] recipients, uint256[] eths) public isStarted onlyOwner {
require( recipients.length == eths.length );
for (uint i=0; i<recipients.length; i++) {
_grantPresaleTokens( recipients[i], eths[i] );
}
}
}
| Allow owner to change the multisig wallet _vault the new address of the multisig wallet/ | function setVault(address _vault) public onlyOwner {
require(_vault != 0x0);
vault = _vault;
}
| 6,456,222 |
pragma solidity 0.4.23;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* @notice Checks if 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) {
// a variable to load `extcodesize` to
uint256 size = 0;
// 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.
// solium-disable-next-line security/no-inline-assembly
assembly {
// retrieve the size of the code at address `addr`
size := extcodesize(addr)
}
// positive size indicates a smart contract address
return size > 0;
}
}
/**
* Library for working with strings, primarily converting
* between strings and integer types
*/
library StringUtils {
/**
* @dev Converts a string to unsigned integer using the specified `base`
* @dev Throws on invalid input
* (wrong characters for a given `base`)
* @dev Throws if given `base` is not supported
* @param a string to convert
* @param base number base, one of 2, 8, 10, 16
* @return a number representing given string
*/
function atoi(string a, uint8 base) internal pure returns (uint256 i) {
// check if the base is valid
require(base == 2 || base == 8 || base == 10 || base == 16);
// convert string into bytes for convenient iteration
bytes memory buf = bytes(a);
// iterate over the string (bytes buffer)
for(uint256 p = 0; p < buf.length; p++) {
// extract the digit
uint8 digit = uint8(buf[p]) - 0x30;
// if digit is greater then 10 β mind the gap
// see `itoa` function for more details
if(digit > 10) {
// remove the gap
digit -= 7;
}
// check if digit meets the base
require(digit < base);
// move to the next digit slot
i *= base;
// add digit to the result
i += digit;
}
// return the result
return i;
}
/**
* @dev Converts a integer to a string using the specified `base`
* @dev Throws if given `base` is not supported
* @param i integer to convert
* @param base number base, one of 2, 8, 10, 16
* @return a string representing given integer
*/
function itoa(uint256 i, uint8 base) internal pure returns (string a) {
// check if the base is valid
require(base == 2 || base == 8 || base == 10 || base == 16);
// for zero input the result is "0" string for any base
if (i == 0) {
return "0";
}
// bytes buffer to put ASCII characters into
bytes memory buf = new bytes(256);
// position within a buffer to be used in cycle
uint256 p = 0;
// extract digits one by one in a cycle
while (i > 0) {
// extract current digit
uint8 digit = uint8(i % base);
// convert it to an ASCII code
// 0x20 is " "
// 0x30-0x39 is "0"-"9"
// 0x41-0x5A is "A"-"Z"
// 0x61-0x7A is "a"-"z" ("A"-"Z" XOR " ")
uint8 ascii = digit + 0x30;
// if digit is greater then 10,
// fix the 0x3A-0x40 gap of punctuation marks
// (7 characters in ASCII table)
if(digit > 10) {
// jump through the gap
ascii += 7;
}
// write character into the buffer
buf[p++] = byte(ascii);
// move to the next digit
i /= base;
}
// `p` contains real length of the buffer now, save it
uint256 length = p;
// reverse the buffer
for(p = 0; p < length / 2; p++) {
// swap elements at position `p` from the beginning and end using XOR:
// https://en.wikipedia.org/wiki/XOR_swap_algorithm
buf[p] ^= buf[length - 1 - p];
buf[length - 1 - p] ^= buf[p];
buf[p] ^= buf[length - 1 - p];
}
// construct string and return
return string(buf);
}
/**
* @dev Concatenates two strings `s1` and `s2`, for example, if
* `s1` == `foo` and `s2` == `bar`, the result `s` == `foobar`
* @param s1 first string
* @param s2 second string
* @return concatenation result s1 + s2
*/
function concat(string s1, string s2) internal pure returns (string s) {
// convert s1 into buffer 1
bytes memory buf1 = bytes(s1);
// convert s2 into buffer 2
bytes memory buf2 = bytes(s2);
// create a buffer for concatenation result
bytes memory buf = new bytes(buf1.length + buf2.length);
// copy buffer 1 into buffer
for(uint256 i = 0; i < buf1.length; i++) {
buf[i] = buf1[i];
}
// copy buffer 2 into buffer
for(uint256 j = buf1.length; j < buf2.length; j++) {
buf[j] = buf2[j - buf1.length];
}
// construct string and return
return string(buf);
}
}
/**
* @dev Access control module provides an API to check
* if specific operation is permitted globally and
* if particular user's has a permission to execute it
*/
contract AccessControl {
/// @notice Role manager is responsible for assigning the roles
/// @dev Role ROLE_ROLE_MANAGER allows executing addOperator/removeOperator
uint256 private constant ROLE_ROLE_MANAGER = 0x10000000;
/// @notice Feature manager is responsible for enabling/disabling
/// global features of the smart contract
/// @dev Role ROLE_FEATURE_MANAGER allows enabling/disabling global features
uint256 private constant ROLE_FEATURE_MANAGER = 0x20000000;
/// @dev Bitmask representing all the possible permissions (super admin role)
uint256 private constant FULL_PRIVILEGES_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/// @dev A bitmask of globally enabled features
uint256 public features;
/// @notice Privileged addresses with defined roles/permissions
/// @notice In the context of ERC20/ERC721 tokens these can be permissions to
/// allow minting tokens, transferring on behalf and so on
/// @dev Maps an address to the permissions bitmask (role), where each bit
/// represents a permission
/// @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
/// represents all possible permissions
mapping(address => uint256) public userRoles;
/// @dev Fired in updateFeatures()
event FeaturesUpdated(address indexed _by, uint256 _requested, uint256 _actual);
/// @dev Fired in addOperator(), removeOperator(), addRole(), removeRole()
event RoleUpdated(address indexed _by, address indexed _to, uint256 _role);
/**
* @dev Creates an access controlled instance
*/
constructor() public {
// contract creator has full privileges
userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
}
/**
* @dev Updates set of the globally enabled features (`f`),
* taking into account sender's permissions.
* @dev Requires sender to have `ROLE_FEATURE_MANAGER` permission.
* @param mask bitmask representing a set of features to enable/disable
*/
function updateFeatures(uint256 mask) public {
// call sender nicely - caller
address caller = msg.sender;
// read caller's permissions
uint256 p = userRoles[caller];
// caller should have a permission to update global features
require(__hasRole(p, ROLE_FEATURE_MANAGER));
// taking into account caller's permissions,
// 1) enable features requested
features |= p & mask;
// 2) disable features requested
features &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ mask));
// fire an event
emit FeaturesUpdated(caller, mask, features);
}
/**
* @dev Adds a new `operator` - an address which has
* some extended privileges over the smart contract,
* for example token minting, transferring on behalf, etc.
* @dev Newly added `operator` cannot have any permissions which
* transaction sender doesn't have.
* @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.
* @dev Cannot update existing operator. Throws if `operator` already exists.
* @param operator address of the operator to add
* @param role bitmask representing a set of permissions which
* newly created operator will have
*/
function addOperator(address operator, uint256 role) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// read manager's permissions (role)
uint256 permissions = userRoles[manager];
// check that `operator` doesn't exist
require(userRoles[operator] == 0);
// manager must have a ROLE_ROLE_MANAGER role
require(__hasRole(permissions, ROLE_ROLE_MANAGER));
// recalculate permissions (role) to set:
// we cannot create an operator more powerful then calling `manager`
uint256 r = role & permissions;
// check if we still have some permissions (role) to set
require(r != 0);
// create an operator by persisting his permissions (roles) to storage
userRoles[operator] = r;
// fire an event
emit RoleUpdated(manager, operator, userRoles[operator]);
}
/**
* @dev Deletes an existing `operator`.
* @dev Requires sender to have `ROLE_ROLE_MANAGER` permission.
* @param operator address of the operator to delete
*/
function removeOperator(address operator) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// check if an `operator` exists
require(userRoles[operator] != 0);
// do not allow transaction sender to remove himself
// protects from an accidental removal of all the operators
require(operator != manager);
// manager must have a ROLE_ROLE_MANAGER role
// and he must have all the permissions operator has
require(__hasRole(userRoles[manager], ROLE_ROLE_MANAGER | userRoles[operator]));
// perform operator deletion
delete userRoles[operator];
// fire an event
emit RoleUpdated(manager, operator, 0);
}
/**
* @dev Updates an existing `operator`, adding a specified role to it.
* @dev Note that `operator` cannot receive permission which
* transaction sender doesn't have.
* @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.
* @dev Cannot create a new operator. Throws if `operator` doesn't exist.
* @dev Existing permissions of the `operator` are preserved
* @param operator address of the operator to update
* @param role bitmask representing a set of permissions which
* `operator` will have
*/
function addRole(address operator, uint256 role) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// read manager's permissions (role)
uint256 permissions = userRoles[manager];
// check that `operator` exists
require(userRoles[operator] != 0);
// manager must have a ROLE_ROLE_MANAGER role
require(__hasRole(permissions, ROLE_ROLE_MANAGER));
// recalculate permissions (role) to add:
// we cannot make an operator more powerful then calling `manager`
uint256 r = role & permissions;
// check if we still have some permissions (role) to add
require(r != 0);
// update operator's permissions (roles) in the storage
userRoles[operator] |= r;
// fire an event
emit RoleUpdated(manager, operator, userRoles[operator]);
}
/**
* @dev Updates an existing `operator`, removing a specified role from it.
* @dev Note that permissions which transaction sender doesn't have
* cannot be removed.
* @dev Requires transaction sender to have `ROLE_ROLE_MANAGER` permission.
* @dev Cannot remove all permissions. Throws on such an attempt.
* @param operator address of the operator to update
* @param role bitmask representing a set of permissions which
* will be removed from the `operator`
*/
function removeRole(address operator, uint256 role) public {
// call sender gracefully - `manager`
address manager = msg.sender;
// read manager's permissions (role)
uint256 permissions = userRoles[manager];
// check that we're not removing all the `operator`s permissions
// this is not really required and just causes inconveniences is function use
//require(userRoles[operator] ^ role != 0);
// manager must have a ROLE_ROLE_MANAGER role
require(__hasRole(permissions, ROLE_ROLE_MANAGER));
// recalculate permissions (role) to remove:
// we cannot revoke permissions which calling `manager` doesn't have
uint256 r = role & permissions;
// check if we still have some permissions (role) to revoke
require(r != 0);
// update operator's permissions (roles) in the storage
userRoles[operator] &= FULL_PRIVILEGES_MASK ^ r;
// fire an event
emit RoleUpdated(manager, operator, userRoles[operator]);
}
/// @dev Checks if requested feature is enabled globally on the contract
function __isFeatureEnabled(uint256 featureRequired) internal constant returns(bool) {
// delegate call to `__hasRole`
return __hasRole(features, featureRequired);
}
/// @dev Checks if transaction sender `msg.sender` has all the required permissions `roleRequired`
function __isSenderInRole(uint256 roleRequired) internal constant returns(bool) {
// read sender's permissions (role)
uint256 userRole = userRoles[msg.sender];
// delegate call to `__hasRole`
return __hasRole(userRole, roleRequired);
}
/// @dev Checks if user role `userRole` contain all the permissions required `roleRequired`
function __hasRole(uint256 userRole, uint256 roleRequired) internal pure returns(bool) {
// check the bitmask for the role required and return the result
return userRole & roleRequired == roleRequired;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safe transfers
* from ERC721 asset contracts.
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
interface ERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient after a `transfer`.
* This function MAY throw to revert and reject the transfer.
* Return of other than the magic value MUST result in the transaction being reverted.
* @notice The contract address is always the message sender.
* A wallet/broker/auction application MUST implement the wallet interface
* if it will accept safe transfers.
* @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)"))` unless throwing
*/
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
contract ERC165 {
/**
* 0x01ffc9a7 == bytes4(keccak256('supportsInterface(bytes4)'))
*/
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* @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 {
// register itself in a lookup table
_registerInterface(InterfaceId_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.
* @dev This function uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) public constant returns (bool) {
// find if interface is supported using a lookup table
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
/**
* @notice Gem is unique tradable entity. Non-fungible.
* @dev A gem is an ERC721 non-fungible token, which maps Token ID,
* a 32 bit number to a set of gem properties -
* attributes (mostly immutable by their nature) and state variables (mutable)
* @dev A gem token supports only minting, it can be only created
*/
contract GemERC721 is AccessControl, ERC165 {
/// @dev Smart contract version
/// @dev Should be incremented manually in this source code
/// each time smart contact source code is changed
uint32 public constant TOKEN_VERSION = 0x3;
/// @dev ERC20 compliant token symbol
string public constant symbol = "GEM";
/// @dev ERC20 compliant token name
string public constant name = "GEM β CryptoMiner World";
/// @dev ERC20 compliant token decimals
/// @dev this can be only zero, since ERC721 token is non-fungible
uint8 public constant decimals = 0;
/// @dev A gem data structure
/// @dev Occupies 64 bytes of storage (512 bits)
struct Gem {
/// High 256 bits
/// @dev Where gem was found: land plot ID,
/// land block within a plot,
/// gem number (id) within a block of land, immutable
uint64 coordinates;
/// @dev Gem color, one of 12 values, immutable
uint8 color;
/// @dev Level modified time
/// @dev Stored as Ethereum Block Number of the transaction
/// when the gem was created
uint32 levelModified;
/// @dev Level value (mutable), one of 1, 2, 3, 4, 5
uint8 level;
/// @dev Grade modified time
/// @dev Stored as Ethereum Block Number of the transaction
/// when the gem was created
uint32 gradeModified;
/// @dev High 8 bits store grade type and low 24 bits grade value
/// @dev Grade type is one of D (1), C (2), B (3), A (4), AA (5) and AAA (6)
uint32 grade;
/// @dev Store state modified time
/// @dev Stored as Ethereum Block Number of the transaction
/// when the gem was created
uint32 stateModified;
/// @dev State value, mutable
uint48 state;
/// Low 256 bits
/// @dev Gem creation time, immutable, cannot be zero
/// @dev Stored as Ethereum Block Number of the transaction
/// when the gem was created
uint32 creationTime;
/// @dev Gem index within an owner's collection of gems, mutable
uint32 index;
/// @dev Initially zero, changes when ownership is transferred
/// @dev Stored as Ethereum Block Number of the transaction
/// when the gem's ownership was changed, mutable
uint32 ownershipModified;
/// @dev Gem's owner, initialized upon gem creation, mutable
address owner;
}
/// @notice All the emitted gems
/// @dev Core of the Gem as ERC721 token
/// @dev Maps Gem ID => Gem Data Structure
mapping(uint256 => Gem) public gems;
/// @dev Mapping from a gem ID to an address approved to
/// transfer ownership rights for this gem
mapping(uint256 => address) public approvals;
/// @dev Mapping from owner to operator approvals
/// token owner => approved token operator => is approved
mapping(address => mapping(address => bool)) public approvedOperators;
/// @notice Storage for a collections of tokens
/// @notice A collection of tokens is an ordered list of token IDs,
/// owned by a particular address (owner)
/// @dev A mapping from owner to a collection of his tokens (IDs)
/// @dev ERC20 compliant structure for balances can be derived
/// as a length of each collection in the mapping
/// @dev ERC20 balances[owner] is equal to collections[owner].length
mapping(address => uint32[]) public collections;
/// @dev Array with all token ids, used for enumeration
/// @dev ERC20 compliant structure for totalSupply can be derived
/// as a length of this collection
/// @dev ERC20 totalSupply() is equal to allTokens.length
uint32[] public allTokens;
/// @dev The data in token's state may contain lock(s)
/// (ex.: is gem currently mining or not)
/// @dev A locked token cannot be transferred or upgraded
/// @dev The token is locked if it contains any bits
/// from the `lockedBitmask` in its `state` set
uint64 public lockedBitmask = DEFAULT_MINING_BIT;
/// @dev Enables ERC721 transfers of the tokens
uint32 public constant FEATURE_TRANSFERS = 0x00000001;
/// @dev Enables ERC721 transfers on behalf
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x00000002;
/// @dev Enables partial support of ERC20 transfers of the tokens,
/// allowing to transfer only all owned tokens at once
//uint32 public constant ERC20_TRANSFERS = 0x00000004;
/// @dev Enables partial support of ERC20 transfers on behalf
/// allowing to transfer only all owned tokens at once
//uint32 public constant ERC20_TRANSFERS_ON_BEHALF = 0x00000008;
/// @dev Enables full support of ERC20 transfers of the tokens,
/// allowing to transfer arbitrary amount of the tokens at once
//uint32 public constant ERC20_INSECURE_TRANSFERS = 0x00000010;
/// @dev Default bitmask indicating that the gem is `mining`
/// @dev Consists of a single bit at position 1 β binary 1
/// @dev This bit is cleared by `miningComplete`
/// @dev The bit meaning in gem's `state` is as follows:
/// 0: not mining
/// 1: mining
uint64 public constant DEFAULT_MINING_BIT = 0x1; // bit number 1
/// @notice Exchange is responsible for trading tokens on behalf of token holders
/// @dev Role ROLE_EXCHANGE allows executing transfer on behalf of token holders
/// @dev Not used
//uint32 public constant ROLE_EXCHANGE = 0x00010000;
/// @notice Level provider is responsible for enabling the workshop
/// @dev Role ROLE_LEVEL_PROVIDER allows leveling up the gem
uint32 public constant ROLE_LEVEL_PROVIDER = 0x00100000;
/// @notice Grade provider is responsible for enabling the workshop
/// @dev Role ROLE_GRADE_PROVIDER allows modifying gem's grade
uint32 public constant ROLE_GRADE_PROVIDER = 0x00200000;
/// @notice Token state provider is responsible for enabling the mining protocol
/// @dev Role ROLE_STATE_PROVIDER allows modifying token's state
uint32 public constant ROLE_STATE_PROVIDER = 0x00400000;
/// @notice Token state provider is responsible for enabling the mining protocol
/// @dev Role ROLE_STATE_LOCK_PROVIDER allows modifying token's locked bitmask
uint32 public constant ROLE_STATE_LOCK_PROVIDER = 0x00800000;
/// @notice Token creator is responsible for creating tokens
/// @dev Role ROLE_TOKEN_CREATOR allows minting tokens
uint32 public constant ROLE_TOKEN_CREATOR = 0x00040000;
/// @notice Token destroyer is responsible for destroying tokens
/// @dev Role ROLE_TOKEN_DESTROYER allows burning tokens
//uint32 public constant ROLE_TOKEN_DESTROYER = 0x00080000;
/// @dev Magic value to be returned upon successful reception of an NFT
/// @dev Equal to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
/// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
/**
* Supported interfaces section
*/
/**
* ERC721 interface definition in terms of ERC165
*
* 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 private constant InterfaceId_ERC721 = 0x80ac58cd;
/**
* ERC721 interface extension β exists(uint256)
*
* 0x4f558e79 == bytes4(keccak256('exists(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/**
* ERC721 interface extension - ERC721Enumerable
*
* 0x780e9d63 ==
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* ERC721 interface extension - ERC721Metadata
*
* 0x5b5e139f ==
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/// @dev Event names are self-explanatory:
/// @dev Fired in mint()
/// @dev Address `_by` allows to track who created a token
event Minted(address indexed _by, address indexed _to, uint32 indexed _tokenId);
/// @dev Fired in burn()
/// @dev Address `_by` allows to track who destroyed a token
//event Burnt(address indexed _from, address _by, uint32 indexed _tokenId);
/// @dev Fired in transfer(), transferFor(), mint()
/// @dev When minting a token, address `_from` is zero
/// @dev ERC20/ERC721 compliant event
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId, uint256 _value);
/// @dev Fired in approve()
/// @dev ERC721 compliant event
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev Fired in setApprovalForAll()
/// @dev ERC721 compliant event
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _value);
/// @dev Fired in levelUp()
event LevelUp(address indexed _by, address indexed _owner, uint256 indexed _tokenId, uint8 _levelReached);
/// @dev Fired in upgradeGrade()
event UpgradeComplete(address indexed _by, address indexed _owner, uint256 indexed _tokenId, uint32 _gradeFrom, uint32 _gradeTo);
/// @dev Fired in setState()
event StateModified(address indexed _by, address indexed _owner, uint256 indexed _tokenId, uint48 _stateFrom, uint48 _stateTo);
/// @dev Creates a Gem ERC721 instance,
/// @dev Registers a ERC721 interface using ERC165
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets a gem by ID, representing it as two integers.
* The two integers are tightly packed with a gem data:
* First integer (high bits) contains (from higher to lower bits order):
* coordinates:
* plotId,
* depth (block ID),
* gemNum (gem ID within a block)
* color,
* levelModified,
* level,
* gradeModified,
* grade,
* stateModified,
* state,
* Second integer (low bits) contains (from higher to lower bits order):
* creationTime,
* index,
* ownershipModified,
* owner
* @dev Throws if gem doesn't exist
* @param _tokenId ID of the gem to fetch
*/
function getPacked(uint256 _tokenId) public constant returns(uint256, uint256) {
// validate gem existence
require(exists(_tokenId));
// load the gem from storage
Gem memory gem = gems[_tokenId];
// pack high 256 bits of the result
uint256 high = uint256(gem.coordinates) << 192
| uint192(gem.color) << 184
| uint184(gem.levelModified) << 152
| uint152(gem.level) << 144
| uint144(gem.gradeModified) << 112
| uint112(gem.grade) << 80
| uint80(gem.stateModified) << 48
| uint48(gem.state);
// pack low 256 bits of the result
uint256 low = uint256(gem.creationTime) << 224
| uint224(gem.index) << 192
| uint192(gem.ownershipModified) << 160
| uint160(gem.owner);
// return the whole 512 bits of result
return (high, low);
}
/**
* @dev Allows to fetch collection of tokens, including internal token data
* in a single function, useful when connecting to external node like INFURA
* @param owner an address to query a collection for
*/
function getPackedCollection(address owner) public constant returns (uint80[]) {
// get an array of Gem IDs owned by an `owner` address
uint32[] memory tokenIds = getCollection(owner);
// how many gems are there in a collection
uint32 balance = uint32(tokenIds.length);
// data container to store the result
uint80[] memory result = new uint80[](balance);
// fetch token info one by one and pack into structure
for(uint32 i = 0; i < balance; i++) {
// token ID to work with
uint32 tokenId = tokenIds[i];
// get the token properties and pack them together with tokenId
uint48 properties = getProperties(tokenId);
// pack the data
result[i] = uint80(tokenId) << 48 | properties;
}
// return the packed data structure
return result;
}
/**
* @notice Retrieves a collection of tokens owned by a particular address
* @notice An order of token IDs is not guaranteed and may change
* when a token from the list is transferred
* @param owner an address to query a collection for
* @return an ordered list of tokens
*/
function getCollection(address owner) public constant returns(uint32[]) {
// read a collection from mapping and return
return collections[owner];
}
/**
* @dev Allows setting the `lockedBitmask` parameter of the contract,
* which is used to determine if a particular token is locked or not
* @dev A locked token cannot be transferred, upgraded or burnt
* @dev The token is locked if it contains any bits
* from the `lockedBitmask` in its `state` set
* @dev Requires sender to have `ROLE_STATE_PROVIDER` permission.
* @param bitmask a value to set `lockedBitmask` to
*/
function setLockedBitmask(uint64 bitmask) public {
// check that the call is made by a state lock provider
require(__isSenderInRole(ROLE_STATE_LOCK_PROVIDER));
// update the locked bitmask
lockedBitmask = bitmask;
}
/**
* @dev Gets the coordinates of a token
* @param _tokenId ID of the token to get coordinates for
* @return a token coordinates
*/
function getCoordinates(uint256 _tokenId) public constant returns(uint64) {
// validate token existence
require(exists(_tokenId));
// obtain token's coordinates from storage and return
return gems[_tokenId].coordinates;
}
/**
* @dev Gets the land plot ID of a gem
* @param _tokenId ID of the gem to get land plot ID value for
* @return a token land plot ID
*/
function getPlotId(uint256 _tokenId) public constant returns(uint32) {
// extract high 32 bits of the coordinates and return
return uint32(getCoordinates(_tokenId) >> 32);
}
/**
* @dev Gets the depth (block ID) within plot of land of a gem
* @param _tokenId ID of the gem to get depth value for
* @return a token depth
*/
function getDepth(uint256 _tokenId) public constant returns(uint16) {
// extract middle 16 bits of the coordinates and return
return uint16(getCoordinates(_tokenId) >> 16);
}
/**
* @dev Gets the gem's number within land block
* @param _tokenId ID of the gem to get depth value for
* @return a gem number within a land block
*/
function getGemNum(uint256 _tokenId) public constant returns(uint16) {
// extract low 16 bits of the coordinates and return
return uint16(getCoordinates(_tokenId));
}
/**
* @dev Gets the gem's properties β color, level and
* grade - as packed uint32 number
* @param _tokenId ID of the gem to get properties for
* @return gem's properties - color, level, grade as packed uint32
*/
function getProperties(uint256 _tokenId) public constant returns(uint48) {
// validate token existence
require(exists(_tokenId));
// read gem from storage
Gem memory gem = gems[_tokenId];
// pack data structure and return
return uint48(gem.color) << 40 | uint40(gem.level) << 32 | gem.grade;
}
/**
* @dev Gets the color of a token
* @param _tokenId ID of the token to get color for
* @return a token color
*/
function getColor(uint256 _tokenId) public constant returns(uint8) {
// validate token existence
require(exists(_tokenId));
// obtain token's color from storage and return
return gems[_tokenId].color;
}
/**
* @dev Gets the level modified date of a token
* @param _tokenId ID of the token to get level modification date for
* @return a token level modification date
*/
function getLevelModified(uint256 _tokenId) public constant returns(uint32) {
// validate token existence
require(exists(_tokenId));
// obtain token's level modified date from storage and return
return gems[_tokenId].levelModified;
}
/**
* @dev Gets the level of a token
* @param _tokenId ID of the token to get level for
* @return a token level
*/
function getLevel(uint256 _tokenId) public constant returns(uint8) {
// validate token existence
require(exists(_tokenId));
// obtain token's level from storage and return
return gems[_tokenId].level;
}
/**
* @dev Levels up a gem
* @dev Requires sender to have `ROLE_STATE_PROVIDER` permission
* @param _tokenId ID of the gem to level up
*/
function levelUp(uint256 _tokenId) public {
// check that the call is made by a level provider
require(__isSenderInRole(ROLE_LEVEL_PROVIDER));
// check that token to set state for exists
require(exists(_tokenId));
// update the level modified date
gems[_tokenId].levelModified = uint32(block.number);
// increment the level required
gems[_tokenId].level++;
// emit an event
emit LevelUp(msg.sender, ownerOf(_tokenId), _tokenId, gems[_tokenId].level);
}
/**
* @dev Gets the grade modified date of a gem
* @param _tokenId ID of the gem to get grade modified date for
* @return a token grade modified date
*/
function getGradeModified(uint256 _tokenId) public constant returns(uint32) {
// validate token existence
require(exists(_tokenId));
// obtain token's grade modified date from storage and return
return gems[_tokenId].gradeModified;
}
/**
* @dev Gets the grade of a gem
* @param _tokenId ID of the gem to get grade for
* @return a token grade
*/
function getGrade(uint256 _tokenId) public constant returns(uint32) {
// validate token existence
require(exists(_tokenId));
// obtain token's grade from storage and return
return gems[_tokenId].grade;
}
/**
* @dev Gets the grade type of a gem
* @param _tokenId ID of the gem to get grade type for
* @return a token grade type
*/
function getGradeType(uint256 _tokenId) public constant returns(uint8) {
// extract high 8 bits of the grade and return
return uint8(getGrade(_tokenId) >> 24);
}
/**
* @dev Gets the grade value of a gem
* @param _tokenId ID of the gem to get grade value for
* @return a token grade value
*/
function getGradeValue(uint256 _tokenId) public constant returns(uint24) {
// extract low 24 bits of the grade and return
return uint24(getGrade(_tokenId));
}
/**
* @dev Upgrades the grade of the gem
* @dev Requires new grade to be higher than an old one
* @dev Requires sender to have `ROLE_GRADE_PROVIDER` permission
* @param _tokenId ID of the gem to modify the grade for
* @param grade new grade to set for the token, should be higher then current state
*/
function upgradeGrade(uint256 _tokenId, uint32 grade) public {
// check that the call is made by a grade provider
require(__isSenderInRole(ROLE_GRADE_PROVIDER));
// check that token to set grade for exists
require(exists(_tokenId));
// check if we're not downgrading the gem
require(gems[_tokenId].grade < grade);
// emit an event
emit UpgradeComplete(msg.sender, ownerOf(_tokenId), _tokenId, gems[_tokenId].grade, grade);
// set the grade required
gems[_tokenId].grade = grade;
// update the grade modified date
gems[_tokenId].gradeModified = uint32(block.number);
}
/**
* @dev Gets the state modified date of a token
* @param _tokenId ID of the token to get state modified date for
* @return a token state modification date
*/
function getStateModified(uint256 _tokenId) public constant returns(uint32) {
// validate token existence
require(exists(_tokenId));
// obtain token's state modified date from storage and return
return gems[_tokenId].stateModified;
}
/**
* @dev Gets the state of a token
* @param _tokenId ID of the token to get state for
* @return a token state
*/
function getState(uint256 _tokenId) public constant returns(uint48) {
// validate token existence
require(exists(_tokenId));
// obtain token's state from storage and return
return gems[_tokenId].state;
}
/**
* @dev Sets the state of a token
* @dev Requires sender to have `ROLE_STATE_PROVIDER` permission
* @param _tokenId ID of the token to set state for
* @param state new state to set for the token
*/
function setState(uint256 _tokenId, uint48 state) public {
// check that the call is made by a state provider
require(__isSenderInRole(ROLE_STATE_PROVIDER));
// check that token to set state for exists
require(exists(_tokenId));
// emit an event
emit StateModified(msg.sender, ownerOf(_tokenId), _tokenId, gems[_tokenId].state, state);
// set the state required
gems[_tokenId].state = state;
// update the state modified date
gems[_tokenId].stateModified = uint32(block.number);
}
/**
* @dev Gets the creation time of a token
* @param _tokenId ID of the token to get creation time for
* @return a token creation time
*/
function getCreationTime(uint256 _tokenId) public constant returns(uint32) {
// validate token existence
require(exists(_tokenId));
// obtain token's creation time from storage and return
return gems[_tokenId].creationTime;
}
/**
* @dev Gets the ownership modified time of a token
* @param _tokenId ID of the token to get ownership modified time for
* @return a token ownership modified time
*/
function getOwnershipModified(uint256 _tokenId) public constant returns(uint32) {
// validate token existence
require(exists(_tokenId));
// obtain token's ownership modified time from storage and return
return gems[_tokenId].ownershipModified;
}
/**
* @notice Total number of existing tokens (tracked by this contract)
* @return A count of valid tokens tracked by this contract,
* where each one of them has an assigned and
* queryable owner not equal to the zero address
*/
function totalSupply() public constant returns (uint256) {
// read the length of the `allTokens` collection
return allTokens.length;
}
/**
* @notice Enumerate valid tokens
* @dev Throws if `_index` >= `totalSupply()`.
* @param _index a counter less than `totalSupply()`
* @return The token ID for the `_index`th token, unsorted
*/
function tokenByIndex(uint256 _index) public constant returns (uint256) {
// out of bounds check
require(_index < allTokens.length);
// get the token ID and return
return allTokens[_index];
}
/**
* @notice Enumerate tokens assigned to an owner
* @dev Throws if `_index` >= `balanceOf(_owner)`.
* @param _owner an address of the owner to query token from
* @param _index a counter less than `balanceOf(_owner)`
* @return the token ID for the `_index`th token assigned to `_owner`, unsorted
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256) {
// out of bounds check
require(_index < collections[_owner].length);
// get the token ID from owner collection and return
return collections[_owner][_index];
}
/**
* @notice Gets an amount of token owned by the given address
* @dev Gets the balance of the specified address
* @param _owner address to query the balance for
* @return an amount owned by the address passed as an input parameter
*/
function balanceOf(address _owner) public constant returns (uint256) {
// read the length of the `who`s collection of tokens
return collections[_owner].length;
}
/**
* @notice Checks if specified token exists
* @dev Returns whether the specified token ID exists
* @param _tokenId ID of the token to query the existence for
* @return whether the token exists (true - exists)
*/
function exists(uint256 _tokenId) public constant returns (bool) {
// check if this token exists (owner is not zero)
return gems[_tokenId].owner != address(0);
}
/**
* @notice Finds an owner address for a token specified
* @dev Gets the owner of the specified token from the `gems` mapping
* @dev Throws if a token with the ID specified doesn't exist
* @param _tokenId ID of the token to query the owner for
* @return owner address currently marked as the owner of the given token
*/
function ownerOf(uint256 _tokenId) public constant returns (address) {
// check if this token exists
require(exists(_tokenId));
// return owner's address
return gems[_tokenId].owner;
}
/**
* @dev Creates new token with `tokenId` ID specified and
* assigns an ownership `to` for that token
* @dev Allows setting initial token's properties
* @param to an address to assign created token ownership to
* @param tokenId ID of the token to create
*/
function mint(
address to,
uint32 tokenId,
uint32 plotId,
uint16 depth,
uint16 gemNum,
uint8 color,
uint8 level,
uint8 gradeType,
uint24 gradeValue
) public {
// validate destination address
require(to != address(0));
require(to != address(this));
// check if caller has sufficient permissions to mint a token
// and if feature is enabled globally
require(__isSenderInRole(ROLE_TOKEN_CREATOR));
// delegate call to `__mint`
__mint(to, tokenId, plotId, depth, gemNum, color, level, gradeType, gradeValue);
// fire ERC20 transfer event
emit Transfer(address(0), to, tokenId, 1);
}
/**
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @dev Requires the sender of the transaction to be an owner
* of the token specified (`tokenId`)
* @param to new owner address
* @param _tokenId ID of the token to transfer ownership rights for
*/
function transfer(address to, uint256 _tokenId) public {
// check if token transfers feature is enabled
require(__isFeatureEnabled(FEATURE_TRANSFERS));
// call sender gracefully - `from`
address from = msg.sender;
// delegate call to unsafe `__transfer`
__transfer(from, to, _tokenId);
}
/**
* @notice A.k.a "transfer a token on behalf"
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @notice Allows transferring ownership rights by a trading operator
* on behalf of token owner. Allows building an exchange of tokens.
* @dev Transfers the ownership of a given token ID to another address
* @dev Requires the transaction sender to be one of:
* owner of a gem - then its just a usual `transfer`
* approved β an address explicitly approved earlier by
* the owner of a token to transfer this particular token `tokenId`
* operator - an address explicitly approved earlier by
* the owner to transfer all his tokens on behalf
* @param from current owner of the token
* @param to address to receive the ownership of the token
* @param _tokenId ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 _tokenId) public {
// check if transfers on behalf feature is enabled
require(__isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF));
// call sender gracefully - `operator`
address operator = msg.sender;
// find if an approved address exists for this token
address approved = approvals[_tokenId];
// we assume `from` is an owner of the token,
// this will be explicitly checked in `__transfer`
// fetch how much approvals left for an operator
bool approvedOperator = approvedOperators[from][operator];
// operator must have an approval to transfer this particular token
// or operator must be approved to transfer all the tokens
// or, if nothing satisfies, this is equal to regular transfer,
// where `from` is basically a transaction sender and owner of the token
if(operator != approved && !approvedOperator) {
// transaction sender doesn't have any special permissions
// we will treat him as a token owner and sender and try to perform
// a regular transfer:
// check `from` to be `operator` (transaction sender):
require(from == operator);
// additionally check if token transfers feature is enabled
require(__isFeatureEnabled(FEATURE_TRANSFERS));
}
// delegate call to unsafe `__transfer`
__transfer(from, to, _tokenId);
}
/**
* @notice A.k.a "safe transfer a token on behalf"
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @notice Allows transferring ownership rights by a trading operator
* on behalf of token owner. Allows building an exchange of tokens.
* @dev Safely transfers the ownership of a given token ID to another address
* @dev Requires the transaction sender to be the owner, approved, or operator
* @dev When transfer is complete, this function
* checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
* @param _from current owner of the token
* @param _to address to receive the ownership of the token
* @param _tokenId ID of the token to be transferred
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public {
// delegate call to usual (unsafe) `transferFrom`
transferFrom(_from, _to, _tokenId);
// check if receiver `_to` supports ERC721 interface
if (AddressUtils.isContract(_to)) {
// if `_to` is a contract β execute onERC721Received
bytes4 response = ERC721Receiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
// expected response is ERC721_RECEIVED
require(response == ERC721_RECEIVED);
}
}
/**
* @notice A.k.a "safe transfer a token on behalf"
* @notice Transfers ownership rights of a token defined
* by the `tokenId` to a new owner specified by address `to`
* @notice Allows transferring ownership rights by a trading operator
* on behalf of token owner. Allows building an exchange of tokens.
* @dev Safely transfers the ownership of a given token ID to another address
* @dev Requires the transaction sender to be the owner, approved, or operator
* @dev Requires from to be an owner of the token
* @dev 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,uint256,bytes)"))`;
* otherwise the transfer is reverted.
* @dev This works identically to the other function with an extra data parameter,
* except this function just sets data to "".
* @param _from current owner of the token
* @param _to address to receive the ownership of the token
* @param _tokenId ID of the token to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
// delegate call to overloaded `safeTransferFrom`, set data to ""
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @notice Approves an address to transfer the given token on behalf of its owner
* Can also be used to revoke an approval by setting `to` address to zero
* @dev The zero `to` address revokes an approval for a given token
* @dev There can only be one approved address per token at a given time
* @dev This function can only be called by the token owner
* @param _approved address to be approved to transfer the token on behalf of its owner
* @param _tokenId ID of the token to be approved for transfer on behalf
*/
function approve(address _approved, uint256 _tokenId) public {
// call sender nicely - `from`
address from = msg.sender;
// get token owner address (also ensures that token exists)
address owner = ownerOf(_tokenId);
// caller must own this token
require(from == owner);
// approval for owner himself is pointless, do not allow
require(_approved != owner);
// either we're removing approval, or setting it
require(approvals[_tokenId] != address(0) || _approved != address(0));
// set an approval (deletes an approval if to == 0)
approvals[_tokenId] = _approved;
// emit an ERC721 event
emit Approval(from, _approved, _tokenId);
}
/**
* @notice Removes an approved address, which was previously added by `approve`
* for the given token. Equivalent to calling approve(0, tokenId)
* @dev Same as calling approve(0, tokenId)
* @param _tokenId ID of the token to remove approved address for
*/
function revokeApproval(uint256 _tokenId) public {
// delegate call to `approve`
approve(address(0), _tokenId);
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer *all* tokens of the sender on their behalf
* @param to operator address to set the approval for
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
// call sender nicely - `from`
address from = msg.sender;
// validate destination address
require(to != address(0));
// approval for owner himself is pointless, do not allow
require(to != from);
// set an approval
approvedOperators[from][to] = approved;
// emit an ERC721 compliant event
emit ApprovalForAll(from, to, approved);
}
/**
* @notice Get the approved address for a single token
* @dev Throws if `_tokenId` is not a valid token ID.
* @param _tokenId ID of the token to find the approved address for
* @return the approved address for this token, or the zero address if there is none
*/
function getApproved(uint256 _tokenId) public constant returns (address) {
// validate token existence
require(exists(_tokenId));
// find approved address and return
return approvals[_tokenId];
}
/**
* @notice Query if an address is an authorized operator for another address
* @param _owner the address that owns at least one token
* @param _operator the address that acts on behalf of the owner
* @return true if `_operator` is an approved operator for `_owner`, false otherwise
*/
function isApprovedForAll(address _owner, address _operator) public constant returns (bool) {
// is there a positive amount of approvals left
return approvedOperators[_owner][_operator];
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev Throws if `_tokenId` is not a valid token ID.
* URIs are defined in RFC 3986.
* @param _tokenId uint256 ID of the token to query
* @return token URI
*/
function tokenURI(uint256 _tokenId) public constant returns (string) {
// validate token existence
require(exists(_tokenId));
// token URL consists of base URL part (domain) and token ID
return StringUtils.concat("http://cryptominerworld.com/gem/", StringUtils.itoa(_tokenId, 16));
}
/// @dev Creates new token with `tokenId` ID specified and
/// assigns an ownership `to` for this token
/// @dev Unsafe: doesn't check if caller has enough permissions to execute the call
/// checks only that the token doesn't exist yet
/// @dev Must be kept private at all times
function __mint(
address to,
uint32 tokenId,
uint32 plotId,
uint16 depth,
uint16 gemNum,
uint8 color,
uint8 level,
uint8 gradeType,
uint24 gradeValue
) private {
// check that `tokenId` is inside valid bounds
require(tokenId > 0);
// ensure that token with such ID doesn't exist
require(!exists(tokenId));
// create new gem in memory
Gem memory gem = Gem({
coordinates: uint64(plotId) << 32 | uint32(depth) << 16 | gemNum,
color: color,
levelModified: 0,
level: level,
gradeModified: 0,
grade: uint32(gradeType) << 24 | gradeValue,
stateModified: 0,
state: 0,
creationTime: uint32(block.number),
// token index within the owner's collection of token
// points to the place where the token will be placed to
index: uint32(collections[to].length),
ownershipModified: 0,
owner: to
});
// push newly created `tokenId` to the owner's collection of tokens
collections[to].push(tokenId);
// persist gem to the storage
gems[tokenId] = gem;
// add token ID to the `allTokens` collection,
// automatically updates total supply
allTokens.push(tokenId);
// fire Minted event
emit Minted(msg.sender, to, tokenId);
// fire ERC20/ERC721 transfer event
emit Transfer(address(0), to, tokenId, 1);
}
/// @dev Performs a transfer of a token `tokenId` from address `from` to address `to`
/// @dev Unsafe: doesn't check if caller has enough permissions to execute the call;
/// checks only for token existence and that ownership belongs to `from`
/// @dev Is save to call from `transfer(to, tokenId)` since it doesn't need any additional checks
/// @dev Must be kept private at all times
function __transfer(address from, address to, uint256 _tokenId) private {
// validate source and destination address
require(to != address(0));
require(to != from);
// impossible by design of transfer(), transferFrom(),
// approveToken() and approve()
assert(from != address(0));
// validate token existence
require(exists(_tokenId));
// validate token ownership
require(ownerOf(_tokenId) == from);
// transfer is not allowed for a locked gem
// (ex.: if ge is currently mining)
require(getState(_tokenId) & lockedBitmask == 0);
// clear approved address for this particular token + emit event
__clearApprovalFor(_tokenId);
// move gem ownership,
// update old and new owner's gem collections accordingly
__move(from, to, _tokenId);
// fire ERC20/ERC721 transfer event
emit Transfer(from, to, _tokenId, 1);
}
/// @dev Clears approved address for a particular token
function __clearApprovalFor(uint256 _tokenId) private {
// check if approval exists - we don't want to fire an event in vain
if(approvals[_tokenId] != address(0)) {
// clear approval
delete approvals[_tokenId];
// emit an ERC721 event
emit Approval(msg.sender, address(0), _tokenId);
}
}
/// @dev Move a `gem` from owner `from` to a new owner `to`
/// @dev Unsafe, doesn't check for consistence
/// @dev Must be kept private at all times
function __move(address from, address to, uint256 _tokenId) private {
// cast token ID to uint32 space
uint32 tokenId = uint32(_tokenId);
// overflow check, failure impossible by design of mint()
assert(tokenId == _tokenId);
// get the gem pointer to the storage
Gem storage gem = gems[_tokenId];
// get a reference to the collection where gem is now
uint32[] storage source = collections[from];
// get a reference to the collection where gem goes to
uint32[] storage destination = collections[to];
// collection `source` cannot be empty, if it is - it's a bug
assert(source.length != 0);
// index of the gem within collection `source`
uint32 i = gem.index;
// we put the last gem in the collection `source` to the position released
// get an ID of the last gem in `source`
uint32 sourceId = source[source.length - 1];
// update gem index to point to proper place in the collection `source`
gems[sourceId].index = i;
// put it into the position i within `source`
source[i] = sourceId;
// trim the collection `source` by removing last element
source.length--;
// update gem index according to position in new collection `destination`
gem.index = uint32(destination.length);
// update gem owner
gem.owner = to;
// update ownership transfer date
gem.ownershipModified = uint32(block.number);
// push gem into collection
destination.push(tokenId);
}
} | Allows setting the `lockedBitmask` parameter of the contract, which is used to determine if a particular token is locked or not A locked token cannot be transferred, upgraded or burnt The token is locked if it contains any bits from the `lockedBitmask` in its `state` set Requires sender to have `ROLE_STATE_PROVIDER` permission. bitmask a value to set `lockedBitmask` to/ check that the call is made by a state lock provider update the locked bitmask | function setLockedBitmask(uint64 bitmask) public {
require(__isSenderInRole(ROLE_STATE_LOCK_PROVIDER));
lockedBitmask = bitmask;
}
| 1,803,650 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import "./IslandBase.sol";
contract EthereumIslands is IslandBase {
uint256 public genesisMintIndex;
uint256 public genesisMintPrice = 1000000 * 10**18;
IERC20Burnable public pmlg;
constructor(
IERC20Burnable pml,
IMetadataStorage metadataStorage,
IERC20Burnable _pmlg
) IslandBase("Grassland Archipelago", "PGA", pml, metadataStorage) {
pmlg = _pmlg;
}
// @notice mint genesis islands with PMLG tokens
function mintGenesis(uint256 amount) external {
if (genesisMintIndex + amount > genesisLimit) revert MintWouldExceedLimit();
pmlg.burnFrom(msg.sender, amount * genesisMintPrice);
uint256 newMintIndex = genesisMintIndex;
for (uint256 i = 0; i < amount; i++) {
++newMintIndex;
_safeMint(msg.sender, newMintIndex);
}
genesisMintIndex = newMintIndex;
}
// ------------------
// Setter
// ------------------
function setGenesisMintPrice(uint256 _genesisMintPrice) external onlyOwner {
genesisMintPrice = _genesisMintPrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./MetadataStorage.sol";
import "../ERC-20/IERC20Burnable.sol";
contract IslandBase is ERC721Enumerable, Ownable {
uint256 public constant GENESIS_FALLBACK_ID = 10000000;
uint256 public constant FALLBACK_ID = 20000000;
bool public burnIsActive;
// @dev max mintable genesis Islands
uint256 public genesisLimit = 1000;
uint256 public mintIndex = genesisLimit;
// @dev max mintable "non-genesis" Islands
uint256 public limit = 3000;
uint256 public mintPrice = 100000 * 10**18;
IERC20Burnable public pml;
IMetadataStorage public metadataStorage;
// @dev occurs when a mint function is called and the current supply + the amount would exceed the limit
error MintWouldExceedLimit();
// @dev occurs when the burn function is called when the burning functionality is inactive
error BurnNotActive();
// @dev occurs if anything is to be done with the token for which the sender must be the owner or approved by the
// owner and the sender does not match any of these criteria
error NotTheOwnerOrApproved(uint256 tokenId);
constructor(
string memory name,
string memory symbol,
IERC20Burnable _pml,
IMetadataStorage _metadataStorage
) ERC721(name, symbol) {
pml = _pml;
metadataStorage = _metadataStorage;
}
// @notice mint "non-genesis" islands
function mint(uint256 amount) external {
if (mintIndex + amount > limit + genesisLimit) revert MintWouldExceedLimit();
pml.burnFrom(msg.sender, amount * mintPrice);
uint256 newMintIndex = mintIndex;
for (uint256 i = 0; i < amount; i++) {
++newMintIndex;
_safeMint(msg.sender, newMintIndex);
}
mintIndex = newMintIndex;
}
// @notice tokens can only be burned is the flag burnIsActive is set to true
function burn(uint256 tokenId) external {
if (!burnIsActive) revert BurnNotActive();
if (!_isApprovedOrOwner(msg.sender, tokenId)) revert NotTheOwnerOrApproved(tokenId);
_burn(tokenId);
}
function tokensOfOwner(address owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
result[i] = tokenOfOwnerByIndex(owner, i);
}
return result;
}
}
// ------------------
// Explicit overrides
// ------------------
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
}
// @notice get the BASE64 encoded metadata from a OnChainMetadataStorage contract on chain.
// @dev if the metadata is not stored under the ID, a fallback is used: genesis 1000000, "non-genesis" 2000000
// @return the metadata BASE64 encoded.
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
uint256 fallbackId = tokenId <= genesisLimit ? GENESIS_FALLBACK_ID : FALLBACK_ID;
return metadataStorage.getMetadata(tokenId, fallbackId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
// ------------------
// Setter
// ------------------
function toggleBurnState() external onlyOwner {
burnIsActive = !burnIsActive;
}
function setMetadataStorage(IMetadataStorage _metadataStorage) external onlyOwner {
metadataStorage = _metadataStorage;
}
function setLimit(uint256 _limit) external onlyOwner {
limit = _limit;
}
function setMintPrice(uint256 _mintPrice) external onlyOwner {
mintPrice = _mintPrice;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).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(base, _tokenURI));
}
return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @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();
}
}
// 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
pragma solidity ^0.8.12;
import "@openzeppelin/contracts/access/Ownable.sol";
interface IMetadataStorage {
function getMetadata(uint256 id, uint256 fallbackId) external view returns (string memory);
}
contract MetadataStorage is IMetadataStorage, Ownable {
mapping(uint256 => string) private _idToMetadata;
// solhint-disable-next-line no-empty-blocks
constructor() {
// nothing to do
}
function getMetadata(uint256 id, uint256 fallbackId) external view returns (string memory) {
if (keccak256(abi.encodePacked(_idToMetadata[id])) == keccak256("")) {
return _idToMetadata[fallbackId];
} else {
return _idToMetadata[id];
}
}
function setMetadata(uint256 id, string memory metadata) external onlyOwner {
_idToMetadata[id] = metadata;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
interface IERC20Burnable {
function burnFrom(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner");
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);
_afterTokenTransfer(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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// 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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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/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 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @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);
/**
* @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);
} | tokens can only be burned is the flag burnIsActive is set to true | function burn(uint256 tokenId) external {
if (!burnIsActive) revert BurnNotActive();
if (!_isApprovedOrOwner(msg.sender, tokenId)) revert NotTheOwnerOrApproved(tokenId);
_burn(tokenId);
}
| 12,009,371 |
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
// ============ Contract information ============
/**
* @title InterestRateSwapFactory
* @notice A deployment contract for Greenwood basis swap pools
* @author Greenwood Labs
*/
// ============ Imports ============
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import './libraries/FactoryUtils.sol';
contract Factory {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ============ Immutable storage ============
address private immutable governance;
// ============ Mutable storage ============
mapping(address => mapping(uint256 => mapping(uint256 => mapping(uint256 => mapping(uint256 => address))))) public getPool;
mapping(uint256 => bool) public swapDurations;
mapping(uint256 => bool) public protocols;
mapping(uint256 => mapping(address => bool)) public protocolMarkets;
mapping(uint256 => address) public protocolAdapters;
mapping(address => uint256) public underlierDecimals;
mapping(address => Params) public getParamsByPool;
address[] public allPools;
uint256 public swapDurationCount;
uint256 public protocolCount;
uint256 public protocolMarketCount;
bool public isPaused;
// ============ Structs ============
struct Params {
uint256 durationInSeconds;
uint256 position;
uint256 protocol0;
uint256 protocol1;
address underlier;
}
struct FeeParams {
uint256 rateLimit;
uint256 rateSensitivity;
uint256 utilizationInflection;
uint256 rateMultiplier;
}
// ============ Events ============
event PoolCreated(
uint256 durationInSeconds,
address pool,
uint256 position,
uint256[] protocols,
address indexed underlier,
uint256 poolLength
);
// ============ Constructor ============
constructor(
address _governance
) {
governance = _governance;
}
// ============ Modifiers ============
modifier onlyGovernance {
// assert that the caller is governance
require(msg.sender == governance);
_;
}
// ============ External methods ============
// ============ Get the number of created pools ============
function allPoolsLength() external view returns (uint256) {
// return the length of the allPools array
return allPools.length;
}
// ============ Pause and unpause the factory ============
function togglePause() external onlyGovernance() returns (bool){
// toggle the value of isPaused
isPaused = !isPaused;
return true;
}
// ============ Update the supported swap durations ============
function updateSwapDurations(
uint256 _duration,
bool _is_supported
) external onlyGovernance() returns (bool){
// get the initial value
bool initialValue = swapDurations[_duration];
// update the swapDurations mapping
swapDurations[_duration] = _is_supported;
// check if a swapDuration is being added
if (initialValue == false && _is_supported == true) {
// increment the swapDurationCount
swapDurationCount = swapDurationCount.add(1);
}
// check if a swapDuration is being removed
else if (initialValue == true && _is_supported == false) {
// decrement the swapDurationCount
swapDurationCount = swapDurationCount.sub(1);
}
return true;
}
// ============ Update the supported protocols ============
function updateProtocols(
uint256 _protocol,
bool _is_supported
) external onlyGovernance() returns (bool){
// get the initial value
bool initialValue = protocols[_protocol];
// update the protocols mapping
protocols[_protocol] = _is_supported;
// check if a protocol is being added
if (initialValue == false && _is_supported == true) {
// increment the protocolCount
protocolCount = protocolCount.add(1);
}
// check if a protocol is being removed
else if (initialValue == true && _is_supported == false) {
// decrement the protocolCount
protocolCount = protocolCount.sub(1);
}
return true;
}
// ============ Update the supported protocol markets ============
function updateProtocolMarkets(
uint256 _protocol,
address _market,
bool _is_supported
) external onlyGovernance() returns (bool){
// get the initial value
bool initialValue = protocolMarkets[_protocol][_market];
// update the protocolMarkets mapping
protocolMarkets[_protocol][_market] = _is_supported;
// check if a protocol market is being added
if (initialValue == false && _is_supported == true) {
// increment the protocolMarketCount
protocolMarketCount = protocolMarketCount.add(1);
}
// check if a protocol market is being removed
else if (initialValue == true && _is_supported == false) {
// decrement the protocolMarketCount
protocolMarketCount = protocolMarketCount.sub(1);
}
return true;
}
// ============ Update the protocol adapters mapping ============
function updateProtocolAdapters(
uint256 _protocol,
address _adapter
) external onlyGovernance() returns(bool) {
// update the protocolMarkets mapping
protocolAdapters[_protocol] = _adapter;
return true;
}
// ============ Update the underlier decimals mapping ============
function updateUnderlierDecimals (
address _underlier,
uint256 _decimals
) external onlyGovernance() returns (bool) {
require(_decimals <= 18, '20');
// update the underlierDecimals mapping
underlierDecimals[_underlier] = _decimals;
return true;
}
// ============ Create a new pool ============
function createPool(
uint256 _duration,
uint256 _position,
uint256[] memory _protocols,
address _underlier,
uint256 _initialDeposit,
uint256 _rateLimit,
uint256 _rateSensitivity,
uint256 _utilizationInflection,
uint256 _rateMultiplier
) external returns (address pool) {
// assert that the factory is not paused
require(isPaused == false, '1');
// assert that the duration of the swap is supported
require(swapDurations[_duration] == true, '2');
// assert that the position is supported
require(_position == 0 || _position == 1, '3');
// assert that the protocols are not the same
require(_protocols[0] != _protocols[1], '4');
// assert that both protocols are supported
require(protocols[_protocols[0]] && protocols[_protocols[1]], '4');
// assert that the specified protocols support the specified underlier
require(protocolMarkets[_protocols[0]][_underlier] && protocolMarkets[_protocols[1]][_underlier], '5');
// assert that the pool has not already been created
require(getPool[_underlier][_protocols[0]][_protocols[1]][_duration][_position] == address(0), '6');
// assert that the adapter for the specified protocol0 is defined
require(protocolAdapters[_protocols[0]] != address(0), '7');
// assert that the adapter for the specified protocol1 is defined
require(protocolAdapters[_protocols[1]] != address(0), '7');
// assert that the decimals for the underlier is defined
require(underlierDecimals[_underlier] != 0, '8');
FeeParams memory feeParams;
bytes memory initCode;
bytes32 salt;
// scope to avoid stack too deep errors
{
feeParams = FeeParams(
_rateLimit,
_rateSensitivity,
_utilizationInflection,
_rateMultiplier
);
}
// scope to avoid stack too deep errors
{
// generate byte code
(bytes memory encodedParams, bytes memory encodedPackedParams) = _generateByteCode(
_duration,
_position,
_protocols,
_underlier,
_initialDeposit,
feeParams
);
// generate the init code
initCode = FactoryUtils.generatePoolInitCode(encodedParams);
// generate the salt
salt = keccak256(encodedPackedParams);
}
// get the address of the pool
assembly {
pool := create2(0, add(initCode, 32), mload(initCode), salt)
}
// add the pool to the registry
getPool[_underlier][_protocols[0]][_protocols[1]][_duration][_position] = pool;
getParamsByPool[pool] = Params(_duration, _position, _protocols[0], _protocols[1], _underlier);
allPools.push(pool);
// transfer the initial deposit into the pool
IERC20(_underlier).safeTransferFrom(
msg.sender,
pool,
_initialDeposit
);
// emit a PoolCreated event
emit PoolCreated(
_duration,
pool,
_position,
_protocols,
_underlier,
allPools.length
);
}
// ============ Internal functions ============
// ============ Generates byte code for pool creation ============
function _generateByteCode(
uint256 _duration,
uint256 _position,
uint256[] memory _protocols,
address _underlier,
uint256 _initialDeposit,
FeeParams memory feeParams
) internal view returns (bytes memory encodedParams, bytes memory encodedPackedParams) {
// create the initcode
encodedParams = abi.encode(
_underlier,
underlierDecimals[_underlier],
protocolAdapters[_protocols[0]],
protocolAdapters[_protocols[1]],
_protocols[0],
_protocols[1],
_position,
_duration,
_initialDeposit,
feeParams.rateLimit,
feeParams.rateSensitivity,
feeParams.utilizationInflection,
feeParams.rateMultiplier,
msg.sender
);
// create the salt
encodedPackedParams = abi.encodePacked(
_underlier,
underlierDecimals[_underlier],
protocolAdapters[_protocols[0]],
protocolAdapters[_protocols[1]],
_protocols[0],
_protocols[1],
_position,
_duration,
_initialDeposit,
feeParams.rateLimit,
feeParams.rateSensitivity,
feeParams.utilizationInflection,
feeParams.rateMultiplier,
msg.sender
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
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: Unlicensed
pragma solidity 0.7.6;
import '../Pool.sol';
library FactoryUtils {
function generatePoolInitCode(bytes memory encodedParams) external pure returns (bytes memory) {
// generate the init code
return abi.encodePacked(
type(Pool).creationCode, encodedParams
);
}
}
// 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: Unlicensed
pragma solidity 0.7.6;
// ============ Contract information ============
/**
* @title Interest Rate Swaps V1
* @notice A pool for Interest Rate Swaps
* @author Greenwood Labs
*/
// ============ Imports ============
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/math/Math.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../interfaces/IPool.sol';
import '../interfaces/IAdapter.sol';
import '../interfaces/IGreenwoodERC20.sol';
import './GreenwoodERC20.sol';
contract Pool is IPool, GreenwoodERC20 {
// ============ Import usage ============
using SafeMath for uint256;
using SafeERC20 for IERC20;
// ============ Immutable storage ============
address private constant GOVERNANCE = 0xe3D5260Cd7F8a4207f41C3B2aC87882489f97213;
uint256 private constant TEN_EXP_18 = 1000000000000000000;
uint256 private constant STANDARD_DECIMALS = 18;
uint256 private constant BLOCKS_PER_DAY = 6570; // 13.15 seconds per block
uint256 private constant MAX_TO_PAY_BUFFER_NUMERATOR = 10;
uint256 private constant MAX_TO_PAY_BUFFER_DENOMINATOR = 100;
uint256 private constant DAYS_PER_YEAR = 360;
// ============ Mutable storage ============
address private factory;
address public adapter0;
address public adapter1;
address public underlier;
uint256 public protocol0;
uint256 public protocol1;
uint256 public totalSwapCollateral;
uint256 public totalSupplementaryCollateral;
uint256 public totalActiveLiquidity;
uint256 public totalAvailableLiquidity;
uint256 public utilization;
uint256 public totalFees;
uint256 public fee;
uint256 public direction;
uint256 public durationInDays;
uint256 public underlierDecimals;
uint256 public decimalDifference;
uint256 public rateLimit;
uint256 public rateSensitivity;
uint256 public utilizationInflection;
uint256 public rateMultiplier;
uint256 public maxDepositLimit;
mapping(bytes32 => Swap) public swaps;
mapping(address => uint256) public swapNumbers;
mapping(address => uint256) public liquidityProviderLastDeposit;
// ============ Structs ============
struct Swap {
address user;
bool isClosed;
uint256 notional;
uint256 swapCollateral;
uint256 activeLiquidity;
uint256 openBlock;
uint256 underlierProtocol0BorrowIndex;
uint256 underlierProtocol1BorrowIndex;
}
// ============ Modifiers ============
// None
// ============ Events ============
event OpenSwap(address indexed user, uint256 notional, uint256 activeLiquidity, uint256 swapFee);
event CloseSwap(address indexed user, uint256 notional, uint256 userToPay, uint256 ammToPay);
event DepositLiquidity(address indexed user, uint256 liquidityAmount);
event WithdrawLiquidity(address indexed user, uint256 liquidityAmount, uint256 feesAccrued);
event Liquidate(address indexed liquidator, address indexed user, uint256 swapNumber, uint256 liquidatorReward);
event Mint(address indexed user, uint256 underlyingTokenAmount, uint256 liquidityTokenAmount);
event Burn(address indexed user, uint256 underlyingTokenAmount, uint256 liquidityTokenAmount);
// ============ Constructor ============
constructor(
address _underlier,
uint256 _underlierDecimals,
address _adapter0,
address _adapter1,
uint256 _protocol0,
uint256 _protocol1,
uint256 _direction,
uint256 _durationInDays,
uint256 _initialDeposit,
uint256 _rateLimit,
uint256 _rateSensitivity,
uint256 _utilizationInflection,
uint256 _rateMultiplier,
address _poolDeployer
) {
// assert that the pool can be initialized with a non-zero amount
require(_initialDeposit > 0, 'Initial token amount must be greater than 0');
// initialize the pool
factory = msg.sender;
underlier = _underlier;
underlierDecimals = _underlierDecimals;
direction = _direction;
durationInDays = _durationInDays;
adapter0 = _adapter0;
adapter1 = _adapter1;
protocol0 = _protocol0;
protocol1 = _protocol1;
// calculate difference in decimals between underlier and STANDARD_DECIMALS
decimalDifference = _calculatedDecimalDifference(underlierDecimals, STANDARD_DECIMALS);
// adjust the token decimals to the standard number
uint256 adjustedInitialDeposit = _convertToStandardDecimal(_initialDeposit);
totalAvailableLiquidity = adjustedInitialDeposit;
rateLimit = _rateLimit;
rateSensitivity = _rateSensitivity;
utilizationInflection = _utilizationInflection;
rateMultiplier = _rateMultiplier;
maxDepositLimit = 1000000000000000000000000;
// calculate the initial swap fee
fee = _calculateFee();
// Update the pool deployer's deposit block number
liquidityProviderLastDeposit[_poolDeployer] = block.number;
// mint LP tokens to the pool deployer
_mintLPTokens(_poolDeployer, adjustedInitialDeposit);
}
// ============ Opens a new basis swap ============
function openSwap(uint256 _notional) external override returns (bool) {
// assert that a swap is opened with an non-zero notional
require(_notional > 0, '9');
// adjust notional to standard decimal places
uint256 adjustedNotional = _convertToStandardDecimal(_notional);
// calculate the swap collateral and trade active liquidity based off the notional
(uint256 swapCollateral, uint256 activeLiquidity) = _calculateSwapCollateralAndActiveLiquidity(adjustedNotional);
// assert that there is sufficient liquidity to open this swap
require(activeLiquidity <= totalAvailableLiquidity, '10');
// assign the supplementary collateral
uint256 supplementaryCollateral = activeLiquidity;
// calculate the fee based on swap collateral
uint256 swapFee = swapCollateral.mul(fee).div(TEN_EXP_18);
// calculate the current borrow index for the underlier on protocol 0
uint256 underlierProtocol0BorrowIndex = IAdapter(adapter0).getBorrowIndex(underlier);
// calculate the current borrow index for the underlier on protocol 1
uint256 underlierProtocol1BorrowIndex = IAdapter(adapter1).getBorrowIndex(underlier);
// create the swap struct
Swap memory swap = Swap(
msg.sender,
false,
adjustedNotional,
swapCollateral,
activeLiquidity,
block.number,
underlierProtocol0BorrowIndex,
underlierProtocol1BorrowIndex
);
// create a swap key by hashing together the user and their current swap number
bytes32 swapKey = keccak256(abi.encode(msg.sender, swapNumbers[msg.sender]));
swaps[swapKey] = swap;
// update the user's swap number
swapNumbers[msg.sender] = swapNumbers[msg.sender].add(1);
// update the total active liquidity
totalActiveLiquidity = totalActiveLiquidity.add(activeLiquidity);
// update the total swap collateral
totalSwapCollateral = totalSwapCollateral.add(swapCollateral);
// update the total supplementary collateral
totalSupplementaryCollateral = totalSupplementaryCollateral.add(supplementaryCollateral);
// update the total available liquidity
totalAvailableLiquidity = totalAvailableLiquidity.sub(activeLiquidity);
// update the total fees accrued
totalFees = totalFees.add(swapFee);
// the total amount to debit the user (swap collateral + fee + the supplementary collateral)
uint256 amountToDebit = swapCollateral.add(fee).add(supplementaryCollateral);
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fixed interest rate
fee = _calculateFee();
// transfer underlier from the user
IERC20(underlier).safeTransferFrom(
msg.sender,
address(this),
_convertToUnderlierDecimal(amountToDebit)
);
// emit an open swap event
emit OpenSwap(msg.sender, adjustedNotional, activeLiquidity, swapFee);
// return true on successful open swap
return true;
}
// ============ Closes an interest rate swap ============
function closeSwap(uint256 _swapNumber) external override returns (bool) {
// the key of the swap
bytes32 swapKey = keccak256(abi.encode(msg.sender, _swapNumber));
// assert that a swap exists for this user
require(swaps[swapKey].user == msg.sender, '11');
// assert that this swap has not already been closed
require(!swaps[swapKey].isClosed, '12');
// get the swap to be closed
Swap memory swap = swaps[swapKey];
// the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap
(uint256 userToPay, uint256 ammToPay) = _calculateInterestAccrued(swap);
// assert that the swap cannot be closed in the same block that it was opened
require(block.number > swap.openBlock, '13');
// the total payout for this swap
uint256 payout = userToPay > ammToPay ? userToPay.sub(ammToPay) : ammToPay.sub(userToPay);
// the supplementary collateral of this swap
uint256 supplementaryCollateral = swap.activeLiquidity;
// the active liquidity recovered upon closure of this swap
uint256 activeLiquidityRecovered;
// the amount to reward the user upon closing of the swap
uint256 redeemableFunds;
// the user won the swap
if (ammToPay > userToPay) {
// ensure the payout does not exceed the active liquidity for this swap
payout = Math.min(payout, swap.activeLiquidity);
// active liquidity recovered is the the total active liquidity reduced by the user's payout
activeLiquidityRecovered = swap.activeLiquidity.sub(payout);
// User can redeem all of swap collateral, all of supplementary collateral, and the payout
redeemableFunds = swap.swapCollateral.add(supplementaryCollateral).add(payout);
}
// the AMM won the swap
else if (ammToPay < userToPay) {
// ensure the payout does not exceed the swap collateral for this swap
payout = Math.min(payout, swap.swapCollateral);
// active liquidity recovered is the the total active liquidity increased by the amm's payout
activeLiquidityRecovered = swap.activeLiquidity.add(payout);
// user can redeem all of swap collateral, all of supplementary collateral, with the payout subtracted
redeemableFunds = swap.swapCollateral.add(supplementaryCollateral).sub(payout);
}
// neither party won the swap
else {
// active liquidity recovered is the the initial active liquidity for the trade
activeLiquidityRecovered = swap.activeLiquidity;
// user can redeem all of swap collateral and all of supplementary collateral
redeemableFunds = swap.swapCollateral.add(supplementaryCollateral);
}
// update the total active liquidity
totalActiveLiquidity = totalActiveLiquidity.sub(swap.activeLiquidity);
// update the total swap collateral
totalSwapCollateral = totalSwapCollateral.sub(swap.swapCollateral);
// update the total supplementary collateral
totalSupplementaryCollateral = totalSupplementaryCollateral.sub(supplementaryCollateral);
// update the total available liquidity
totalAvailableLiquidity = totalAvailableLiquidity.add(activeLiquidityRecovered);
// close the swap
swaps[swapKey].isClosed = true;
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fee
fee = _calculateFee();
// transfer redeemable funds to the user
IERC20(underlier).safeTransfer(
msg.sender,
_convertToUnderlierDecimal(redeemableFunds)
);
// emit a close swap event
emit CloseSwap(msg.sender, swap.notional, userToPay, ammToPay);
return true;
}
// ============ Deposit liquidity into the pool ============
function depositLiquidity(uint256 _liquidityAmount) external override returns (bool) {
// adjust liquidity amount to standard decimals
uint256 adjustedLiquidityAmount = _convertToStandardDecimal(_liquidityAmount);
// asert that liquidity amount must be greater than 0 and amount to less than the max deposit limit
require(adjustedLiquidityAmount > 0 && adjustedLiquidityAmount.add(totalActiveLiquidity).add(totalAvailableLiquidity) <= maxDepositLimit, '14');
// transfer the specified amount of underlier into the pool
IERC20(underlier).safeTransferFrom(msg.sender, address(this), _liquidityAmount);
// add to the total available liquidity in the pool
totalAvailableLiquidity = totalAvailableLiquidity.add(adjustedLiquidityAmount);
// update the most recent deposit block of the liquidity provider
liquidityProviderLastDeposit[msg.sender] = block.number;
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fee
fee = _calculateFee();
// mint LP tokens to the liiquidity provider
_mintLPTokens(msg.sender, adjustedLiquidityAmount);
// emit deposit liquidity event
emit DepositLiquidity(msg.sender, adjustedLiquidityAmount);
return true;
}
// ============ Withdraw liquidity from the pool ============
function withdrawLiquidity(uint256 _liquidityTokenAmount) external override returns (bool) {
// assert that withdrawal does not occur in the same block as a deposit
require(liquidityProviderLastDeposit[msg.sender] < block.number, '19');
// asert that liquidity amount must be greater than 0
require(_liquidityTokenAmount > 0, '14');
// transfer the liquidity tokens from sender to the pool
IERC20(address(this)).safeTransferFrom(msg.sender, address(this), _liquidityTokenAmount);
// determine the amount of underlying tokens that the liquidity tokens can be redeemed for
uint256 redeemableUnderlyingTokens = calculateLiquidityTokenValue(_liquidityTokenAmount);
// assert that there is enough available liquidity to safely withdraw this amount
require(totalAvailableLiquidity >= redeemableUnderlyingTokens, '10');
// the fees that this withdraw will yield (total fees accrued * withdraw amount / total liquidity provided)
uint256 feeShare = totalFees.mul(redeemableUnderlyingTokens).div(totalActiveLiquidity.add(totalAvailableLiquidity));
// update the total fees remaining in the pool
totalFees = totalFees.sub(feeShare);
// remove the withdrawn amount from the total available liquidity in the pool
totalAvailableLiquidity = totalAvailableLiquidity.sub(redeemableUnderlyingTokens);
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fee
fee = _calculateFee();
// mint LP tokens to the liiquidity provider
_burnLPTokens(msg.sender, _liquidityTokenAmount);
// emit withdraw liquidity event
emit WithdrawLiquidity(msg.sender, redeemableUnderlyingTokens, feeShare);
return true;
}
// ============ Liquidate a swap that has expired ============
function liquidate(address _user, uint256 _swapNumber) external override returns (bool) {
// the key of the swap
bytes32 swapKey = keccak256(abi.encode(_user, _swapNumber));
// assert that a swap exists for this user
require(swaps[swapKey].user == _user, '11');
// get the swap to be liquidated
Swap memory swap = swaps[swapKey];
// assert that the swap has not already been closed
require(!swap.isClosed, '12');
// the expiration block of the swap
uint256 expirationBlock = swap.openBlock.add(durationInDays.mul(BLOCKS_PER_DAY));
// assert that the swap has eclipsed the expiration block
require(block.number >= expirationBlock, '17');
// transfer trade active liquidity from the liquidator
IERC20(underlier).safeTransferFrom(
msg.sender,
address(this),
_convertToUnderlierDecimal(swap.activeLiquidity)
);
// the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap
(uint256 userToPay, uint256 ammToPay) =_calculateInterestAccrued(swap);
// the total payout for this swap
uint256 payout = userToPay > ammToPay ? userToPay.sub(ammToPay) : ammToPay.sub(userToPay);
// the supplementary collateral of this swap
uint256 supplementaryCollateral = swap.activeLiquidity;
// the active liquidity recovered upon liquidation of this swap
uint256 activeLiquidityRecovered;
// the amount to reward the liquidator upon liquidation of the swap
uint256 liquidatorReward;
// the user won the swap
if (ammToPay > userToPay) {
// ensure the payout does not exceed the active liquidity for this swap
payout = Math.min(payout, swap.activeLiquidity);
// active liquidity recovered is the the total active liquidity increased by the user's unclaimed payout
activeLiquidityRecovered = swap.activeLiquidity.add(payout);
// liquidator is rewarded the supplementary collateral and the difference between the swap collateral and the payout
liquidatorReward = supplementaryCollateral.add(swap.swapCollateral).sub(payout);
}
// the AMM won the swap
else if (ammToPay < userToPay) {
// ensure the payout does not exceed the swap collateral for this swap
payout = Math.min(payout, swap.swapCollateral);
// active liquidity recovered is the the total active liquidity increased by the entire swap collateral
activeLiquidityRecovered = swap.activeLiquidity.add(swap.swapCollateral);
// liquidator is rewarded all of the supplementary collateral
liquidatorReward = supplementaryCollateral;
}
// neither party won the swap
else {
// active liquidity recovered is the the total active liquidity for this swap
activeLiquidityRecovered = swap.activeLiquidity;
// liquidator is rewarded all of the supplementary collateral and the swap collateral
liquidatorReward = supplementaryCollateral.add(swap.swapCollateral);
}
// update the total active liquidity
totalActiveLiquidity = totalActiveLiquidity.sub(swap.activeLiquidity);
// update the total swap collateral
totalSwapCollateral = totalSwapCollateral.sub(swap.swapCollateral);
// update the total supplementary collateral
totalSupplementaryCollateral = totalSupplementaryCollateral.sub(supplementaryCollateral);
// update the total available liquidity
totalAvailableLiquidity = totalAvailableLiquidity.add(activeLiquidityRecovered);
// close the swap
swaps[swapKey].isClosed = true;
// calculate the new pool utilization
utilization = _calculateUtilization();
// calculate the new fee
fee = _calculateFee();
// transfer liquidation reward to the liquidator
IERC20(underlier).safeTransfer(
msg.sender,
_convertToUnderlierDecimal(liquidatorReward)
);
// emit liquidate event
emit Liquidate(msg.sender, _user, _swapNumber, liquidatorReward);
return true;
}
// ============ External view for the interest accrued on a variable rate ============
function calculateVariableInterestAccrued(uint256 _notional, uint256 _protocol, uint256 _borrowIndex) external view override returns (uint256) {
return _calculateVariableInterestAccrued(_notional, _protocol, _borrowIndex);
}
// ============ Calculates the current variable rate for the underlier on a particular protocol ============
function calculateVariableRate(uint256 _protocol) external view returns (uint256) {
// the adapter to use given the particular protocol
address adapter = _protocol == protocol0 ? adapter0 : adapter1;
// use the current variable rate for the underlying token
uint256 variableRate = IAdapter(adapter).getBorrowRate(underlier);
return variableRate;
}
function changeMaxDepositLimit(uint256 _limit) external {
// assert that only governance can adjust the deposit limit
require(msg.sender == GOVERNANCE, '18');
// change the deposit limit
maxDepositLimit = _limit;
}
// ============ Calculates the current approximate value of liquidity tokens denoted in the underlying token ============
function calculateLiquidityTokenValue(uint256 liquidityTokenAmount) public view returns (uint256 redeemableUnderlyingTokens) {
// get the total underlying token balance in this pool with supplementary and swap collateral amounts excluded
uint256 adjustedUnderlyingTokenBalance = _convertToStandardDecimal(IERC20(underlier).balanceOf(address(this)))
.sub(totalSwapCollateral)
.sub(totalSupplementaryCollateral);
// the total supply of LP tokens in circulation
uint256 _totalSupply = totalSupply();
// determine the amount of underlying tokens that the liquidity tokens can be redeemed for
redeemableUnderlyingTokens = liquidityTokenAmount.mul(adjustedUnderlyingTokenBalance).div(_totalSupply);
}
// ============ Calculates the max variable rate to pay ============
function calculateMaxVariableRate(address adapter) external view returns (uint256) {
return _calculateMaxVariableRate(adapter);
}
// ============ Internal methods ============
// ============ Mints LP tokens to users that deposit liquidity to the protocol ============
function _mintLPTokens(address to, uint256 underlyingTokenAmount) internal {
// the total supply of LP tokens in circulation
uint256 _totalSupply = totalSupply();
// determine the amount of LP tokens to mint
uint256 mintableLiquidity;
if (_totalSupply == 0) {
// initialize the supply of LP tokens
mintableLiquidity = underlyingTokenAmount;
}
else {
// get the total underlying token balance in this pool
uint256 underlyingTokenBalance = _convertToStandardDecimal(IERC20(underlier).balanceOf(address(this)));
// adjust the underlying token balance to standardize the decimals
// the supplementary collateral, swap collateral, and newly added liquidity amounts are excluded
uint256 adjustedUnderlyingTokenBalance = underlyingTokenBalance
.sub(totalSwapCollateral)
.sub(totalSupplementaryCollateral)
.sub(underlyingTokenAmount);
// mint a proportional amount of LP tokens
mintableLiquidity = underlyingTokenAmount.mul(_totalSupply).div(adjustedUnderlyingTokenBalance);
}
// assert that enough liquidity tokens are available to be minted
require(mintableLiquidity > 0, 'INSUFFICIENT_LIQUIDITY_MINTED');
// mint the tokens directly to the LP
_mint(to, mintableLiquidity);
// emit minting of LP token event
emit Mint(to, underlyingTokenAmount, mintableLiquidity);
}
// ============ Burns LP tokens and sends users the equivalent underlying tokens in return ============
function _burnLPTokens(address to, uint256 liquidityTokenAmount) internal {
// determine the amount of underlying tokens that the liquidity tokens can be redeemed for
uint256 redeemableUnderlyingTokens = calculateLiquidityTokenValue(liquidityTokenAmount);
// assert that enough underlying tokens are available to send to the redeemer
require(redeemableUnderlyingTokens > 0, 'INSUFFICIENT_LIQUIDITY_BURNED');
// burn the liquidity tokens
_burn(address(this), liquidityTokenAmount);
// transfer the underlying tokens
IERC20(underlier).safeTransfer(to, _convertToUnderlierDecimal(redeemableUnderlyingTokens));
// emit burning of LP token event
emit Mint(to, redeemableUnderlyingTokens, liquidityTokenAmount);
}
// ============ Calculate the current pool fee ============
function _calculateFee() internal view returns (uint256) {
// the new fee based on updated pool utilization
uint256 newFee;
// the fee offered before the utilization inflection is hit
// (utilization * rate sensitivity) + rate limit
int256 preInflectionLeg = int256(utilization.mul(rateSensitivity).div(TEN_EXP_18).add(rateLimit));
// pool utilization is below the inflection
if (utilization < utilizationInflection) {
// assert that the leg is positive before converting to uint256
require(preInflectionLeg > 0);
newFee = uint256(preInflectionLeg);
}
// pool utilization is at or above the inflection
else {
// The additional change in the rate after the utilization inflection is hit
// rate multiplier * (utilization - utilization inflection)
int256 postInflectionLeg = int256(rateMultiplier.mul(utilization.sub(utilizationInflection)).div(TEN_EXP_18));
// assert that the addition of the legs is positive before converting to uint256
require(preInflectionLeg + postInflectionLeg > 0);
newFee = uint256(preInflectionLeg + postInflectionLeg);
}
// adjust the fee value as a percentage
return newFee.div(100);
}
// ============ Calculates the pool utilization ============
function _calculateUtilization() internal view returns (uint256) {
// get the total liquidity of this pool
uint256 totalPoolLiquidity = totalActiveLiquidity.add(totalAvailableLiquidity);
// pool utilization is the total active liquidity / total pool liquidity
uint256 newUtilization = totalActiveLiquidity.mul(TEN_EXP_18).div(totalPoolLiquidity);
// adjust utilization to be an integer between 0 and 100
uint256 adjustedUtilization = newUtilization * 100;
return adjustedUtilization;
}
// ============ Calculates the swap collateral and active liquidity needed for a given notional ============
function _calculateSwapCollateralAndActiveLiquidity(uint256 _notional) internal view returns (uint256, uint256) {
// The maximum rate the user will pay on a swap
uint256 userMaxRateToPay = direction == 0 ? _calculateMaxVariableRate(adapter0) : _calculateMaxVariableRate(adapter1);
// the maximum rate the AMM will pay on a swap
uint256 ammMaxRateToPay = direction == 1 ? _calculateMaxVariableRate(adapter0) : _calculateMaxVariableRate(adapter1);
// notional * maximum rate to pay * (swap duration in days / days per year)
uint256 swapCollateral = _calculateMaxAmountToPay(_notional, userMaxRateToPay);
uint256 activeLiquidity = _calculateMaxAmountToPay(_notional, ammMaxRateToPay);
return (swapCollateral, activeLiquidity);
}
// ============ Calculates the maximum amount to pay over a specific time window with a given notional and rate ============
function _calculateMaxAmountToPay(uint256 _notional, uint256 _rate) internal view returns (uint256) {
// the period by which to adjust the rate
uint256 period = DAYS_PER_YEAR.div(durationInDays);
// notional * maximum rate to pay / (days per year / swap duration in days)
return _notional.mul(_rate).div(TEN_EXP_18).div(period);
}
// ============ Calculates the maximum variable rate ============
function _calculateMaxVariableRate(address _adapter) internal view returns (uint256) {
// use the current variable rate for the underlying token
uint256 variableRate = IAdapter(_adapter).getBorrowRate(underlier);
// calculate a variable rate buffer
uint256 maxBuffer = MAX_TO_PAY_BUFFER_NUMERATOR.mul(TEN_EXP_18).div(MAX_TO_PAY_BUFFER_DENOMINATOR);
// add the buffer to the current variable rate
return variableRate.add(maxBuffer);
}
// ============ Calculates the interest accrued for both parties on a swap ============
function _calculateInterestAccrued(Swap memory _swap) internal view returns (uint256, uint256) {
// the amounts that the user and the AMM will pay on this swap, depending on the direction of the swap
uint256 userToPay;
uint256 ammToPay;
// the fixed interest accrued on this swap
uint256 protocol0VariableInterestAccrued = _calculateVariableInterestAccrued(_swap.notional, protocol0, _swap.underlierProtocol0BorrowIndex);
// the variable interest accrued on this swap
uint256 protocol1VariableInterestAccrued = _calculateVariableInterestAccrued(_swap.notional, protocol1, _swap.underlierProtocol1BorrowIndex);
// user went long on the variable rate
if (direction == 0) {
userToPay = protocol0VariableInterestAccrued;
ammToPay = protocol1VariableInterestAccrued;
}
// user went short on the variable rate
else {
userToPay = protocol1VariableInterestAccrued;
ammToPay = protocol0VariableInterestAccrued;
}
return (userToPay, ammToPay);
}
// ============ Calculates the interest accrued on a variable rate ============
function _calculateVariableInterestAccrued(uint256 _notional, uint256 _protocol, uint256 _openSwapBorrowIndex) internal view returns (uint256) {
// the adapter to use based on the protocol
address adapter = _protocol == protocol0 ? adapter0 : adapter1;
// get the current borrow index of the underlying asset
uint256 currentBorrowIndex = IAdapter(adapter).getBorrowIndex(underlier);
// The ratio between the current borrow index and the borrow index at time of open swap
uint256 indexRatio = currentBorrowIndex.mul(TEN_EXP_18).div(_openSwapBorrowIndex);
// notional * (current borrow index / borrow index when swap was opened) - notional
return _notional.mul(indexRatio).div(TEN_EXP_18).sub(_notional);
}
// ============ Converts an amount to have the contract standard numfalse,ber of decimals ============
function _convertToStandardDecimal(uint256 _amount) internal view returns (uint256) {
// set adjustment direction to false to convert to standard pool decimals
return _convertToDecimal(_amount, true);
}
// ============ Converts an amount to have the underlying token's number of decimals ============
function _convertToUnderlierDecimal(uint256 _amount) internal view returns (uint256) {
// set adjustment direction to true to convert to underlier decimals
return _convertToDecimal(_amount, false);
}
// ============ Converts an amount to have a particular number of decimals ============
function _convertToDecimal(uint256 _amount, bool _adjustmentDirection) internal view returns (uint256) {
// the amount after it has been converted to have the underlier number of decimals
uint256 convertedAmount;
// the underlying token has less decimal places
if (underlierDecimals < STANDARD_DECIMALS) {
convertedAmount = _adjustmentDirection ? _amount.mul(10 ** decimalDifference) : _amount.div(10 ** decimalDifference);
}
// there is no difference in the decimal places
else {
convertedAmount = _amount;
}
return convertedAmount;
}
// ============ Calculates the difference between the underlying decimals and the standard decimals ============
function _calculatedDecimalDifference(uint256 _x_decimal, uint256 _y_decimal) internal pure returns (uint256) {
// the difference in decimals
uint256 difference;
// the second decimal is greater
if (_x_decimal < _y_decimal) {
difference = _y_decimal.sub(_x_decimal);
}
return difference;
}
}
// 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: Unlicensed
pragma solidity 0.7.6;
interface IPool {
function openSwap(uint256 _notional) external returns (bool);
function closeSwap(uint256 _swapNumber) external returns (bool);
function depositLiquidity(uint256 _liquidityAmount) external returns (bool);
function withdrawLiquidity(uint256 _liquidityAmount) external returns (bool);
function liquidate(address _user, uint256 _swapNumber) external returns (bool);
function calculateVariableInterestAccrued(uint256 _notional, uint256 _protocol, uint256 _borrowIndex) external view returns (uint256);
}
// SPDX-License-Identifier: Unlicensed
pragma solidity >=0.6.12;
interface IAdapter {
function getBorrowIndex(address underlier) external view returns (uint256);
function getBorrowRate(address underlier) external view returns (uint256);
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
interface IGreenwoodERC20 {
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.7.6;
// ============ Contract information ============
/**
* @title Greenwood LP token
* @notice An LP token for Greenwood Basis Swaps
* @author Greenwood Labs
*/
// ============ Imports ============
import '../interfaces/IGreenwoodERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
contract GreenwoodERC20 is IGreenwoodERC20 {
// ============ Import usage ============
using SafeMath for uint256;
// ============ Immutable storage ============
string public constant override name = 'Greenwood';
string public constant override symbol = 'GRN';
uint256 public constant override decimals = 18;
// ============ Mutable storage ============
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
// ============ Events ============
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
// ============ Constructor ============
constructor() {}
// ============ External methods ============
// ============ Returns the amount of tokens in existence ============
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
// ============ Returns the amount of tokens owned by `account` ============
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
// ============ Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` ============
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
// ============ Sets `amount` as the allowance of `spender` over the caller's tokens ============
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
// ============ Moves `amount` tokens from the caller's account to `recipient` ============
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
// ============ Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism ============
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds allowance'));
return true;
}
// ============ Internal methods ============
// ============ Creates `amount` tokens and assigns them to `account`, increasing the total supply ============
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'GreenwoodERC20: mint to the zero address');
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
// ============ Destroys `amount` tokens from `account`, reducing the total supply ============
function _burn(address account, uint256 amount) internal {
require(account != address(0), 'GreenwoodERC20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'GreenwoodERC20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
// ============ Sets `amount` as the allowance of `spender` over the tokens of the `owner` ============
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), 'GreenwoodERC20: approve from the zero address');
require(spender != address(0), 'GreenwoodERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// ============ Moves tokens `amount` from `sender` to `recipient` ============
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), 'GreenwoodERC20: transfer from the zero address');
require(recipient != address(0), 'GreenwoodERC20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'GreenwoodERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
| toggle the value of isPaused | function togglePause() external onlyGovernance() returns (bool){
isPaused = !isPaused;
return true;
}
| 1,627,784 |
./partial_match/1/0xAB42127980a3bff124E6465e097a5fC97228827e/sources/src/contracts/core/DataLayrServiceManager.sol | Used by DataLayr governance to adjust the address of the `feeSetter`, which can adjust the value of `feePerBytePerTime`. | function setFeeSetter(address _feeSetter)
external
onlyOwner
{
_setFeeSetter(_feeSetter);
}
| 9,359,615 |
pragma solidity ^0.4.18;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
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 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// 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 CryptoPepeMarketToken is ERC721 {
// Modified CryptoCelebs contract
// Note: "Item" refers to a SocialMedia asset.
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new item comes into existence.
event Birth(uint256 tokenId, string name, address owner);
/// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner);
/// @dev Transfer event as defined in current draft of ERC721.
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoSocialMedia"; // solhint-disable-line
string public constant SYMBOL = "CryptoPepeMarketToken"; // solhint-disable-line
uint256 private startingPrice = 0.001 ether;
uint256 private constant PROMO_CREATION_LIMIT = 5000;
uint256 private firstStepLimit = 0.053613 ether;
uint256 private secondStepLimit = 0.564957 ether;
mapping (uint256 => TopOwner) private topOwner;
mapping (uint256 => address) public lastBuyer;
/*** STORAGE ***/
/// @dev A mapping from item IDs to the address that owns them. All items have
/// some valid owner address.
mapping (uint256 => address) public itemIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
/// @dev A mapping from ItemIDs to an address that has been approved to call
/// transferFrom(). Each item can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public itemIndexToApproved;
// @dev A mapping from ItemIDs to the price of the token.
mapping (uint256 => uint256) private itemIndexToPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cooAddress;
struct TopOwner {
address addr;
uint256 price;
}
/*** DATATYPES ***/
struct Item {
string name;
bytes32 message;
address creatoraddress; // Creators get the dev fee for item sales.
}
Item[] private items;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// Access modifier for contract owner only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
/*** CONSTRUCTOR ***/
function CryptoPepeMarketToken() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
// Restored bag holders
_createItem("Feelsgood", 0x7d9450A4E85136f46BA3F519e20Fea52f5BEd063,359808729788989630,"",address(this));
_createItem("Ree",0x2C3756c4cB4Ff488F666a3856516ba981197f3f3,184801761494400960,"",address(this));
_createItem("TwoGender",0xb16948C62425ed389454186139cC94178D0eFbAF,359808729788989630,"",address(this));
_createItem("Gains",0xA69E065734f57B73F17b38436f8a6259cCD090Fd,359808729788989630,"",address(this));
_createItem("Trump",0xBcce2CE773bE0250bdDDD4487d927aCCd748414F,94916238056430340,"",address(this));
_createItem("Brain",0xBcce2CE773bE0250bdDDD4487d927aCCd748414F,94916238056430340,"",address(this));
_createItem("Illuminati",0xbd6A9D2C44b571F33Ee2192BD2d46aBA2866405a,94916238056430340,"",address(this));
_createItem("Hang",0x2C659bf56012deeEc69Aea6e87b6587664B99550,94916238056430340,"",address(this));
_createItem("Pepesaur",0x7d9450A4E85136f46BA3F519e20Fea52f5BEd063,184801761494400960,"",address(this));
_createItem("BlockChain",0x2C3756c4cB4Ff488F666a3856516ba981197f3f3,184801761494400960,"",address(this));
_createItem("Wanderer",0xBcce2CE773bE0250bdDDD4487d927aCCd748414F,184801761494400960,"",address(this));
_createItem("Link",0xBcce2CE773bE0250bdDDD4487d927aCCd748414F,184801761494400960,"",address(this));
// Set top owners.
topOwner[1] = TopOwner(0x7d9450A4E85136f46BA3F519e20Fea52f5BEd063,350000000000000000);
topOwner[2] = TopOwner(0xb16948C62425ed389454186139cC94178D0eFbAF, 350000000000000000);
topOwner[3] = TopOwner(0xA69E065734f57B73F17b38436f8a6259cCD090Fd, 350000000000000000);
lastBuyer[1] = ceoAddress;
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
itemIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
/// @dev Creates a new Item with the given name.
function createContractItem(string _name, bytes32 _message, address _creatoraddress) public onlyCOO {
_createItem(_name, address(this), startingPrice, _message, _creatoraddress);
}
/// @notice Returns all the relevant information about a specific item.
/// @param _tokenId The tokenId of the item of interest.
function getItem(uint256 _tokenId) public view returns (
string itemName,
uint256 sellingPrice,
address owner,
bytes32 itemMessage,
address creator
) {
Item storage item = items[_tokenId];
itemName = item.name;
itemMessage = item.message;
sellingPrice = itemIndexToPrice[_tokenId];
owner = itemIndexToOwner[_tokenId];
creator = item.creatoraddress;
}
function implementsERC721() public pure returns (bool) {
return true;
}
/// @dev Required for ERC-721 compliance.
function name() public pure returns (string) {
return NAME;
}
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = itemIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId, bytes32 _message) public payable {
address oldOwner = itemIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = itemIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
uint256 msgPrice = msg.value;
require(msgPrice >= sellingPrice);
// Onwer of the item gets 86%
uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 86), 100));
// Top 3 owners get 6% (2% each)
uint256 twoPercentFee = uint256(SafeMath.mul(SafeMath.div(sellingPrice, 100), 2));
topOwner[1].addr.transfer(twoPercentFee);
topOwner[2].addr.transfer(twoPercentFee);
topOwner[3].addr.transfer(twoPercentFee);
uint256 fourPercentFee = uint256(SafeMath.mul(SafeMath.div(sellingPrice, 100), 4));
// Transfer 4% to the last buyer
lastBuyer[1].transfer(fourPercentFee);
// Transfer 4% to the item creator. (Don't transfer if creator is the contract owner)
if(items[_tokenId].creatoraddress != address(this)){
items[_tokenId].creatoraddress.transfer(fourPercentFee);
}
// Update prices
if (sellingPrice < firstStepLimit) {
// first stage
itemIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 86);
} else if (sellingPrice < secondStepLimit) {
// second stage
itemIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 86);
} else {
// third stage
itemIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 86);
}
_transfer(oldOwner, newOwner, _tokenId);
// ## Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment);
}
// Update the message of the item
items[_tokenId].message = _message;
TokenSold(_tokenId, sellingPrice, itemIndexToPrice[_tokenId], oldOwner, newOwner);
// Set last buyer
lastBuyer[1] = msg.sender;
// Set next top owner (If applicable)
if(sellingPrice > topOwner[3].price){
for(uint8 i = 3; i >= 1; i--){
if(sellingPrice > topOwner[i].price){
if(i <= 2){ topOwner[3] = topOwner[2]; }
if(i <= 1){ topOwner[2] = topOwner[1]; }
topOwner[i] = TopOwner(msg.sender, sellingPrice);
break;
}
}
}
// refund any excess eth to buyer
uint256 excess = SafeMath.sub(msg.value, sellingPrice);
msg.sender.transfer(excess);
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return itemIndexToPrice[_tokenId];
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current COO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns (string) {
return SYMBOL;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = itemIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
/// @param _owner The owner whose social media tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Items array looking for items belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalItems = totalSupply();
uint256 resultIndex = 0;
uint256 itemId;
for (itemId = 0; itemId <= totalItems; itemId++) {
if (itemIndexToOwner[itemId] == _owner) {
result[resultIndex] = itemId;
resultIndex++;
}
}
return result;
}
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return items.length;
}
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
/// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return itemIndexToApproved[_tokenId] == _to;
}
/// For creating Item
function _createItem(string _name, address _owner, uint256 _price, bytes32 _message, address _creatoraddress) private {
Item memory _item = Item({
name: _name,
message: _message,
creatoraddress: _creatoraddress
});
uint256 newItemId = items.push(_item) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newItemId == uint256(uint32(newItemId)));
Birth(newItemId, _name, _owner);
itemIndexToPrice[newItemId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newItemId);
}
/// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == itemIndexToOwner[_tokenId];
}
/// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
/// @dev Assigns ownership of a specific Item to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of items is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
itemIndexToOwner[_tokenId] = _to;
// When creating new items _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete itemIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
}
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;
}
} | Returns all the relevant information about a specific item. _tokenId The tokenId of the item of interest. | function getItem(uint256 _tokenId) public view returns (
string itemName,
uint256 sellingPrice,
address owner,
bytes32 itemMessage,
address creator
) {
Item storage item = items[_tokenId];
itemName = item.name;
itemMessage = item.message;
sellingPrice = itemIndexToPrice[_tokenId];
owner = itemIndexToOwner[_tokenId];
creator = item.creatoraddress;
}
| 10,703,087 |
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title Ownable
* @dev Ownable contract with two-step ownership transfer. The new owner should accept ownership to prevent
* transferring to wrong address.
*/
contract SafeTransferOwnable is Ownable {
address public newOwner;
event OwnershipProposed(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Throws if called by any account other than the newOwner.
*/
modifier onlyProposedOwner() {
require(msg.sender == newOwner);
_;
}
/**
* @dev Allows the current owner to propose control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
emit OwnershipProposed(owner, newOwner);
}
/**
* @dev Allows the proposed newOwner to accept control of the contract.
*/
function acceptOwnership() public onlyProposedOwner {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
} | Allows the current owner to propose control of the contract to a newOwner. _newOwner The address to transfer ownership to./ | function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
emit OwnershipProposed(owner, newOwner);
}
| 12,806,062 |
pragma solidity ^0.5.0;
import "./libs/ListAsRingLib.sol";
import "./libs/EntityLib.sol";
import "./libs/AddressIndexLib.sol";
import "./libs/StringIndexLib.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
contract HallOfFame is Ownable {
using EntityLib for EntityLib.Entities;
using ListAsRingLib for ListAsRingLib.ListData;
using AddressIndexLib for AddressIndexLib.Indexes;
using StringIndexLib for StringIndexLib.Indexes;
EntityLib.Entities private donators;
StringIndexLib.Indexes private donatorIndexes;
EntityLib.Entities private admins;
AddressIndexLib.Indexes private adminIndexes;
EntityLib.Entities private groups;
StringIndexLib.Indexes private groupIndexes;
mapping (uint => ListAsRingLib.ListData) private groupDonators;
/**
* @dev Check if a sender is admin
*/
modifier onlyAdmin() {
uint id = adminIndexes.getId(msg.sender);
require(id > 0, "You are not admin");
_;
}
/**
* @dev Check if input array has valid size
*/
modifier validArraySize(uint[] memory _ids, uint _size) {
require(_ids.length < _size, "array can't be that big");
_;
}
/**
* @dev Event for adding a donator.
* @param actor Who added donator (Indexed).
* @param id donator id (Indexed).
* @param externalId donator unique code.
*/
event DonatorAdded(address indexed actor, uint indexed id, string externalId);
/**
* @dev Event for editing donator.
* @param actor Who added donator (Indexed).
* @param id donator id (Indexed).
*/
event DonatorUpdated(address indexed actor, uint indexed id);
/**
* @dev Event for donator deleting.
* @param actor Who deleted donator (Indexed).
* @param id donator id (Indexed).
*/
event DonatorDeleted(address indexed actor, uint indexed id);
/**
* @dev Event for adding a admin.
* @param actor Who added admin (Indexed).
* @param id admin id (Indexed).
* @param admin admin address.
*/
event AdminAdded(address indexed actor, uint indexed id, address admin);
/**
* @dev Event for editing admin.
* @param actor Who added admin (Indexed).
* @param id admin id (Indexed).
*/
event AdminUpdated(address indexed actor, uint indexed id);
/**
* @dev Event for admin deleting.
* @param actor Who deleted admin (Indexed).
* @param id admin id (Indexed).
*/
event AdminDeleted(address indexed actor, uint indexed id);
/**
* @dev Event for adding a group.
* @param actor Who added group (Indexed).
* @param id group id (Indexed).
* @param groupCode group unique code.
*/
event GroupAdded(address indexed actor, uint indexed id, string groupCode);
/**
* @dev Event for editing group.
* @param actor Who added group (Indexed).
* @param id group id (Indexed).
*/
event GroupUpdated(address indexed actor, uint indexed id);
/**
* @dev Event for group deleting.
* @param actor Who deleted group (Indexed).
* @param id group id (Indexed).
*/
event GroupDeleted(address indexed actor, uint indexed id);
/**
* @dev Event for adding donator to groups.
* @param actor actor (Indexed).
* @param donatorId donator id (Indexed).
* @param groupIds group ids.
*/
event DonatorAddedToGroups(address indexed actor, uint indexed donatorId, uint[] groupIds);
/**
* @dev Event for removed donator from groups.
* @param actor actor (Indexed).
* @param donatorId donator id (Indexed).
* @param groupIds group ids.
*/
event DonatorRemovedFromGroups(address indexed actor, uint indexed donatorId, uint[] groupIds);
/**
* @dev Event for moving donator in a group.
* @param actor actor (Indexed).
* @param groupId group id (Indexed)
* @param donatorId donator id (Indexed).
* @param to donator new position after this id
*/
event DonatorMovedInGroup(address indexed actor, uint groupId, uint indexed donatorId, uint to);
/**
* @dev Link donator to groups.
* @param _donatorId donator ids.
* @param _removeIds group ids.
* @param _addIds group ids.
* //revert
*/
function linkToGroups(
uint _donatorId,
uint[] memory _removeIds,
uint[] memory _addIds
)
public
validArraySize(_addIds, 50)
validArraySize(_removeIds, 50)
{
uint removeLen = _removeIds.length;
uint addLen = _addIds.length;
for (uint i = 0; i < removeLen; i++) {
require(groups.list.exists(_removeIds[i]), "Can't unassign from unexisting group");
groupDonators[_removeIds[i]].remove(_donatorId);
}
if (removeLen > 0) {
emit DonatorRemovedFromGroups(msg.sender, _donatorId, _removeIds);
}
for (uint i = 0; i < addLen; i++) {
require(groups.list.exists(_addIds[i]), "Can't assign to unexisting group");
groupDonators[_addIds[i]].add(_donatorId);
}
if (addLen > 0) {
emit DonatorAddedToGroups(msg.sender, _donatorId, _addIds);
}
}
/**
* @dev Create a donator
* @param _data donator info.
* @param _externalId donator uniq code.
* @return uint
*/
function addDonator(
string memory _data,
string memory _externalId
)
public
onlyAdmin
returns(uint)
{
uint id = donators.add(_data);
donatorIndexes.add(_externalId, id);
emit DonatorAdded(msg.sender, id, _externalId);
return id;
}
/**
* @dev Create a donator and assign groups
* @param _data donator info.
* @param _externalId donator uniq code.
* @param _linkGroupIds group ids to link.
* @return uint
*/
function addDonatorAndLinkGroups(
string calldata _data,
string calldata _externalId,
uint[] calldata _linkGroupIds
)
external
onlyAdmin
returns(uint)
{
uint[] memory unlink = new uint[](0);
uint id = addDonator(_data, _externalId);
linkToGroups(id, unlink, _linkGroupIds);
return id;
}
/**
* @dev Update a donator
* @param _id donator id.
* @param _data donator info.
* @param _externalId donator uniq code.
* @return uint
*/
function updateDonator(
uint _id,
string memory _data,
string memory _externalId
)
public
onlyAdmin
returns(uint)
{
donators.update(_id, _data);
uint id = donatorIndexes.getId(_externalId);
if (id != _id) {
donatorIndexes.update(_externalId, _id);
}
emit DonatorUpdated(msg.sender, _id);
}
/**
* @dev Update donator and assign groups
* @param _data donator info.
* @param _externalId donator uniq code.
* @param _unlinkGroupIds group ids to unlink.
* @param _linkGroupIds group ids to link.
* @return uint
*/
function updateDonatorAndLinkGroups(
uint _id,
string calldata _data,
string calldata _externalId,
uint[] calldata _unlinkGroupIds,
uint[] calldata _linkGroupIds
)
external
onlyAdmin
returns(uint)
{
updateDonator(_id, _data, _externalId);
linkToGroups(_id, _unlinkGroupIds, _linkGroupIds);
return _id;
}
/**
* @dev Create a donator
* @param _id donator id.
* @return uint
*/
function removeDonator(
uint _id
)
external
onlyAdmin
returns(uint)
{
uint groupId = groups.list.getNextId(0);
uint[] memory removeGroupIds = new uint[](1);
uint[] memory emptyArray = new uint[](0);
while (groupId > 0) {
if (groupDonators[groupId].exists(_id)) {
removeGroupIds[0] = groupId;
linkToGroups(_id, removeGroupIds, emptyArray);
}
// require(!groupDonators[groupId].exists(_id), "Remove donator from all groups first");
groupId = groups.list.getNextId(groupId);
}
donators.remove(_id);
donatorIndexes.remove(donatorIndexes.getIndex(_id));
emit DonatorDeleted(msg.sender, _id);
}
/**
* @dev Get donator.
* @param _id donator id.
* @return uint, string
* //revert
*/
function getDonator(uint _id) external view returns (
uint id,
string memory data,
uint version,
string memory index
) {
(id, data, version) = donators.get(_id);
return (id, data, version, donatorIndexes.getIndex(_id));
}
/**
* @dev Get next donator.
* @param _id donator id.
* @return uint
* //revert
*/
function nextDonator(uint _id) external view returns (uint) {
return donators.list.getNextId(_id);
}
/**
* @dev Check if donators exist.
* @param _ids donator ids.
* @return bool[]
* //revert
*/
function areDonators(uint[] calldata _ids) external view returns (bool[] memory) {
return donators.list.statuses(_ids);
}
/**
* @dev Create a group
* @param _data group info.
* @param _code group uniq code.
* @return uint
*/
function addGroup(
string calldata _data,
string calldata _code
)
external
onlyAdmin
returns(uint)
{
uint id = groups.add(_data);
groupIndexes.add(_code, id);
emit GroupAdded(msg.sender, id, _code);
}
/**
* @dev Update a group
* @param _id group id.
* @param _data group info.
* @param _code group uniq code.
* @return uint
*/
function updateGroup(
uint _id,
string calldata _data,
string calldata _code
)
external
onlyAdmin
returns(uint)
{
groups.update(_id, _data);
uint id = groupIndexes.getId(_code);
if (id != _id) {
groupIndexes.update(_code, _id);
}
emit GroupUpdated(msg.sender, _id);
}
/**
* @dev Create a group
* @param _id group id.
* @return uint
*/
function removeGroup(
uint _id
)
external
onlyAdmin
returns(uint)
{
require(groupDonators[_id].count == 0, "Can't delete non empty group");
groups.remove(_id);
groupIndexes.remove(groupIndexes.getIndex(_id));
delete groupDonators[_id];
emit GroupDeleted(msg.sender, _id);
}
/**
* @dev Get group.
* @param _id group id.
* @return uint, string, string
* //revert
*/
function getGroup(uint _id) external view returns (
uint id,
string memory data,
uint version,
string memory index
) {
(id, data, version) = groups.get(_id);
return (id, data, version, groupIndexes.getIndex(_id));
}
/**
* @dev Get next group.
* @param _id group id.
* @return uint
* //revert
*/
function nextGroup(uint _id) external view returns (uint) {
return groups.list.getNextId(_id);
}
/**
* @dev Check if donators exist.
* @param _ids donator ids.
* @return bool[]
* //revert
*/
function areGroups(uint[] calldata _ids) external view returns (bool[] memory) {
return groups.list.statuses(_ids);
}
/**
* @dev Check if donators exist.
* @param _donatorId donator ids.
* @param _ids group ids.
* @return bool[]
* //revert
*/
function areInGroups(uint _donatorId, uint[] calldata _ids)
external
validArraySize(_ids, 50)
view
returns (bool[] memory)
{
uint len = _ids.length;
bool[] memory result = new bool[](len);
for (uint i = 0; i < len; i++) {
result[i] = groupDonators[_ids[i]].exists(_donatorId);
}
return result;
}
/**
* @dev Get next donator in group.
* @param _groupId group id.
* @param _donatorId donator id.
* @return uint
* //revert
*/
function nextGroupDonator(uint _groupId, uint _donatorId) external view returns (uint) {
return groupDonators[_groupId].getNextId(_donatorId);
}
/**
* @dev Get banch of donators in group. Order dependent
* @param _groupId group id.
* @param _fromId donator id.
* @param _count number of donators.
* @return uint
* //revert
*/
function getGroupDonators(uint _groupId, uint _fromId, uint _count) external view returns (uint[] memory) {
require(_count <= 1000, "List can't be more than 1000");
require(_count > 0, "Count can't be 0");
require(groups.list.exists(_groupId), "group must exist");
uint[] memory result = new uint[](_count);
uint id = groupDonators[_groupId].getNextId(_fromId);
uint i = 0;
while (id > 0 && i < _count) {
result[i] = id;
id = groupDonators[_groupId].getNextId(id);
i++;
}
return result;
}
/**
* @dev Move a donator to a new position
* @param _groupId group id.
* @param _id donator id.
* @param _to set after this position.
* @return uint
* //revert
*/
function moveDonator(uint _groupId, uint _id, uint _to)
external
returns (uint)
{
groupDonators[_groupId].move_after(_id, _to);
emit DonatorMovedInGroup(msg.sender, _groupId, _id, _to);
}
/**
* @dev Create an admin
* @param _data admin info.
* @param _address admin uniq code.
* @return uint
*/
function addAdmin(
string calldata _data,
address _address
)
external
onlyOwner
returns(uint)
{
uint id = admins.add(_data);
adminIndexes.add(_address, id);
emit AdminAdded(msg.sender, id, _address);
}
/**
* @dev Update an admin
* @param _id admin id.
* @param _data admin info.
* @param _address admin uniq code.
* @return uint
*/
function updateAdmin(
uint _id,
string calldata _data,
address _address
)
external
onlyOwner
returns(uint)
{
admins.update(_id, _data);
uint id = adminIndexes.getId(_address);
if (id != _id) {
adminIndexes.update(_address, _id);
}
emit AdminUpdated(msg.sender, _id);
}
/**
* @dev Create a admin
* @param _id admin id.
* @return uint
*/
function removeAdmin(
uint _id
)
external
onlyOwner
returns(uint)
{
admins.remove(_id);
adminIndexes.remove(adminIndexes.getIndex(_id));
emit AdminDeleted(msg.sender, _id);
}
/**
* @dev Get admin.
* @param _id admin id.
* @return uint, string, string
* //revert
*/
function getAdmin(uint _id) external view returns (
uint id,
string memory data,
uint version,
address index
) {
(id, data, version) = admins.get(_id);
return (id, data, version, adminIndexes.getIndex(_id));
}
/**
* @dev Get next admin.
* @param _id admin id.
* @return uint
* //revert
*/
function nextAdmin(uint _id) external view returns (uint) {
return admins.list.getNextId(_id);
}
/**
* @dev Check if admins exist.
* @param _ids admin ids.
* @return bool[]
* //revert
*/
function areAdmins(uint[] calldata _ids) external view returns (bool[] memory) {
return admins.list.statuses(_ids);
}
}
| Get group. _id group id. return uint, string, string/ | function getGroup(uint _id) external view returns (
uint id,
string memory data,
uint version,
string memory index
) {
(id, data, version) = groups.get(_id);
return (id, data, version, groupIndexes.getIndex(_id));
}
| 12,636,180 |
./full_match/1/0x1bB602b7a2ef2aECBA8FE3Df4b501C4C567B697d/sources/lib/ERC721A/contracts/ERC721A.sol | Mints `quantity` tokens and transfers them to `to`. Requirements: - `to` cannot be the zero address. - `quantity` must be greater than 0. Emits a {Transfer} event for each mint./ Overflows are incredibly unrealistic. `balance` and `numberMinted` have a maximum limit of 264. `tokenId` has a maximum limit of 2256. Updates: - `balance += quantity`. - `numberMinted += quantity`. We can directly add to the `balance` and `numberMinted`. Updates: - `address` to the owner. - `startTimestamp` to the timestamp of minting. - `burned` to `false`. - `nextInitialized` to `quantity == 1`. Use assembly to loop and emit the `Transfer` event for gas savings. The duplicated `log4` removes an extra check and reduces stack juggling. The assembly, together with the surrounding Solidity code, have been delicately arranged to nudge the compiler into producing optimized opcodes. Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. Emit the `Transfer` event. The `iszero(eq(,))` check ensures that large values of `quantity` that overflows uint256 will make the loop run out of gas. The compiler will optimize the `iszero` away for performance. Emit the `Transfer` event. Similar to above. | function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] =
_packOwnershipData(to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0));
uint256 toMasked;
uint256 end = startTokenId + quantity;
assembly {
toMasked := and(to, _BITMASK_ADDRESS)
log4(
)
log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
}
}
if (toMasked == 0) revert MintToZeroAddress();
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
| 2,948,540 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
// Minimum funds for airline
uint256 constant minAirlineFunding = 10 ether;
// Track contract balance
uint256 private contractFundBalance = 0 ether;
// Used to check external authorized callers
mapping(address => uint8) private authorizedCallers;
// Airline Data and structures
struct Airline {
uint256 funds;
bool isRegistered;
}
mapping(address => address[]) airlineVotes;
address[] private registeredAirlines;
mapping(address => Airline) airlines;
// Flights Data and Structures
struct Flight {
bytes32 flight;
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
bytes32[] private flightKeys;
// Insurance Data and Structures
struct Insurance {
address customer;
uint256 funds;
bool isPaid;
}
// Flightkeys to insurances
mapping(bytes32 => bytes32[]) private flightInsurances;
// Insuree to balances
mapping(address => uint256) private insureeBalances;
// Unique insurance keys for recall
mapping(bytes32 => Insurance) private idToInsurance;
// Track insurance keys
bytes32[] private insuranceKeys;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
address _firstAirline
)
public
{
contractOwner = msg.sender;
firstAirline(_firstAirline);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireAuthorizedCaller()
{
require(authorizedCallers[msg.sender] == 1, "You are definitely not authorized for that.");
_;
}
modifier requireOwnerOrAuthorized()
{
require(msg.sender == contractOwner || authorizedCallers[msg.sender] == 1, "You are must be owner or authorized to do that");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
// @dev Authorize / deauthorize a caller to use contract
// @return null
function authorizeCaller( address _authorizedAddress ) external requireContractOwner {
authorizedCallers[_authorizedAddress] = 1;
}
function deauthorizeCaller( address _deauthorizedAddress ) external requireContractOwner {
authorizedCallers[_deauthorizedAddress] = 0;
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireOwnerOrAuthorized
{
require(mode != operational, "Status is already that");
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/* Airline Function1ality */
function firstAirline( address _airlineAddress ) internal requireIsOperational {
airlines[_airlineAddress] = Airline({funds: 0, isRegistered: true});
registeredAirlines.push(_airlineAddress);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address _airlineAddress
)
external
requireIsOperational
requireAuthorizedCaller
{
airlines[_airlineAddress] = Airline({funds: 0, isRegistered: true});
registeredAirlines.push(_airlineAddress);
}
function isAirline( address _airlineAddress ) external view returns (bool) {
return airlines[_airlineAddress].isRegistered;
}
function isFundedAirline ( address _airlineAddress ) public view requireIsOperational returns (bool) {
return airlines[_airlineAddress].funds >= minAirlineFunding;
}
function numRegisteredAirlines() public view requireIsOperational returns (uint256) {
return registeredAirlines.length;
}
function addAirlineVote(address _voter, address _airline) external requireIsOperational requireAuthorizedCaller {
airlineVotes[_airline].push(_voter);
}
function getAirlineVotes(address _airline) public view requireIsOperational returns (address[]) {
return airlineVotes[_airline];
}
function clearAirlineVotes(address _airline) external requireIsOperational requireAuthorizedCaller {
delete airlineVotes[_airline];
}
function fundAirline(address _airline, uint256 _funds) external payable requireAuthorizedCaller requireIsOperational {
airlines[_airline].funds = airlines[_airline].funds.add(_funds);
contractFundBalance = contractFundBalance.add(_funds);
}
/* FLIGHTS FUNCTIONALITY */
function registerFlight (address _airline, uint256 _time, bytes32 _flight) public requireAuthorizedCaller requireIsOperational {
bytes32 flightKey = getUniqueKey(_airline, _flight, _time);
flightKeys.push(flightKey);
flights[flightKey] = Flight({
flight: _flight,
isRegistered: true,
statusCode: 0,
updatedTimestamp: _time,
airline: _airline
});
}
function checkFlightExists (bytes32 _flightNumber) public view requireIsOperational returns (bool) {
for(uint16 f = 0; f < flightKeys.length; f++) {
if(flights[flightKeys[f]].flight == _flightNumber) {
return true;
}
}
return false;
}
function getFlightkeyByFlight (bytes32 _flightNumber) internal view requireIsOperational returns (bytes32) {
for(uint16 f = 0; f < flightKeys.length; f++) {
if(flights[flightKeys[f]].flight == _flightNumber) {
return flightKeys[f];
}
}
return bytes32(0);
}
function getFlightInformation (bytes32 _flightNumber)
public view
requireIsOperational
requireAuthorizedCaller
returns (address, bytes32, uint256, uint8, bytes32) {
bytes32 flightKey = getFlightkeyByFlight(_flightNumber);
Flight storage flight = flights[flightKey];
return (flight.airline, flight.flight, flight.updatedTimestamp, flight.statusCode, flightKey);
}
function getAllFlights () public view returns (bytes32[] memory) {
bytes32[] memory flightList = new bytes32[](flightKeys.length);
for (uint f = 0; f < flightKeys.length; f++) {
flightList[f] = flights[flightKeys[f]].flight;
}
return flightList;
}
/**
* @dev Buy insurance for a flight
*
*/
function buyFlightInsurance (bytes32 _flight, address _insuree) external payable requireIsOperational requireAuthorizedCaller {
Insurance memory newInsurance = Insurance({customer: _insuree, funds: msg.value, isPaid: false});
bytes32 flightKey = getFlightkeyByFlight(_flight);
bytes32 insuranceKey = getUniqueKey(_insuree, _flight, 0);
flightInsurances[flightKey].push(insuranceKey);
idToInsurance[insuranceKey] = newInsurance;
insuranceKeys.push(insuranceKey);
airlines[flights[flightKey].airline].funds.add(msg.value);
}
function getFlightInsuranceDetails (address _insuree, bytes32 _flight)
external view
requireIsOperational
returns (address, uint256, bool, bytes32) {
bytes32 insuranceKey = getUniqueKey(_insuree, _flight, 0);
Insurance storage insurance = idToInsurance[insuranceKey];
return (insurance.customer, insurance.funds, insurance.isPaid, insuranceKey);
}
function updateFlightStatus (uint8 _statusCode, bytes32 _flight) public requireIsOperational requireAuthorizedCaller {
bytes32 flightKey = getFlightkeyByFlight(_flight);
flights[flightKey].statusCode = _statusCode;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees (bytes32 _flight) public requireIsOperational requireAuthorizedCaller {
bytes32 flightKey = getFlightkeyByFlight(_flight);
address flightAirline = flights[flightKey].airline;
for(uint8 p=0; p < flightInsurances[flightKey].length; p++) {
Insurance storage insurance = idToInsurance[flightInsurances[flightKey][p]];
if (insurance.isPaid == false) {
uint256 credit = insurance.funds.mul(3).div(2);
insurance.isPaid == true;
insureeBalances[insurance.customer] = insureeBalances[insurance.customer].add(credit);
airlines[flightAirline].funds.sub(credit);
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function payInsuree (address _insuree) external requireIsOperational requireAuthorizedCaller returns (bool){
require(insureeBalances[_insuree] > 0, "This Insuree has no credit to withdraw.");
uint256 amount = insureeBalances[_insuree];
insureeBalances[_insuree] = 0;
address(_insuree).transfer(amount);
return true;
}
function getInsureeBalance (address _insuree) external view requireIsOperational requireAuthorizedCaller returns (uint256) {
return insureeBalances[_insuree];
}
function getUniqueKey
(
address _address,
bytes32 _flight,
uint256 _timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(_address, _flight, _timestamp));
}
function fund
(
)
public
payable
{
contractFundBalance.add(msg.value);
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
| FLIGHTS FUNCTIONALITY / | function registerFlight (address _airline, uint256 _time, bytes32 _flight) public requireAuthorizedCaller requireIsOperational {
bytes32 flightKey = getUniqueKey(_airline, _flight, _time);
flightKeys.push(flightKey);
flights[flightKey] = Flight({
flight: _flight,
isRegistered: true,
statusCode: 0,
updatedTimestamp: _time,
airline: _airline
});
}
| 12,922,177 |
./full_match/56/0xa603b15B6a9A76a688B65A3C63590B3098407760/sources/project_/contracts/diamond/libraries/LibPriceFacade.sol | Take the newer price | function getPriceFromCacheOrOracle(PriceFacadeStorage storage pfs, address token) internal view returns (uint64, uint40) {
LatestCallbackPrice memory cachePrice = pfs.callbackPrices[token];
(uint256 price, uint8 decimals,uint256 startedAt) = LibChainlinkPrice.getPriceFromChainlink(token);
uint40 updatedAt = cachePrice.timestamp >= startedAt ? cachePrice.timestamp : uint40(startedAt);
uint64 tokenPrice = cachePrice.timestamp >= startedAt ? cachePrice.price :
(decimals == 8 ? uint64(price) : uint64(price * 1e8 / (10 ** decimals)));
return (tokenPrice, updatedAt);
}
| 3,227,833 |
pragma solidity ^0.4.22;
//
// complied with 0.4.24+commit.e67f0147.Emscripten.clang
// 2018-09-07
// With Optimization enabled
//
// Contact [email protected]
//
// Play at: https://win1million.app
//
// Provably fair prize game where you can win $1m!
//
//
/**
* @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 Win1Million {
using SafeMath for uint256;
address owner;
address bankAddress;
address charityAddress;
bool gamePaused = false;
uint256 public housePercent = 2;
uint256 public charityPercent = 2;
uint256 public bankBalance;
uint256 public charityBalance;
uint256 public totalCharitySent = 0;
uint256 public minGamePlayAmount = 30000000000000000;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyBanker() {
require(bankAddress == msg.sender);
_;
}
modifier whenNotPaused() {
require(gamePaused == false);
_;
}
modifier correctAnswers(uint256 barId, string _answer1, string _answer2, string _answer3) {
require(compareStrings(gameBars[barId].answer1, _answer1));
require(compareStrings(gameBars[barId].answer2, _answer2));
require(compareStrings(gameBars[barId].answer3, _answer3));
_;
}
struct Bar {
uint256 Limit; // max amount of wei for this game
uint256 CurrentGameId;
string answer1;
string answer2;
string answer3;
}
struct Game {
uint256 BarId;
uint256 CurrentTotal;
mapping(address => uint256) PlayerBidMap;
address[] PlayerAddressList;
}
struct Winner {
address winner;
uint256 amount;
uint256 timestamp;
uint256 barId;
uint256 gameId;
}
Bar[] public gameBars;
Game[] public games;
Winner[] public winners;
mapping (address => uint256) playerPendingWithdrawals;
function getWinnersLen() public view returns(uint256) {
return winners.length;
}
// helper function so we can extrat list of all players at the end of each game...
function getGamesPlayers(uint256 gameId) public view returns(address[]){
return games[gameId].PlayerAddressList;
}
// and then enumerate through them and get their respective bids...
function getGamesPlayerBids(uint256 gameId, address playerAddress) public view returns(uint256){
return games[gameId].PlayerBidMap[playerAddress];
}
constructor() public {
owner = msg.sender;
bankAddress = owner;
// ensure we are above gameBars[0]
gameBars.push(Bar(0,0,"","",""));
// and for games[0]
address[] memory _addressList;
games.push(Game(0,0,_addressList));
}
event uintEvent(
uint256 eventUint
);
event gameComplete(
uint256 gameId
);
// Should only be used on estimate gas to check if the players bid
// will be acceptable and not be over the game limit...
// Should not be used to send Ether!
function playGameCheckBid(uint256 barId) public whenNotPaused payable {
uint256 gameAmt = (msg.value.div(100)).mul(100-(housePercent+charityPercent));
uint256 currentGameId = gameBars[barId].CurrentGameId;
if(gameBars[barId].CurrentGameId == 0) {
if(gameAmt > gameBars[barId].Limit) {
require(msg.value == minGamePlayAmount);
}
} else {
currentGameId = gameBars[barId].CurrentGameId;
require(games[currentGameId].BarId > 0); // Ensure it hasn't been closed already
if(games[currentGameId].CurrentTotal.add(gameAmt) > gameBars[barId].Limit) {
require(msg.value == minGamePlayAmount);
}
}
}
function playGame(uint256 barId,
string _answer1, string _answer2, string _answer3) public
whenNotPaused
correctAnswers(barId, _answer1, _answer2, _answer3)
payable {
require(msg.value >= minGamePlayAmount);
// check if a game is in play for this bar...
uint256 houseAmt = (msg.value.div(100)).mul(housePercent);
uint256 charityAmt = (msg.value.div(100)).mul(charityPercent);
uint256 gameAmt = (msg.value.div(100)).mul(100-(housePercent+charityPercent));
uint256 currentGameId = 0;
if(gameBars[barId].CurrentGameId == 0) {
if(gameAmt > gameBars[barId].Limit) {
require(msg.value == minGamePlayAmount);
}
address[] memory _addressList;
games.push(Game(barId, gameAmt, _addressList));
currentGameId = games.length-1;
gameBars[barId].CurrentGameId = currentGameId;
} else {
currentGameId = gameBars[barId].CurrentGameId;
require(games[currentGameId].BarId > 0); // Ensure it hasn't been closed already
if(games[currentGameId].CurrentTotal.add(gameAmt) > gameBars[barId].Limit) {
require(msg.value == minGamePlayAmount);
}
games[currentGameId].CurrentTotal = games[currentGameId].CurrentTotal.add(gameAmt);
}
if(games[currentGameId].PlayerBidMap[msg.sender] == 0) {
games[currentGameId].PlayerAddressList.push(msg.sender);
}
games[currentGameId].PlayerBidMap[msg.sender] = games[currentGameId].PlayerBidMap[msg.sender].add(gameAmt);
bankBalance+=houseAmt;
charityBalance+=charityAmt;
if(games[currentGameId].CurrentTotal >= gameBars[barId].Limit) {
emit gameComplete(gameBars[barId].CurrentGameId);
gameBars[barId].CurrentGameId = 0;
}
}
event completeGameResult(
uint256 indexed gameId,
uint256 indexed barId,
uint256 winningNumber,
string proof,
address winnersAddress,
uint256 winningAmount,
uint256 timestamp
);
// using NotaryProxy to generate random numbers with proofs stored in logs so they can be traced back
// publish list of players addresses - random number selection (With proof) and then how it was selected
function completeGame(uint256 gameId, uint256 _winningNumber, string _proof, address winner) public onlyOwner {
if(!winner.send(games[gameId].CurrentTotal)){
playerPendingWithdrawals[winner] = playerPendingWithdrawals[winner].add(games[gameId].CurrentTotal);
}
winners.push(Winner(
winner,
games[gameId].CurrentTotal,
now,
games[gameId].BarId,
gameId
));
emit completeGameResult(
gameId,
games[gameId].BarId,
_winningNumber,
_proof,
winner,
games[gameId].CurrentTotal,
now
);
// reset the bar state...
gameBars[games[gameId].BarId].CurrentGameId = 0;
}
event cancelGame(
uint256 indexed gameId,
uint256 indexed barId,
uint256 amountReturned,
address playerAddress
);
// players can cancel their participation in a game as long as it hasn't completed
// they lose their housePercent fee (And pay any gas of course)
function player_cancelGame(uint256 barId) public {
address _playerAddr = msg.sender;
uint256 _gameId = gameBars[barId].CurrentGameId;
uint256 _gamePlayerBalance = games[_gameId].PlayerBidMap[_playerAddr];
if(_gamePlayerBalance > 0){
// reset player bid amount
games[_gameId].PlayerBidMap[_playerAddr] = 1; // set to 1 wei to avoid duplicates
games[_gameId].CurrentTotal -= _gamePlayerBalance;
if(!_playerAddr.send(_gamePlayerBalance)){
// need to add to a retry list...
playerPendingWithdrawals[_playerAddr] = playerPendingWithdrawals[_playerAddr].add(_gamePlayerBalance);
}
}
emit cancelGame(
_gameId,
barId,
_gamePlayerBalance,
_playerAddr
);
}
function player_withdrawPendingTransactions() public
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
if (msg.sender.call.value(withdrawAmount)()) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
uint256 internal gameOpUint;
function gameOp() public returns(uint256) {
return gameOpUint;
}
function private_SetPause(bool _gamePaused) public onlyOwner {
gamePaused = _gamePaused;
}
function private_AddGameBar(uint256 _limit,
string _answer1, string _answer2, string _answer3) public onlyOwner {
gameBars.push(Bar(_limit, 0, _answer1, _answer2, _answer3));
emit uintEvent(gameBars.length);
}
function private_DelGameBar(uint256 barId) public onlyOwner {
if(gameBars[barId].CurrentGameId > 0){
delete games[gameBars[barId].CurrentGameId];
}
delete gameBars[barId];
}
// Used to rebalance a game when the ETH/USD rate changes
function private_UpdateGameBarLimit(uint256 barId, uint256 _limit) public onlyOwner {
gameBars[barId].Limit = _limit;
}
function private_setHousePercent(uint256 _housePercent) public onlyOwner {
housePercent = _housePercent;
}
function private_setMinGamePlayAmount(uint256 _minGamePlayAmount) onlyOwner {
minGamePlayAmount = _minGamePlayAmount;
}
function private_setBankAddress(address _bankAddress) public onlyOwner {
bankAddress = _bankAddress;
}
function private_withdrawBankFunds(address _whereTo) public onlyBanker {
if(_whereTo.send(bankBalance)) {
bankBalance = 0;
}
}
function private_withdrawBankFunds(address _whereTo, uint256 _amount) public onlyBanker {
if(_whereTo.send(_amount)){
bankBalance-=_amount;
}
}
function private_setCharityAddress(address _charityAddress) public onlyOwner {
charityAddress = _charityAddress;
}
event charityDonation(
address indexed charityAddress,
string charityName,
uint256 amountDonated,
uint256 timestamp
);
function private_sendCharityFunds(string _charityName) public onlyOwner {
if(charityAddress.send(charityBalance)) {
totalCharitySent += charityBalance;
emit charityDonation(
charityAddress,
_charityName,
charityBalance,
now
);
charityBalance = 0;
}
}
function private_sendCharityFunds(string _charityName, uint256 _amount) public onlyOwner {
require(_amount <= charityBalance);
if(charityAddress.send(_amount)) {
charityBalance -= _amount;
totalCharitySent += _amount;
emit charityDonation(
charityAddress,
_charityName,
_amount,
now
);
}
}
function compareStrings (string a, string b) internal pure returns (bool){
return keccak256(a) == keccak256(b);
}
} | and then enumerate through them and get their respective bids... | function getGamesPlayerBids(uint256 gameId, address playerAddress) public view returns(uint256){
return games[gameId].PlayerBidMap[playerAddress];
}
| 1,021,278 |
./partial_match/8453/0x3997B940aE1B6A1a767fFbf0cE91b82d0179Ad72/sources/Swamp.sol | handle the transfer of reward tokens via `transferFrom` to reduce the number of transactions required and ensure correctness of the reward amount | function notifyRewardAmount(address _rewardsToken, uint256 reward) external updateReward(address(0)) {
require(rewardData[_rewardsToken].notifier == msg.sender);
IERC20(_rewardsToken).safeTransferFrom(msg.sender, address(this), reward);
if (block.timestamp >= rewardData[_rewardsToken].periodFinish) {
rewardData[_rewardsToken].rewardRate = reward.div(rewardData[_rewardsToken].rewardsDuration);
uint256 remaining = rewardData[_rewardsToken].periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardData[_rewardsToken].rewardRate);
rewardData[_rewardsToken].rewardRate = reward.add(leftover).div(rewardData[_rewardsToken].rewardsDuration);
}
rewardData[_rewardsToken].lastUpdateTime = block.timestamp;
rewardData[_rewardsToken].periodFinish = block.timestamp.add(rewardData[_rewardsToken].rewardsDuration);
emit RewardAdded(reward);
}
| 16,814,103 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import './token/PoolsInterestBearingToken.sol';
import './token/Bridge.sol';
import './utils/MyPausableUpgradeable.sol';
import 'hardhat/console.sol';
import './interfaces/IBuyBackAndBurn.sol';
interface IBridge is IERC20 {
function burn(uint256 amount) external;
}
contract RewardPools is MyPausableUpgradeable, IPools {
using SafeERC20 for IERC20;
using SafeERC20 for IBridge;
/// contains information about a specific reward pool
struct RewardPool {
IERC20 rewardToken; // token the pool is created for
IERC20 interestBearingToken; // interest token that was created for this reward pool
uint256 minStakeAmount; // minimum amount that must be staked per account in BRIDGE token
uint256 maxStakeAmount; // maximum amount that can be staked per account in BRIDGE token
uint256 maxPoolSize; // max pool size in BRIDGE token
uint256 totalStakedAmount; // sum of all staked tokens
uint256 totalRewardAmount; // sum of all rewards ever assigned to this reward pool
uint256 accRewardPerShare; // the amount of unharvested rewards per share of the staking pool
uint256 lastRewardAmount; // sum of all rewards in this reward pool from last calculation
bool exists; // flag to show if this reward pool exists already
}
struct StakerInfo {
uint256 balance; // amount of staked tokens
uint256 stakeUpdateTime; // timestamp of last update
uint256 rewardDebt; // a negative reward amount that ensures that harvest cannot be called repeatedly to drain the rewards
address poolTokenAddress; // the token address of the underlying token of a specific reward pool
}
// bridge token that gets distributed by BridgeChef contract
IBridge private _bridgeToken;
/// Role for managing this contract
bytes32 public constant MANAGE_COLLECTED_FEES_ROLE = keccak256('MANAGE_COLLECTED_FEES_ROLE');
bytes32 public constant MANAGE_REWARD_POOLS_ROLE = keccak256('MANAGE_REWARD_POOLS_ROLE');
/// stores the reward pool information for each token that is supported by the bridge
/// tokenAddress to reward pool
mapping(address => RewardPool) public rewardPools;
/// Stores current stakings
/// there is a mapping from user wallet address to StakerInfo for each reward pool
/// tokenAddress (RewardPool) => Staker wallet address as identifier => StakerInfo
mapping(address => mapping(address => StakerInfo)) public stakes;
// Constant that facilitates handling of token fractions
uint256 private constant _DIV_PRECISION = 1e18;
/// Contract to receive rewards of pools without stake balance = 0 (for token burns)
IBuyBackAndBurn public buyBackAndBurnContract;
/// Default reward pool token withdrawal fee (in ppm: parts per million - 10,000ppm = 1%)
uint256 public defaultRewardPoolWithdrawalFee;
/// Individual reward pool withdrawal fees per underlying token (in ppm: parts per million - 10,000ppm = 1%)
/// tokenAdress => ppm
mapping(address => uint256) public rewardPoolWithdrawalFees;
string public constant upgradeSuccessfulDone = 'YES_YES_NO';
event RewardsAdded(address indexed tokenAddress, uint256 amount);
event StakeAdded(address indexed accountAddress, address indexed tokenAddress, uint256 amount);
event StakeWithdrawn(address indexed accountAddress, address indexed tokenAddress, uint256 amount);
event InterestBearingTokenTransferred(
address indexed senderAddress,
address indexed tokenAddress,
address indexed receiverAddress,
uint256 amount
);
event RewardsHarvested(address indexed staker, address indexed tokenAddress, uint256 amount);
/**
* @notice Initializer instead of constructor to have the contract upgradeable
* @dev can only be called once after deployment of the contract
*/
function initialize(IBridge bridgeToken, IBuyBackAndBurn _buyBackAndBurnContract) external initializer {
// call parent initializers
__MyPausableUpgradeable_init();
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
// initialize required state variables
_bridgeToken = bridgeToken;
buyBackAndBurnContract = _buyBackAndBurnContract;
defaultRewardPoolWithdrawalFee = 300000; // 30%
require(_bridgeToken.approve(address(buyBackAndBurnContract), type(uint256).max), 'RewardPools: approval failed');
}
/**
* @notice Sets the default reward pool withdrawal fee (to be paid in Bridge token)
*
* @dev can only be called by MANAGE_COLLECTED_FEES_ROLE
* @param fee the default bridging fee rate provided in ppm: parts per million - 10,000ppm = 1%
*/
function setDefaultRewardPoolWithdrawalFee(uint256 fee) external {
require(
hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()),
'RewardPools: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function'
);
defaultRewardPoolWithdrawalFee = fee;
}
/**
* @notice Sets an individual reward pool withdrawal fee for the given token
*
* @dev can only be called by MANAGE_COLLECTED_FEES_ROLE
* @param sourceNetworkTokenAddress the address of the underlying token contract
* @param fee the individual reward pool withdrawal fee rate provided in ppm: parts per million - 10,000ppm = 1%
*/
function setRewardPoolWithdrawalFee(address sourceNetworkTokenAddress, uint256 fee) external {
require(
hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()),
'RewardPools: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function'
);
require(rewardPools[sourceNetworkTokenAddress].exists, 'RewardPools: rewardPool does not exist');
rewardPoolWithdrawalFees[sourceNetworkTokenAddress] = fee;
}
/**
* @notice Sets the minimum stake amount for a specific token
*
* @dev can only be called by MANAGE_REWARD_POOLS_ROLE
* @param tokenAddress the address of the underlying token of the reward pool
* @param _minStakeAmount the minimum staking amount
*/
function setMinStakeAmount(address tokenAddress, uint256 _minStakeAmount) external {
require(
hasRole(MANAGE_REWARD_POOLS_ROLE, _msgSender()),
'RewardPools: must have MANAGE_REWARD_POOLS_ROLE role to execute this function'
);
require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist');
rewardPools[tokenAddress].minStakeAmount = _minStakeAmount;
}
/**
* @notice Sets the maximum stake amount for a specific token
*
* @dev can only be called by MANAGE_REWARD_POOLS_ROLE
* @param tokenAddress the address of the token
* @param _maxStakeAmount the maximum staking amount
*/
function setMaxStakeAmount(address tokenAddress, uint256 _maxStakeAmount) external {
require(
hasRole(MANAGE_REWARD_POOLS_ROLE, _msgSender()),
'RewardPools: must have MANAGE_REWARD_POOLS_ROLE role to execute this function'
);
require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist');
rewardPools[tokenAddress].maxStakeAmount = _maxStakeAmount;
}
/**
* @notice Sets the maximum staking pool size for a specific token
*
* @dev can only be called by MANAGE_REWARD_POOLS_ROLE
* @param tokenAddress the address of the token
* @param _maxPoolSize the maximum staking pool size
*/
function setMaxPoolSize(address tokenAddress, uint256 _maxPoolSize) external {
require(
hasRole(MANAGE_REWARD_POOLS_ROLE, _msgSender()),
'RewardPools: must have MANAGE_REWARD_POOLS_ROLE role to execute this function'
);
require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist');
rewardPools[tokenAddress].maxPoolSize = _maxPoolSize;
}
/**
* @notice Sets the address for the BuyBackAndBurn contract that receives rewards when pools have no stakers
*
* @dev can only be called by MANAGE_COLLECTED_FEES_ROLE
* @param _buyBackAndBurnContract the address of the BuyBackAndBurn contract
*/
function setBuyBackAndBurnContract(IBuyBackAndBurn _buyBackAndBurnContract) external {
require(
hasRole(MANAGE_COLLECTED_FEES_ROLE, _msgSender()),
'RewardPools: must have MANAGE_COLLECTED_FEES_ROLE role to execute this function'
);
require(
address(_buyBackAndBurnContract) != address(0),
'RewardPools: invalid buyBackAndBurnContract address provided'
);
buyBackAndBurnContract = _buyBackAndBurnContract;
require(_bridgeToken.approve(address(buyBackAndBurnContract), type(uint256).max), 'RewardPools: approval failed');
}
/**
* @notice Adds new funds (bridge tokens) to the staking pool
*
* @param tokenAddress the address of the underlying token of the reward pool
* @param amount the amount of bridge tokens that should be staked
* @dev emits event StakeAdded
*/
function stake(address tokenAddress, uint256 amount) external whenNotPaused nonReentrant {
// get reward pool for the given token
RewardPool storage pool = rewardPools[tokenAddress];
// get info about existing stakings in this token by this user (if any)
StakerInfo storage staker = stakes[tokenAddress][_msgSender()];
// check input parameters
require(amount > 0, 'RewardPools: staking amount cannot be 0');
require(rewardPools[tokenAddress].exists, 'RewardPools: rewardPool does not exist');
require(amount >= pool.minStakeAmount, 'RewardPools: staking amount too small');
require(
pool.maxStakeAmount == 0 || staker.balance + amount <= pool.maxStakeAmount,
'RewardPools: staking amount too high'
);
require(
pool.maxPoolSize == 0 || pool.totalStakedAmount + amount <= pool.maxPoolSize,
'RewardPools: max staking pool size exceeded'
);
// re-calculate the current rewards and accumulatedRewardsPerShare for this pool
updateRewards(tokenAddress);
// check if staking rewards are available for harvesting
if (staker.balance > 0) {
_harvest(tokenAddress, _msgSender());
}
// Update staker info
staker.stakeUpdateTime = block.timestamp;
staker.balance = staker.balance + amount;
staker.poolTokenAddress = tokenAddress;
// Assign reward debt in full amount of stake (to prevent that existing rewards can be harvested with the new stake share)
staker.rewardDebt = (staker.balance * pool.accRewardPerShare) / _DIV_PRECISION;
// Update total staked amount in reward pool info
rewardPools[tokenAddress].totalStakedAmount = pool.totalStakedAmount + amount;
// transfer to-be-staked funds from user to this smart contract
_bridgeToken.safeTransferFrom(_msgSender(), address(this), amount);
// Mint interest bearing token to user
PoolsInterestBearingToken(address(pool.interestBearingToken)).mint(_msgSender(), amount);
// funds successfully staked - emit new event
emit StakeAdded(_msgSender(), tokenAddress, amount);
}
/**
* @notice Withdraws staked funds (bridge tokens) from the reward pool after harvesting available rewards, if any
*
* @param tokenAddress the address of the underlying token of the reward pool
* @param amount the amount of bridge tokens that should be unstaked
* @dev emits event StakeAdded
*/
function unstake(address tokenAddress, uint256 amount) external whenNotPaused nonReentrant {
// get reward pool for the given token
RewardPool storage pool = rewardPools[tokenAddress];
// get info about existing stakings in this token by this user (if any)
StakerInfo storage staker = stakes[tokenAddress][_msgSender()];
// check input parameters
require(amount > 0, 'RewardPools: amount to be unstaked cannot be 0');
require(pool.exists, 'RewardPools: rewardPool does not exist');
require(staker.balance >= amount, 'RewardPools: amount exceeds available balance');
if (staker.balance - amount != 0) {
// check if remaining balance is above min stake amount
require(
staker.balance - amount >= pool.minStakeAmount,
'RewardPools: remaining balance below minimum stake amount'
);
}
// harvest available rewards before unstaking, if any
_harvest(tokenAddress, _msgSender());
// Update staker info
staker.stakeUpdateTime = block.timestamp;
staker.balance = staker.balance - amount;
staker.rewardDebt = (staker.balance * pool.accRewardPerShare) / _DIV_PRECISION;
// // determine the reward pool withdrawal fee (usually the default rate)
// // if a specific fee rate is stored for this reward pool then we use this rate instead
uint256 relativeFee = rewardPoolWithdrawalFees[tokenAddress] > 0
? rewardPoolWithdrawalFees[tokenAddress]
: defaultRewardPoolWithdrawalFee;
uint256 withdrFeeAmount = (amount * relativeFee) / 1000000;
// burn withdrawal fee
if (withdrFeeAmount > 0) {
IBridge(_bridgeToken).burn(withdrFeeAmount);
}
// Burn interest bearing token from user
PoolsInterestBearingToken(address(pool.interestBearingToken)).burn(_msgSender(), amount);
// transfer bridge tokens back to user
_bridgeToken.safeTransfer(_msgSender(), amount - withdrFeeAmount);
// funds successfully unstaked - emit new event
emit StakeWithdrawn(_msgSender(), tokenAddress, amount - withdrFeeAmount);
}
/**
* @notice Function that is called by the beforeTokenTransfer hook in the PoolsInterestBearingToken to ensure accurate accounting of stakes and rewards
*
* @dev can only be called by the PoolsInterestBearingToken contract itself
* @param tokenAddress the address of the underlying token
* @param amount the amount of tokens that was transfered
* @param from the sender of the PoolsInterestBearingToken transfer
* @param to the recipient of the PoolsInterestBearingToken transfer
* @dev emits event InterestBearingTokenTransferred
*/
function transferInterestBearingTokenHandler(
address tokenAddress,
uint256 amount,
address from,
address to
) external override whenNotPaused {
// check input parameters
require(
_msgSender() == address(rewardPools[tokenAddress].interestBearingToken),
'RewardPools: function can only be called by PoolsInterestBearingToken'
);
require(
tokenAddress != address(0) && from != address(0) && to != address(0),
'RewardPools: invalid address provided'
);
require(amount > 0, 'RewardPools: transfer amount cannot be 0');
// get reward pool for given token
RewardPool memory pool = rewardPools[tokenAddress];
// get staker info for both sender and receiver of the transfer
StakerInfo storage stakerSender = stakes[tokenAddress][from];
StakerInfo storage stakerReceiver = stakes[tokenAddress][to];
// calculate final staking balance of receiver after transfer
uint256 receiverFinalBalance = stakerReceiver.balance + amount;
// check reward pool requirements and staker balance
require(receiverFinalBalance >= pool.minStakeAmount, 'RewardPools: transfer amount too small');
require(
pool.maxStakeAmount == 0 || receiverFinalBalance <= pool.maxStakeAmount,
'RewardPools: transfer amount too high'
);
require(stakerSender.balance >= amount, 'RewardPools: insufficient balance for transfer');
// as preparation for the transfer, any unharvested rewards need to be harvested so that the sender receives his rewards before the transfer
// update the reward pool calculations (e.g. rewardPerShare)
updateRewards(tokenAddress);
// harvest all outstanding rewards for the sender of the token transfer
_harvest(tokenAddress, from);
if (stakerReceiver.balance > 0) {
_harvest(tokenAddress, to);
}
// update the time stamps in the staker records
stakerSender.stakeUpdateTime = block.timestamp;
stakerReceiver.stakeUpdateTime = block.timestamp;
// update balances in staker info
stakerSender.balance = stakerSender.balance - amount;
stakerReceiver.balance = receiverFinalBalance;
// calculate the new reward debt for both sender and receiver
stakerSender.rewardDebt = (stakerSender.balance * pool.accRewardPerShare) / _DIV_PRECISION;
stakerReceiver.rewardDebt = (receiverFinalBalance * pool.accRewardPerShare) / _DIV_PRECISION;
emit InterestBearingTokenTransferred(from, tokenAddress, to, amount);
}
/**
* @notice Updates the reward calculations for the given reward pool (e.g. rewardPerShare)
*
* @param tokenAddress the address of the underlying token
*/
function updateRewards(address tokenAddress) public whenNotPaused {
// check if amount of unharvested rewards is bigger than last reward amount
if (rewardPools[tokenAddress].totalRewardAmount > rewardPools[tokenAddress].lastRewardAmount) {
// check if reward pool has any staked funds
if (rewardPools[tokenAddress].totalStakedAmount > 0) {
// calculate new accumulated reward per share
// new acc. reward per share = current acc. reward per share + (newly accumulated rewards / totalStakedAmount)
rewardPools[tokenAddress].accRewardPerShare =
rewardPools[tokenAddress].accRewardPerShare +
((rewardPools[tokenAddress].totalRewardAmount - rewardPools[tokenAddress].lastRewardAmount) *
_DIV_PRECISION) /
rewardPools[tokenAddress].totalStakedAmount;
}
// update last reward amount in reward pool
rewardPools[tokenAddress].lastRewardAmount = rewardPools[tokenAddress].totalRewardAmount;
}
}
/**
* @notice Adds additional rewards to a reward pool (e.g. as additional incentive to provide liquidity to this pool)
*
* @param token the address of the underlying token of the reward pool (must be an IERC20 contract)
* @param amount the amount of additional rewards (in the underlying token)
* @dev emits event RewardsAdded
*/
function addRewards(IERC20 token, uint256 amount) external whenNotPaused nonReentrant {
// check input parameters
require(address(token) != address(0), 'RewardPools: invalid address provided');
// check if reward pool for given token exists
if (!rewardPools[address(token)].exists) {
// reward pool does not yet exist - create new reward pool
rewardPools[address(token)] = RewardPool({
rewardToken: token,
interestBearingToken: new PoolsInterestBearingToken('Cross-Chain Bridge RP LPs', 'BRIDGE-RP', address(token)),
minStakeAmount: 1,
maxStakeAmount: 0,
maxPoolSize: 0,
totalStakedAmount: 0,
totalRewardAmount: 0,
accRewardPerShare: 0,
lastRewardAmount: 0,
exists: true
});
// call setRewardPools in PoolsInterestBearingToken to enable the _beforeTokenTransfer hook to work
PoolsInterestBearingToken(address(rewardPools[address(token)].interestBearingToken)).setPoolsContract(
address(this)
);
}
// transfer the additional rewards from the sender to this contract
token.safeTransferFrom(_msgSender(), address(this), amount);
// Funds that are added to reward pools with totalStakedAmount=0 will be locked forever (as there is no staker to distribute them to)
// To avoid "lost" funds we will send these funds to our BuyBackAndBurn contract to burn them instead
// As soon as there is one staker in the pool, funds will be distributed across stakers again
if (rewardPools[address(token)].totalStakedAmount == 0) {
// no stakers - send money to buyBackAndBurnContract to burn
token.safeIncreaseAllowance(address(buyBackAndBurnContract), amount);
buyBackAndBurnContract.depositERC20(token, amount);
} else {
// update the total reward amount for this reward pool (add the new rewards)
rewardPools[address(token)].totalRewardAmount = rewardPools[address(token)].totalRewardAmount + amount;
}
// additional rewards added successfully, emit event
emit RewardsAdded(address(token), amount);
}
/**
* @notice Distributes unharvested staking rewards
*
* @param tokenAddress the address of the underlying token of the reward pool
* @param stakerAddress the address for which the unharvested rewards should be distributed
* @dev emits event RewardsHarvested
*/
function harvest(address tokenAddress, address stakerAddress) external whenNotPaused nonReentrant {
_harvest(tokenAddress, stakerAddress);
}
/**
* @notice Private function that allows calls from other functions despite nonReentrant modifier
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
*/
function _harvest(address tokenAddress, address stakerAddress) private whenNotPaused {
// get staker info and check if such a record exists
StakerInfo storage staker = stakes[tokenAddress][stakerAddress];
require(staker.balance > 0, 'RewardPools: Staker has a balance of 0');
// update the reward pool calculations (e.g. rewardPerShare)
updateRewards(tokenAddress);
// calculate reward amount
uint256 accumulated = (staker.balance * rewardPools[staker.poolTokenAddress].accRewardPerShare) / _DIV_PRECISION;
uint256 rewardAmount = uint256(accumulated - staker.rewardDebt);
// Save the current share of the pool as reward debt to prevent a staker from harvesting again (similar to re-entry attack)
staker.rewardDebt = accumulated;
if (rewardAmount > 0) {
// safely transfer the reward amount to the staker address
rewardPools[tokenAddress].rewardToken.safeTransfer(stakerAddress, rewardAmount);
// successfully harvested, emit event
emit RewardsHarvested(stakerAddress, tokenAddress, rewardAmount);
}
}
/**
* @notice Provides information about how much unharvested reward is available for a specific stake(r) in a reward pool
*
* @dev we recommend to call function updateRewards(address tokenAddress) first to update the reward calculations
* @param tokenAddress the address of the underlying token of the reward pool
* @param stakerAddress the address of the staker for which pending rewards should be returned
* @return the unharvested reward amount
*/
function pendingReward(address tokenAddress, address stakerAddress) external view returns (uint256) {
// get reward pool to check rewards for
RewardPool memory pool = rewardPools[tokenAddress];
// get staker info and check if such a record exists
StakerInfo memory staker = stakes[tokenAddress][stakerAddress];
if (staker.balance == 0) {
return 0;
}
uint256 accRewardPerShare = pool.accRewardPerShare +
((pool.totalRewardAmount - pool.lastRewardAmount) * _DIV_PRECISION) /
pool.totalStakedAmount;
// calculate the amount of rewards that the sender is eligible for through his/her stake
uint256 accumulated = (staker.balance * accRewardPerShare) / _DIV_PRECISION;
return uint256(accumulated - staker.rewardDebt);
}
}
// 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 "../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
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol';
import '../utils/MyPausable.sol';
interface IPools {
function transferInterestBearingTokenHandler(
address baseToken,
uint256 amount,
address from,
address to
) external;
}
/**
* @title PoolsInterestBearingToken
* The token that users receive in return for staking their bridge tokens in our pools (liquidity mining or reward pools)
*/
contract PoolsInterestBearingToken is MyPausable, ERC20Burnable {
bytes32 public constant MANAGE_POOLS_ROLE = keccak256('MANAGE_POOLS_ROLE');
bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE');
bytes32 public constant BURNER_ROLE = keccak256('BURNER_ROLE');
address public baseToken;
address public poolsContractAddress;
/**
* @notice Constructor: Creates a new token
*
* @param name the name of the new token
* @param symbol the symbol (short name) of the new token
* @param _baseToken the address of the underlying token of the pool
*/
constructor(
string memory name,
string memory symbol,
address _baseToken
) ERC20(name, symbol) {
require(address(_baseToken) != address(0), 'PoolsInterestBearingToken: invalid base token address provided');
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MANAGE_POOLS_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(BURNER_ROLE, _msgSender());
baseToken = _baseToken;
}
/**
* @notice Mints new tokens and transfers them to the 'to' address
*
* @param from the address from which the tokens should be burned
* @param amount the amount of tokens that should be minted and transferred
* @dev emits event Transfer()
*/
function burn(address from, uint256 amount) external whenNotPaused {
require(
hasRole(BURNER_ROLE, _msgSender()),
'PoolsInterestBearingToken: must have BURNER_ROLE to execute this function'
);
_burn(from, amount);
}
/**
* @notice Mints new tokens and transfers them to the 'to' address
*
* @param to the address the newly minted tokens should be sent to
* @param amount the amount of tokens that should be minted and transfered
* @dev emits event Transfer()
*/
function mint(address to, uint256 amount) external whenNotPaused {
require(
hasRole(MINTER_ROLE, _msgSender()),
'PoolsInterestBearingToken: must have MINTER_ROLE to execute this function'
);
_mint(to, amount);
}
/**
* @notice This function (or hook) is called before every token transfer
* (to make sure that the accounting in the respective pools is up-to-date)
*
* @dev for further information on hooks see https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks
* @param from the address of the sender of the token transfer
* @param to the address of the recipient of the token transfer
* @param amount the amount of tokens that will be transfered
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override whenNotPaused {
super._beforeTokenTransfer(from, to, amount);
// check if this call was triggered by a mint() (in which case from is zero address) or by a transfer
if (from != address(0) && to != address(0)) {
// token transfer - call handler
IPools(poolsContractAddress).transferInterestBearingTokenHandler(baseToken, amount, from, to);
}
}
/**
* @notice Sets the address of the pools contract
*
* @dev can only be called by MANAGE_POOLS_ROLE
* @param _poolsContractAddress the address of the pools contract (RewardPools or LiquidityMiningPools)
*/
function setPoolsContract(address _poolsContractAddress) external {
require(
hasRole(MANAGE_POOLS_ROLE, _msgSender()),
'PoolsInterestBearingToken: must have MANAGE_POOLS_ROLE to execute this function'
);
require(address(_poolsContractAddress) != address(0), 'PoolsInterestBearingToken: invalid pool address provided');
poolsContractAddress = _poolsContractAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol';
import '../utils/MyPausableUpgradeable.sol';
import 'hardhat/console.sol';
import '../RewardPools.sol';
contract Bridge is ERC20Upgradeable, MyPausableUpgradeable {
bytes32 public constant MANAGE_TOKEN_ROLE = keccak256('MANAGE_TOKEN_ROLE');
/**
* @notice Initializer instead of constructor to have the contract upgradeable
*
* @param _totalSupply the total supply of Bridge tokens
*/
function initialize(uint256 _totalSupply) external initializer {
// call parent initializers
__MyPausableUpgradeable_init();
__ERC20_init('Cross-Chain Bridge Token', 'BRIDGE');
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
// mint total supply to deployer
_mint(_msgSender(), _totalSupply);
}
/**
* @notice Mints (creates new) Bridge tokens and sends them to the given address
*
* @dev can only be called by MANAGE_TOKEN_ROLE
* @param to the address of the receiver the tokens should be minted to
* @param amount the amount of tokens to be minted
* @dev see {ERC20-_burn}
* @dev emits event Transfer
*/
function mint(address to, uint256 amount) external whenNotPaused {
require(hasRole(MANAGE_TOKEN_ROLE, _msgSender()), 'Bridge: must have MANAGE_TOKEN_ROLE to mint');
_mint(to, amount);
}
/**
* @notice Burns (destroys) the given amount of Bridge tokens from the caller of the function
*
* @dev see {ERC20-_burn}
* @dev emits event Transfer
*/
function burn(uint256 amount) external virtual whenNotPaused {
_burn(_msgSender(), amount);
}
/**
* @notice Burns (destroys) the given amount of Bridge tokens on behalf of another account
*
* @dev see {ERC20-_burn} and {ERC20-allowance}
* @dev the caller must have allowance for ``accounts``'s tokens
* @param from the address that owns the tokens to be burned
* @param amount the amount of tokens to be burned
* @dev emits event Transfer
*/
function burnFrom(address from, uint256 amount) external virtual whenNotPaused {
// check if burn amount is within allowance
require(allowance(from, _msgSender()) >= amount, 'Bridge: burn amount exceeds allowance');
_approve(from, _msgSender(), allowance(from, _msgSender()) - amount);
// burn token
_burn(from, amount);
}
/**
* @notice This function (or hook) is called before every token transfer
*
* @dev for further information on hooks see https://docs.openzeppelin.com/contracts/3.x/extending-contracts#using-hooks
* @param from the address of the sender of the token transfer
* @param to the address of the recipient of the token transfer
* @param amount the amount of tokens that will be transferred
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override whenNotPaused {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
/**
* @title MyPausableUpgradeable
* This contracts introduces pausability,reentrancy guard and access control to all smart contracts that inherit from it
*/
abstract contract MyPausableUpgradeable is
AccessControlUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable,
UUPSUpgradeable
{
bytes32 public constant PAUSABILITY_PAUSE_ROLE = keccak256('PAUSABILITY_PAUSE_ROLE');
bytes32 public constant PAUSABILITY_UNPAUSE_ROLE = keccak256('PAUSABILITY_UNPAUSE_ROLE');
bytes32 public constant MANAGE_UPGRADES_ROLE = keccak256('MANAGE_UPGRADES_ROLE');
/**
* @notice Initializer instead of constructor to have the contract upgradeable
* @dev can only be called once after deployment of the contract
*/
function __MyPausableUpgradeable_init() internal initializer {
// call parent initializers
__ReentrancyGuard_init();
__AccessControl_init();
__Pausable_init();
__UUPSUpgradeable_init();
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSABILITY_PAUSE_ROLE, _msgSender());
_setupRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender());
_setupRole(MANAGE_UPGRADES_ROLE, _msgSender());
}
/**
* @notice This function s required to enable the OpenZeppelin UUPS proxy upgrade pattern
* We decided to implement this function here as every other contract inherits from this one
*
* @dev can only be called by MANAGE_UPGRADES_ROLE
*/
function _authorizeUpgrade(address) internal view override {
require(
hasRole(MANAGE_UPGRADES_ROLE, _msgSender()),
'MyPausableUpgradeable: must have MANAGE_UPGRADES_ROLE to execute this function'
);
}
/**
* @notice Pauses all contract functions that have the "whenNotPaused" modifier
*
* @dev can only be called by PAUSABILITY_ADMIN_ROLE
*/
function pause() external whenNotPaused {
require(
hasRole(PAUSABILITY_PAUSE_ROLE, _msgSender()),
'MyPausableUpgradeable: must have PAUSABILITY_PAUSE_ROLE to execute this function'
);
PausableUpgradeable._pause();
}
/**
* @notice Un-pauses/resumes all contract functions that have the "whenNotPaused" modifier
*
* @dev can only be called by PAUSABILITY_ADMIN_ROLE
*/
function unpause() external whenPaused {
require(
hasRole(PAUSABILITY_UNPAUSE_ROLE, _msgSender()),
'MyPausableUpgradeable: must have PAUSABILITY_UNPAUSE_ROLE to execute this function'
);
PausableUpgradeable._unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import './IRouter.sol';
interface IBuyBackAndBurn {
function depositERC20(IERC20 token, uint256 amount) external;
function depositNativeToken(uint256 amount) external payable;
//function iRouter() external returns (IRouter);
}
// 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 "../ERC20.sol";
import "../../../utils/Context.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts/access/AccessControl.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
/**
* @title MyPausable
* This contracts introduces pausability and access control to all smart contracts that inherit from it
*/
abstract contract MyPausable is AccessControl, Pausable {
bytes32 public constant PAUSABILITY_ADMIN_ROLE = keccak256('PAUSABILITY_ADMIN_ROLE');
constructor() {
// set up admin roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSABILITY_ADMIN_ROLE, _msgSender());
}
/**
* @notice Pauses all contract functions that have the "whenNotPaused" modifier
*
* @dev can only be called by PAUSABILITY_ADMIN_ROLE
*/
function pause() external whenNotPaused {
require(
hasRole(PAUSABILITY_ADMIN_ROLE, _msgSender()),
'MyPausable: must have PAUSABILITY_ADMIN_ROLE to execute this function'
);
Pausable._pause();
}
/**
* @notice Un-pauses/resumes all contract functions that have the "whenNotPaused" modifier
*
* @dev can only be called by PAUSABILITY_ADMIN_ROLE
*/
function unpause() external whenPaused {
require(
hasRole(PAUSABILITY_ADMIN_ROLE, _msgSender()),
'MyPausable: must have PAUSABILITY_ADMIN_ROLE to execute this function'
);
Pausable._unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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 Contracts guidelines: functions revert
* instead 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, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @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(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 override 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];
}
/**
* @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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
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] + 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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
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(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
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);
_afterTokenTransfer(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");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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);
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);
_afterTokenTransfer(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 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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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 "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* 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, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override onlyRole(getRoleAdmin(role)) {
_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 override onlyRole(getRoleAdmin(role)) {
_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 override {
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
}
// 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;
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;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 Contracts guidelines: functions revert
* instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 override 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];
}
/**
* @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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
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] + 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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
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(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
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);
_afterTokenTransfer(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");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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);
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);
_afterTokenTransfer(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 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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
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
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 {ERC1967Proxy-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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/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.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* 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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @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 override 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 override onlyRole(getRoleAdmin(role)) {
_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 override onlyRole(getRoleAdmin(role)) {
_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 override {
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 {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/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.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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 {AccessControl-_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) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @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) external;
/**
* @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) external;
/**
* @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) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
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;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// 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 IERC165Upgradeable {
/**
* @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.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^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;
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 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 Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IRouter {
function tradeERC20(
IERC20 collectedToken,
IERC20 burnToken,
uint256 amount
) external returns (uint256 tokensReceived);
function tradeNativeTokenForERC20(IERC20 output, uint256 inputAmount) external payable returns (uint256);
function addSwapPath(
address input,
address output,
address[] memory path
) external;
function wrappedNative() external returns (address);
// function getDexAddress() external returns(address);
} | Private function that allows calls from other functions despite nonReentrant modifier/ get staker info and check if such a record exists update the reward pool calculations (e.g. rewardPerShare) calculate reward amount Save the current share of the pool as reward debt to prevent a staker from harvesting again (similar to re-entry attack) safely transfer the reward amount to the staker address successfully harvested, emit event | function _harvest(address tokenAddress, address stakerAddress) private whenNotPaused {
StakerInfo storage staker = stakes[tokenAddress][stakerAddress];
require(staker.balance > 0, 'RewardPools: Staker has a balance of 0');
updateRewards(tokenAddress);
uint256 accumulated = (staker.balance * rewardPools[staker.poolTokenAddress].accRewardPerShare) / _DIV_PRECISION;
uint256 rewardAmount = uint256(accumulated - staker.rewardDebt);
staker.rewardDebt = accumulated;
if (rewardAmount > 0) {
rewardPools[tokenAddress].rewardToken.safeTransfer(stakerAddress, rewardAmount);
emit RewardsHarvested(stakerAddress, tokenAddress, rewardAmount);
}
}
| 87,320 |
/**
MIT License
Copyright (c) 2019 Mavennet Systems Inc. https://mavennet.com
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.
*/
pragma solidity 0.4.15;
contract Owned {
address public owner;
address newOwner;
bool private transitionState;
event OwnershipTransferInitiated(address indexed _previousOwner, address indexed _newOwner);
event OwnershipTransferAccepted(address indexed _newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyNotOwner() {
require(msg.sender != owner);
_;
}
function Owned() {
owner = msg.sender;
newOwner = msg.sender;
transitionState = false;
}
function owner() public constant returns (address) {
return owner;
}
function isOwner() public constant returns (bool) {
return msg.sender == owner;
}
function hasPendingTransferRequest() public constant returns (bool){
return transitionState;
}
function changeOwner(address _newOwner) public onlyOwner returns (bool) {
require(_newOwner != address(0));
newOwner = _newOwner;
transitionState = true;
OwnershipTransferInitiated(owner, _newOwner);
return true;
}
function acceptOwnership() public returns (bool){
require(newOwner == msg.sender);
owner = newOwner;
transitionState = false;
OwnershipTransferAccepted(owner);
return true;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* @notice This is a softer (in terms of throws) variant of SafeMath:
* https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1121
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal constant returns (uint256) {
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;
require(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal constant returns (uint256) {
// Solidity automatically throws when dividing by 0
// therefore require beforehand avoid throw
require(_b > 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 constant returns (uint256) {
require(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal constant returns (uint256 c) {
c = _a + _b;
require(c >= _a);
return c;
}
function max(uint256 a, uint256 b) internal constant returns (uint256) {
return a > b ? a : b;
}
}
/// @title Bridge Operator Standard implementation for AIP #005 to achieve the cross chain
/// functionality for the tokens or assets on Ethereum network
contract BridgeOperatorBase is Owned {
using SafeMath for uint256;
uint256 constant MAX_SIGNATORIES = 32;
uint256 internal signatoriesCount;
uint256 internal approval;
mapping(address => bool) internal signatories;
mapping(bytes32 => bytes32) internal bundleTxMap;
// this registry holds information about valid signatories
SignatoryRegistry signatoryRegistry =
SignatoryRegistry(signatory-registry-contract-address-here);
// this address points to ATS implementation
ATSTokenBase atsTokenBase =
ATSTokenBase(ATS-token-contract-address-here);
/// @notice informs that the given signatory is available for transfer verification
event AddedSignatory(address _signatory);
/// @notice informs that the given signatory can no more participate in transfer verification
event RemovedSignatory(address _signatory);
/// @notice bridge operator releases the asset on the destination chain at the end of bundle verification
event Distributed(
bytes32 indexed sourceTransactionHash,
address indexed recipient,
uint256 indexed amount,
bytes32 initTransferHash
);
/// @notice the bundle has been processed without any errors
event ProcessedBundle(
bytes32 indexed sourceBlockHash,
bytes32 indexed bundleHash
);
/// @notice inform that the bundle has already been processed
event SuccessfulTransactionHash(
bytes32 indexed destinationTransactionHash
);
function BridgeOperatorBase() public {
signatoriesCount = 0;
}
/// @notice initialize the group of signatories for the bridge operator
/// @dev signatories cannot be reinitialized if already initialized
/// @param _signatories list of signatory addresses
function initializeSignatories(address[] _signatories) public onlyOwner {
require(_signatories.length != 0);
require(_signatories.length < MAX_SIGNATORIES);
require(signatoriesCount == 0);
require(signatoriesCount < MAX_SIGNATORIES);
for (uint256 i=0; i < _signatories.length; i++) {
if (signatoryRegistry.isValid(address(_signatories[i]))) {
signatories[_signatories[i]] = true;
signatoriesCount++;
}
}
require(signatoriesCount > 0);
uint256 count = signatoriesCount.mul(2).div(3);
approval = count.max(1);
}
/// @notice bridge operator onboards a signatory after initializing the bridge
/// @param _signatory signatory address
function addSignatory(address _signatory) public onlyOwner {
require(_signatory != address(0));
require(signatoriesCount < MAX_SIGNATORIES);
require(!signatories[_signatory]);
require(signatoryRegistry.isValid(address(_signatory)));
signatories[_signatory] = true;
signatoriesCount += 1;
uint256 count = signatoriesCount.mul(2).div(3);
approval = count.max(1);
AddedSignatory(_signatory);
}
/// @notice bridge operator removes an existing signatory if it does not want to
/// participate in the transfer process or cannot be trusted further
/// @param _signatory signatory address
function removeSignatory(address _signatory) public onlyOwner {
require(_signatory != address(0));
require(signatories[_signatory]);
signatories[_signatory] = false;
signatoriesCount -= 1;
uint256 count = signatoriesCount.mul(2).div(3);
approval = count.max(1);
RemovedSignatory(_signatory);
}
/// @notice checks if given signatory is selected for this bridge's transfer process
/// @param _signatory signatory address
/// @return true or false
function isValidSignatory(address _signatory) public returns (bool) {
return signatories[_signatory];
}
/// @notice returns number of selected signatories participating in the transfer process
/// @return number
function validSignatoriesCount() constant returns (uint256) {
return signatoriesCount;
}
/// @notice returns the minimum number of selected signatories required to thaw tokens on
/// the destination network.
/// @return number
function minimumSignatoriesApproval() constant returns (uint256) {
return approval;
}
/// @notice Bridge operator verifies that the signatories threshold is met. Thaw function is
/// called in the ATS to release the assets at the end of current bundle verification and
/// emits Distributed event.
/// @dev If the bundle is successfully verified, it emits ProcessedBundle event. If a
/// bundle has already been previously verified and exists then it emits
/// SuccessfulTransactionHash event with its correct parameter.
/// @param _sourceBlockHash The block hash from the source chain having transfer transactions
/// @param _sourceTransactionHashes The transfer transaction hashes in sourceBlockHash from
/// the source chain
/// @param _recipients The destination chain account addresses participating in transfer process
/// @param _amounts The respective amounts to be thawed by bridge operator
/// @param _V The 'v' component of a signature of Secp256k1
/// @param _R The 'r' component of a signature of Secp256k1
/// @param _S The 's' component of a signature of Secp256k1
/// @param _initTransferHashes keccak256 hashes of respective transfer recipients, amounts, UUIDs
function processBundle(
bytes32 _sourceBlockHash,
bytes32[] _sourceTransactionHashes,
address[] _recipients,
uint256[] _amounts,
uint8[] _V,
bytes32[] _R,
bytes32[] _S,
bytes32[] _initTransferHashes
)
public
onlyOwner
{
require(_sourceBlockHash != 0);
require(_sourceTransactionHashes.length == _recipients.length);
require(_recipients.length == _amounts.length);
require(approval > 0);
require(_V.length >= approval);
bytes32 transferBundleHash = sha3(
_sourceBlockHash,
_sourceTransactionHashes,
_recipients,
_amounts
);
if (bundleTxMap[transferBundleHash] != 0) {
SuccessfulTransactionHash(getBundle(transferBundleHash));
}
require(bundleTxMap[transferBundleHash] == 0);
//verify signatures
hasEnoughSignatures(transferBundleHash, _V, _R, _S);
uint256 i;
for (i = 0; i < _sourceTransactionHashes.length; ++i) {
atsTokenBase.thaw(
_recipients[i],
_amounts[i],
this,
_sourceTransactionHashes[i],
_initTransferHashes[i]
);
Distributed(
_sourceTransactionHashes[i],
_recipients[i],
_amounts[i],
_initTransferHashes[i]
);
}
// Ethereum does not have support for transaction hash, hence setting it
// to fixed value 1 temporarily
bundleTxMap[transferBundleHash] = 0x1;
ProcessedBundle(_sourceBlockHash, transferBundleHash);
}
/// @notice returns 1 if bundle is already processed, however this method is ignored for now
/// @param _bundleHash hash of transfer bundle
/// @return returns 1
function getBundle(bytes32 _bundleHash) constant returns (bytes32) {
return bundleTxMap[_bundleHash];
}
/// @notice bridge operator sets the mapping to 1 if bundle is already processed, however,
/// this method is ignored for now
/// @param _bundleHash hash of transfer bundle
/// @param _transactionHash transaction hash from the processBundle operation
function setBundle(bytes32 _bundleHash, bytes32 _transactionHash) public onlyOwner {
if (bundleTxMap[_bundleHash] == 0x1)
bundleTxMap[_bundleHash] = _transactionHash;
}
/// @param _transferBundleHash The bundle hash of the transfer to be validated
/// @param _V The 'v' component of a signature of Secp256k1
/// @param _R The 'r' component of a signature of Secp256k1
/// @param _S The 's' component of a signature of Secp256k1
function hasEnoughSignatures(
bytes32 _transferBundleHash,
uint8[] _V,
bytes32[] _R,
bytes32[] _S
)
internal
{
uint256 i;
uint256 signed = 0;
for (i = 0; i < _V.length; ++i) {
address signatory = ecrecover(_transferBundleHash, _V[i], _R[i], _S[i]);
require(isValidSignatory(signatory));
require(signatoryRegistry.isValid(signatory));
if (signatories[signatory]) {
signed += 1;
}
}
require(signed >= approval);
}
}
/// @title reference to the functions in the ERC20 controller (ATS) implementation
contract ATSTokenBase {
function thaw(
address _recipient,
uint256 _amount,
address _bridgeAddress,
bytes32 _sourceTransactionHash,
bytes32 _initTransferHash
)
public;
}
/// @title reference to the functions in the Signatory Registry implementation
contract SignatoryRegistry {
function isValid(address _signatory) public returns (bool);
} | Adds two numbers, throws on overflow./ | function add(uint256 _a, uint256 _b) internal constant returns (uint256 c) {
c = _a + _b;
require(c >= _a);
return c;
}
| 1,088,834 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../eip712/ITransferWithSig.sol";
import "../defi/ILendManager.sol";
import "../dex/ISwapManager.sol";
import "../matic/IRootChainManager.sol";
import "../matic/IBridgableToken.sol";
import "../libs/SafeDelegate.sol";
contract Cashier is Ownable {
using SafeMath for uint256;
using SafeDelegate for address;
using SafeERC20 for IERC20;
// Amount is informed in bridgeableToken currency
event BridgeDeposit(address indexed wallet, uint256 amount);
event BridgeExit(address indexed wallet, uint256 amount);
event ReserveChanged(address indexed reserve);
IERC20 public reserveToken;
IBridgableToken public bridgeableToken;
ISwapManager public swapManager;
address public posBridge;
constructor(
address _bridge,
address _reserve,
address _bridgeableToken,
address _swapManager
)
Ownable() public
{
posBridge = _bridge;
reserveToken = IERC20(_reserve);
bridgeableToken = IBridgableToken(_bridgeableToken);
/// sets swapManager
setSwapConverter(_swapManager);
}
/**
* @dev Sets swap protocol api
*/
function setSwapConverter(address _manager) public onlyOwner {
require(_manager != address(0), "Cashier: invalid swap manager");
swapManager = ISwapManager(_manager);
}
/**
* @dev The exit() sends tokens to layer 2 withdrawer(),
* we need to get those tokens here to convert sTSX into paymentToken.
* We'are calling this method with a eip712 token transfer signature for that purpose.
*
* @param _tokenAmount sigTransfer tokenAmount
* @param _expiration sigTransfer expiration
* @param _orderId sigTransfer orderId
* @param _orderSignature signedTypedData signature
* @param _paymentToken final payment token ERC20 address
* @param _burnProof from withdraw() inclusion in mainnet
*/
function withdraw(
uint256 _tokenAmount,
uint256 _expiration,
bytes32 _orderId,
bytes calldata _orderSignature,
IERC20 _paymentToken,
bytes calldata _burnProof
)
external
{
uint256 bTokenBalance = bridgeableToken.balanceOf(address(this));
// Get tokens from L2 bridge
IRootChainManager(posBridge).exit(_burnProof);
// Transfer sTSX amount from L2 burner's address
// to this contract using EIP712 signature
ITransferWithSig(address(bridgeableToken)).transferWithSig(
_orderSignature,
_tokenAmount,
keccak256(
abi.encodePacked(_orderId, address(bridgeableToken), _tokenAmount)
),
_expiration,
address(this)
);
// Check bridgeableToken balance from exit
uint256 withdrawAmount = bridgeableToken
.balanceOf(address(this))
.sub(bTokenBalance);
require(withdrawAmount > 0, "Cashier: withdrawAmount invalid");
emit BridgeExit(msg.sender, withdrawAmount);
bridgeableToken.burn(withdrawAmount);
/// If user asked same coin as reserve, send directly
if (_paymentToken == reserveToken) {
reserveToken.safeTransfer(msg.sender, withdrawAmount);
/// reserve <> token conversion
} else {
bytes memory r = address(swapManager).callfn(
abi.encodeWithSelector(
ISwapManager.swapTokenToToken.selector,
// args
reserveToken,
_paymentToken,
withdrawAmount,
0, /// maxDstAmount ??
msg.sender /// _beneficiary
),
"Cashier :: swapTokenToToken()"
);
(, uint256 reminder) = abi.decode(r, (uint256,uint256));
require(reminder == 0, "Cashier :: reminder swap tx");
}
}
/**
* @dev deposit using ERC20
*/
function deposit(
IERC20 _depositToken,
uint256 _depositAmount,
address _addrTo
)
external
{
require(_depositAmount > 0, "Cashier :: invalid _depositAmount");
// transfer user tokens
_depositToken.safeTransferFrom(
msg.sender,
address(this),
_depositAmount
);
// Call uniswap api to perform token <> reserve conversion
if (_depositToken != reserveToken) {
bytes memory r = address(swapManager).callfn(
abi.encodeWithSelector(
ISwapManager.swapTokenToToken.selector,
// args
_depositToken,
reserveToken,
_depositAmount,
0, // maxDstAmount
address(this) // _beneficiary
),
"Cashier :: swapManager swapTokenToToken.delegatecall()"
);
(uint256 amount, uint256 reminder) = abi.decode(r, (uint256,uint256));
require(reminder == 0, "Cashier :: reminder tx");
_depositAmount = amount;
}
_posDeposit(bridgeableToken, _addrTo, _depositAmount);
}
/**
* @dev deposit eth
*/
function deposit(address _addrTo) external payable {
require(msg.value > 0, "Cashier :: invalid msg.value");
bytes memory r = address(swapManager).callfn(
abi.encodeWithSelector(
swapManager.swapEthToToken.selector,
// args
msg.value,
reserveToken,
0, // maxDstAmount
address(this) // _beneficiary
),
"Cashier :: swapEthToToken()"
);
(uint256 _depositAmount, uint256 reminder) = abi.decode(r, (uint256,uint256));
require(reminder == 0, "Cashier :: reminder swap tx");
_posDeposit(bridgeableToken, _addrTo, _depositAmount);
}
/**
* @dev Clears allowance and calls POS bridge depositFor()
* _erc20Token should be already approved to be bridged.
*
* @param _erc20Token to deposit
* @param _toAddr user address to send tokens to
* @param _amount amount to deposit
*/
function _posDeposit(
IBridgableToken _erc20Token,
address _toAddr,
uint256 _amount
)
private
{
// mint 1:1 and deposit
_erc20Token.mint(address(this), _amount);
// Call pos bridge depositFor.
IRootChainManager(posBridge).depositFor(
_toAddr,
address(_erc20Token),
abi.encode(_amount)
);
emit BridgeDeposit(_toAddr, _amount);
}
}
| deposit eth/ args | function deposit(address _addrTo) external payable {
require(msg.value > 0, "Cashier :: invalid msg.value");
bytes memory r = address(swapManager).callfn(
abi.encodeWithSelector(
swapManager.swapEthToToken.selector,
msg.value,
reserveToken,
),
"Cashier :: swapEthToToken()"
);
(uint256 _depositAmount, uint256 reminder) = abi.decode(r, (uint256,uint256));
require(reminder == 0, "Cashier :: reminder swap tx");
_posDeposit(bridgeableToken, _addrTo, _depositAmount);
}
| 13,129,492 |
// Hudson Jameson (Souptacular) Created December 2015
contract owned
{
function owned()
{
owner = msg.sender;
}
modifier onlyowner()
{
if (msg.sender == owner)
_
}
address owner;
}
contract Marriage is owned
{
// Store marriage data
bytes32 public partner1;
bytes32 public partner2;
uint256 public marriageDate;
bytes32 public marriageStatus;
bytes public marriageProofDoc;
// Create initial marriage contract
function createMarriage(bytes32 partner1Entry, bytes32 partner2Entry, uint256 marriageDateEntry, bytes32 status, bytes description)
{
partner1 = partner1Entry;
partner2 = partner2Entry;
marriageDate = marriageDateEntry;
setStatus(marriageStatus);
bytes28 name = "Marriage Contract Creation";
MajorEvent(block.timestamp, marriageDate, name, description);
}
// Set the marriage status if it changes
function setStatus(bytes32 status)
{
marriageStatus = status;
}
// Upload documentation for proof of marrage like a marriage certificate
function marriageProof(bytes IPFSHash)
{
marriageProofDoc = IPFSHash;
}
// Log major life events
function majorEvent(bytes32 name, bytes description, uint256 eventTimeStamp)
{
MajorEvent(block.timestamp, eventTimeStamp, name, description);
}
// Withdraw my vacation fund
function returnFunds()
{
uint256 balance = address(this).balance;
address(owner).send(balance);
}
event MajorEvent(uint256 logTimeStamp, uint256 eventTimeStamp, bytes32 indexed name, bytes indexed description);
} | Set the marriage status if it changes | function setStatus(bytes32 status)
{
marriageStatus = status;
}
| 12,994,491 |
/**
*Submitted for verification at Etherscan.io on 2021-01-31
*/
pragma solidity ^0.6.6;
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 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
/**
* @title The Owned contract
* @notice A contract with helpers for basic contract ownership.
*/
contract Owned {
address public owner;
address private pendingOwner;
event OwnershipTransferRequested(
address indexed from,
address indexed to
);
event OwnershipTransferred(
address indexed from,
address indexed to
);
constructor() public {
owner = msg.sender;
}
/**
* @dev Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address _to)
external
onlyOwner()
{
pendingOwner = _to;
emit OwnershipTransferRequested(owner, _to);
}
/**
* @dev Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership()
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @dev Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "Only callable by owner");
_;
}
}
/**
* @title A trusted proxy for updating where current answers are read from
* @notice This contract provides a consistent address for the
* CurrentAnwerInterface but delegates where it reads from to the owner, who is
* trusted to update it.
*/
contract AggregatorProxy is AggregatorV2V3Interface, Owned {
struct Phase {
uint16 id;
AggregatorV2V3Interface aggregator;
}
Phase private currentPhase;
AggregatorV2V3Interface public proposedAggregator;
mapping(uint16 => AggregatorV2V3Interface) public phaseAggregators;
uint256 constant private PHASE_OFFSET = 64;
uint256 constant private PHASE_SIZE = 16;
uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1;
constructor(address _aggregator) public Owned() {
setAggregator(_aggregator);
}
/**
* @notice Reads the current answer from aggregator delegated to.
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestAnswer()
public
view
virtual
override
returns (int256 answer)
{
return currentPhase.aggregator.latestAnswer();
}
/**
* @notice Reads the last updated height from aggregator delegated to.
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestTimestamp()
public
view
virtual
override
returns (uint256 updatedAt)
{
return currentPhase.aggregator.latestTimestamp();
}
/**
* @notice get past rounds answers
* @param _roundId the answer number to retrieve the answer for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getAnswer(uint256 _roundId)
public
view
virtual
override
returns (int256 answer)
{
if (_roundId > MAX_ID) return 0;
(uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId);
AggregatorV2V3Interface aggregator = phaseAggregators[phaseId];
if (address(aggregator) == address(0)) return 0;
return aggregator.getAnswer(aggregatorRoundId);
}
/**
* @notice get block timestamp when an answer was last updated
* @param _roundId the answer number to retrieve the updated timestamp for
*
* @dev #[deprecated] Use getRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended getRoundData
* instead which includes better verification information.
*/
function getTimestamp(uint256 _roundId)
public
view
virtual
override
returns (uint256 updatedAt)
{
if (_roundId > MAX_ID) return 0;
(uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId);
AggregatorV2V3Interface aggregator = phaseAggregators[phaseId];
if (address(aggregator) == address(0)) return 0;
return aggregator.getTimestamp(aggregatorRoundId);
}
/**
* @notice get the latest completed round where the answer was updated. This
* ID includes the proxy's phase, to make sure round IDs increase even when
* switching to a newly deployed aggregator.
*
* @dev #[deprecated] Use latestRoundData instead. This does not error if no
* answer has been reached, it will simply return 0. Either wait to point to
* an already answered Aggregator or use the recommended latestRoundData
* instead which includes better verification information.
*/
function latestRound()
public
view
virtual
override
returns (uint256 roundId)
{
Phase memory phase = currentPhase; // cache storage reads
return addPhase(phase.id, uint64(phase.aggregator.latestRound()));
}
/**
* @notice get data about a round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @param _roundId the requested round ID as presented through the proxy, this
* is made up of the aggregator's round ID with the phase ID encoded in the
* two highest order bytes
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function getRoundData(uint80 _roundId)
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
(uint16 phaseId, uint64 aggregatorRoundId) = parseIds(_roundId);
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 ansIn
) = phaseAggregators[phaseId].getRoundData(aggregatorRoundId);
return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, phaseId);
}
/**
* @notice get data about the latest round. Consumers are encouraged to check
* that they're receiving fresh data by inspecting the updatedAt and
* answeredInRound return values.
* Note that different underlying implementations of AggregatorV3Interface
* have slightly different semantics for some of the return values. Consumers
* should determine what implementations they expect to receive
* data from and validate that they can properly handle return data from all
* of them.
* @return roundId is the round ID from the aggregator for which the data was
* retrieved combined with an phase to ensure that round IDs get larger as
* time moves forward.
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @dev Note that answer and updatedAt may change between queries.
*/
function latestRoundData()
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Phase memory current = currentPhase; // cache storage reads
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 ansIn
) = current.aggregator.latestRoundData();
return addPhaseIds(roundId, answer, startedAt, updatedAt, ansIn, current.id);
}
/**
* @notice Used if an aggregator contract has been proposed.
* @param _roundId the round ID to retrieve the round data for
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
*/
function proposedGetRoundData(uint80 _roundId)
public
view
virtual
hasProposal()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return proposedAggregator.getRoundData(_roundId);
}
/**
* @notice Used if an aggregator contract has been proposed.
* @return roundId is the round ID for which data was retrieved
* @return answer is the answer for the given round
* @return startedAt is the timestamp when the round was started.
* (Only some AggregatorV3Interface implementations return meaningful values)
* @return updatedAt is the timestamp when the round last was updated (i.e.
* answer was last computed)
* @return answeredInRound is the round ID of the round in which the answer
* was computed.
*/
function proposedLatestRoundData()
public
view
virtual
hasProposal()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return proposedAggregator.latestRoundData();
}
/**
* @notice returns the current phase's aggregator address.
*/
function aggregator()
external
view
returns (address)
{
return address(currentPhase.aggregator);
}
/**
* @notice returns the current phase's ID.
*/
function phaseId()
external
view
returns (uint16)
{
return currentPhase.id;
}
/**
* @notice represents the number of decimals the aggregator responses represent.
*/
function decimals()
external
view
override
returns (uint8)
{
return currentPhase.aggregator.decimals();
}
/**
* @notice the version number representing the type of aggregator the proxy
* points to.
*/
function version()
external
view
override
returns (uint256)
{
return currentPhase.aggregator.version();
}
/**
* @notice returns the description of the aggregator the proxy points to.
*/
function description()
external
view
override
returns (string memory)
{
return currentPhase.aggregator.description();
}
/**
* @notice Allows the owner to propose a new address for the aggregator
* @param _aggregator The new address for the aggregator contract
*/
function proposeAggregator(address _aggregator)
external
onlyOwner()
{
proposedAggregator = AggregatorV2V3Interface(_aggregator);
}
/**
* @notice Allows the owner to confirm and change the address
* to the proposed aggregator
* @dev Reverts if the given address doesn't match what was previously
* proposed
* @param _aggregator The new address for the aggregator contract
*/
function confirmAggregator(address _aggregator)
external
onlyOwner()
{
require(_aggregator == address(proposedAggregator), "Invalid proposed aggregator");
delete proposedAggregator;
setAggregator(_aggregator);
}
/*
* Internal
*/
function setAggregator(address _aggregator)
internal
{
uint16 id = currentPhase.id + 1;
currentPhase = Phase(id, AggregatorV2V3Interface(_aggregator));
phaseAggregators[id] = AggregatorV2V3Interface(_aggregator);
}
function addPhase(
uint16 _phase,
uint64 _originalId
)
internal
view
returns (uint80)
{
return uint80(uint256(_phase) << PHASE_OFFSET | _originalId);
}
function parseIds(
uint256 _roundId
)
internal
view
returns (uint16, uint64)
{
uint16 phaseId = uint16(_roundId >> PHASE_OFFSET);
uint64 aggregatorRoundId = uint64(_roundId);
return (phaseId, aggregatorRoundId);
}
function addPhaseIds(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound,
uint16 phaseId
)
internal
view
returns (uint80, int256, uint256, uint256, uint80)
{
return (
addPhase(phaseId, uint64(roundId)),
answer,
startedAt,
updatedAt,
addPhase(phaseId, uint64(answeredInRound))
);
}
/*
* Modifiers
*/
modifier hasProposal() {
require(address(proposedAggregator) != address(0), "No proposed aggregator present");
_;
}
}
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;
}
}
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 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 IEBOP20 is IERC20 {
//constructor(string memory name_, string memory symbol_) public ERC20(name_, symbol_)
/* Skeleton EBOP20 implementation. not useable*/
function bet(int256 latestPrice, uint256 amount) external virtual returns (uint256, uint256);
function unlockAndPayExpirer(uint256 lockValue , uint256 purchaseValue, address expirer) external virtual returns (bool);
function payout(uint256 lockValue,uint256 purchaseValue, address sender, address buyer) external virtual returns (bool);
}
/**
* @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 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. 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 {
_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 { }
}
contract BIOPToken is ERC20 {
using SafeMath for uint256;
address public binaryOptions = 0x0000000000000000000000000000000000000000;
address public gov;
address public owner;
uint256 public earlyClaimsAvailable = 450000000000000000000000000000;
uint256 public totalClaimsAvailable = 750000000000000000000000000000;
bool public earlyClaims = true;
bool public binaryOptionsSet = false;
constructor(string memory name_, string memory symbol_) public ERC20(name_, symbol_) {
owner = msg.sender;
}
modifier onlyBinaryOptions() {
require(binaryOptions == msg.sender, "Ownable: caller is not the Binary Options Contract");
_;
}
modifier onlyOwner() {
require(binaryOptions == msg.sender, "Ownable: caller is not the owner");
_;
}
function updateEarlyClaim(uint256 amount) external onlyBinaryOptions {
require(totalClaimsAvailable.sub(amount) >= 0, "insufficent claims available");
if (earlyClaims) {
earlyClaimsAvailable = earlyClaimsAvailable.sub(amount);
_mint(tx.origin, amount);
if (earlyClaimsAvailable <= 0) {
earlyClaims = false;
}
} else {
updateClaim(amount.div(4));
}
}
function updateClaim( uint256 amount) internal {
require(totalClaimsAvailable.sub(amount) >= 0, "insufficent claims available");
totalClaimsAvailable.sub(amount);
_mint(tx.origin, amount);
}
function setupBinaryOptions(address payable options_) external {
require(binaryOptionsSet != true, "binary options is already set");
binaryOptions = options_;
}
function setupGovernance(address payable gov_) external onlyOwner {
_mint(owner, 100000000000000000000000000000);
_mint(gov_, 450000000000000000000000000000);
owner = 0x0000000000000000000000000000000000000000;
}
}
/**
* @title Power function by Bancor
* @dev https://github.com/bancorprotocol/contracts
*
* Modified from the original by Slava Balasanov & Tarrence van As
*
* Split Power.sol out from BancorFormula.sol
* https://github.com/bancorprotocol/contracts/blob/c9adc95e82fdfb3a0ada102514beb8ae00147f5d/solidity/contracts/converter/BancorFormula.sol
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements;
* and to You under the Apache License, Version 2.0. "
*/
contract Power {
string public version = "0.3";
uint256 private constant ONE = 1;
uint32 private constant MAX_WEIGHT = 1000000;
uint8 private constant MIN_PRECISION = 32;
uint8 private constant MAX_PRECISION = 127;
/**
The values below depend on MAX_PRECISION. If you choose to change it:
Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below.
*/
uint256 private constant FIXED_1 = 0x080000000000000000000000000000000;
uint256 private constant FIXED_2 = 0x100000000000000000000000000000000;
uint256 private constant MAX_NUM = 0x200000000000000000000000000000000;
/**
Auto-generated via 'PrintLn2ScalingFactors.py'
*/
uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8;
uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80;
/**
Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py'
*/
uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3;
uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000;
/**
The values below depend on MIN_PRECISION and MAX_PRECISION. If you choose to change either one of them:
Apply the same change in file 'PrintFunctionBancorFormula.py', run it and paste the results below.
*/
uint256[128] private maxExpArray;
constructor() public {
// maxExpArray[0] = 0x6bffffffffffffffffffffffffffffffff;
// maxExpArray[1] = 0x67ffffffffffffffffffffffffffffffff;
// maxExpArray[2] = 0x637fffffffffffffffffffffffffffffff;
// maxExpArray[3] = 0x5f6fffffffffffffffffffffffffffffff;
// maxExpArray[4] = 0x5b77ffffffffffffffffffffffffffffff;
// maxExpArray[5] = 0x57b3ffffffffffffffffffffffffffffff;
// maxExpArray[6] = 0x5419ffffffffffffffffffffffffffffff;
// maxExpArray[7] = 0x50a2ffffffffffffffffffffffffffffff;
// maxExpArray[8] = 0x4d517fffffffffffffffffffffffffffff;
// maxExpArray[9] = 0x4a233fffffffffffffffffffffffffffff;
// maxExpArray[10] = 0x47165fffffffffffffffffffffffffffff;
// maxExpArray[11] = 0x4429afffffffffffffffffffffffffffff;
// maxExpArray[12] = 0x415bc7ffffffffffffffffffffffffffff;
// maxExpArray[13] = 0x3eab73ffffffffffffffffffffffffffff;
// maxExpArray[14] = 0x3c1771ffffffffffffffffffffffffffff;
// maxExpArray[15] = 0x399e96ffffffffffffffffffffffffffff;
// maxExpArray[16] = 0x373fc47fffffffffffffffffffffffffff;
// maxExpArray[17] = 0x34f9e8ffffffffffffffffffffffffffff;
// maxExpArray[18] = 0x32cbfd5fffffffffffffffffffffffffff;
// maxExpArray[19] = 0x30b5057fffffffffffffffffffffffffff;
// maxExpArray[20] = 0x2eb40f9fffffffffffffffffffffffffff;
// maxExpArray[21] = 0x2cc8340fffffffffffffffffffffffffff;
// maxExpArray[22] = 0x2af09481ffffffffffffffffffffffffff;
// maxExpArray[23] = 0x292c5bddffffffffffffffffffffffffff;
// maxExpArray[24] = 0x277abdcdffffffffffffffffffffffffff;
// maxExpArray[25] = 0x25daf6657fffffffffffffffffffffffff;
// maxExpArray[26] = 0x244c49c65fffffffffffffffffffffffff;
// maxExpArray[27] = 0x22ce03cd5fffffffffffffffffffffffff;
// maxExpArray[28] = 0x215f77c047ffffffffffffffffffffffff;
// maxExpArray[29] = 0x1fffffffffffffffffffffffffffffffff;
// maxExpArray[30] = 0x1eaefdbdabffffffffffffffffffffffff;
// maxExpArray[31] = 0x1d6bd8b2ebffffffffffffffffffffffff;
maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff;
maxExpArray[42] = 0x1288c4161ce1dfffffffffffffffffffff;
maxExpArray[43] = 0x11c592761c666fffffffffffffffffffff;
maxExpArray[44] = 0x110a688680a757ffffffffffffffffffff;
maxExpArray[45] = 0x1056f1b5bedf77ffffffffffffffffffff;
maxExpArray[46] = 0x0faadceceeff8bffffffffffffffffffff;
maxExpArray[47] = 0x0f05dc6b27edadffffffffffffffffffff;
maxExpArray[48] = 0x0e67a5a25da4107fffffffffffffffffff;
maxExpArray[49] = 0x0dcff115b14eedffffffffffffffffffff;
maxExpArray[50] = 0x0d3e7a392431239fffffffffffffffffff;
maxExpArray[51] = 0x0cb2ff529eb71e4fffffffffffffffffff;
maxExpArray[52] = 0x0c2d415c3db974afffffffffffffffffff;
maxExpArray[53] = 0x0bad03e7d883f69bffffffffffffffffff;
maxExpArray[54] = 0x0b320d03b2c343d5ffffffffffffffffff;
maxExpArray[55] = 0x0abc25204e02828dffffffffffffffffff;
maxExpArray[56] = 0x0a4b16f74ee4bb207fffffffffffffffff;
maxExpArray[57] = 0x09deaf736ac1f569ffffffffffffffffff;
maxExpArray[58] = 0x0976bd9952c7aa957fffffffffffffffff;
maxExpArray[59] = 0x09131271922eaa606fffffffffffffffff;
maxExpArray[60] = 0x08b380f3558668c46fffffffffffffffff;
maxExpArray[61] = 0x0857ddf0117efa215bffffffffffffffff;
maxExpArray[62] = 0x07ffffffffffffffffffffffffffffffff;
maxExpArray[63] = 0x07abbf6f6abb9d087fffffffffffffffff;
maxExpArray[64] = 0x075af62cbac95f7dfa7fffffffffffffff;
maxExpArray[65] = 0x070d7fb7452e187ac13fffffffffffffff;
maxExpArray[66] = 0x06c3390ecc8af379295fffffffffffffff;
maxExpArray[67] = 0x067c00a3b07ffc01fd6fffffffffffffff;
maxExpArray[68] = 0x0637b647c39cbb9d3d27ffffffffffffff;
maxExpArray[69] = 0x05f63b1fc104dbd39587ffffffffffffff;
maxExpArray[70] = 0x05b771955b36e12f7235ffffffffffffff;
maxExpArray[71] = 0x057b3d49dda84556d6f6ffffffffffffff;
maxExpArray[72] = 0x054183095b2c8ececf30ffffffffffffff;
maxExpArray[73] = 0x050a28be635ca2b888f77fffffffffffff;
maxExpArray[74] = 0x04d5156639708c9db33c3fffffffffffff;
maxExpArray[75] = 0x04a23105873875bd52dfdfffffffffffff;
maxExpArray[76] = 0x0471649d87199aa990756fffffffffffff;
maxExpArray[77] = 0x04429a21a029d4c1457cfbffffffffffff;
maxExpArray[78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff;
maxExpArray[79] = 0x03eab73b3bbfe282243ce1ffffffffffff;
maxExpArray[80] = 0x03c1771ac9fb6b4c18e229ffffffffffff;
maxExpArray[81] = 0x0399e96897690418f785257fffffffffff;
maxExpArray[82] = 0x0373fc456c53bb779bf0ea9fffffffffff;
maxExpArray[83] = 0x034f9e8e490c48e67e6ab8bfffffffffff;
maxExpArray[84] = 0x032cbfd4a7adc790560b3337ffffffffff;
maxExpArray[85] = 0x030b50570f6e5d2acca94613ffffffffff;
maxExpArray[86] = 0x02eb40f9f620fda6b56c2861ffffffffff;
maxExpArray[87] = 0x02cc8340ecb0d0f520a6af58ffffffffff;
maxExpArray[88] = 0x02af09481380a0a35cf1ba02ffffffffff;
maxExpArray[89] = 0x0292c5bdd3b92ec810287b1b3fffffffff;
maxExpArray[90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff;
maxExpArray[91] = 0x025daf6654b1eaa55fd64df5efffffffff;
maxExpArray[92] = 0x0244c49c648baa98192dce88b7ffffffff;
maxExpArray[93] = 0x022ce03cd5619a311b2471268bffffffff;
maxExpArray[94] = 0x0215f77c045fbe885654a44a0fffffffff;
maxExpArray[95] = 0x01ffffffffffffffffffffffffffffffff;
maxExpArray[96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff;
maxExpArray[97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff;
maxExpArray[98] = 0x01c35fedd14b861eb0443f7f133fffffff;
maxExpArray[99] = 0x01b0ce43b322bcde4a56e8ada5afffffff;
maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff;
maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff;
maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff;
maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff;
maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff;
maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff;
maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff;
maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff;
maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff;
maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff;
maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff;
maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff;
maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff;
maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff;
maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff;
maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff;
maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff;
maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff;
maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff;
maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff;
maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff;
maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf;
maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df;
maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f;
maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037;
maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf;
maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9;
maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6;
}
/**
General Description:
Determine a value of precision.
Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
Return the result along with the precision used.
Detailed Description:
Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
The larger "precision" is, the more accurately this value represents the real value.
However, the larger "precision" is, the more bits are required in order to store this value.
And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
*/
function power(
uint256 _baseN,
uint256 _baseD,
uint32 _expN,
uint32 _expD
) internal view returns (uint256, uint8)
{
require(_baseN < MAX_NUM, "baseN exceeds max value.");
require(_baseN >= _baseD, "Bases < 1 are not supported.");
uint256 baseLog;
uint256 base = _baseN * FIXED_1 / _baseD;
if (base < OPT_LOG_MAX_VAL) {
baseLog = optimalLog(base);
} else {
baseLog = generalLog(base);
}
uint256 baseLogTimesExp = baseLog * _expN / _expD;
if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
return (optimalExp(baseLogTimesExp), MAX_PRECISION);
} else {
uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
}
}
/**
Compute log(x / FIXED_1) * FIXED_1.
This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
*/
function generalLog(uint256 _x) internal pure returns (uint256) {
uint256 res = 0;
uint256 x = _x;
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
x = (x * x) / FIXED_1; // now 1 < x < 4
if (x >= FIXED_2) {
x >>= 1; // now 1 < x < 2
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
/**
Compute the largest integer smaller than or equal to the binary logarithm of the input.
*/
function floorLog2(uint256 _n) internal pure returns (uint8) {
uint8 res = 0;
uint256 n = _n;
if (n < 256) {
// At most 8 iterations
while (n > 1) {
n >>= 1;
res += 1;
}
} else {
// Exactly 8 iterations
for (uint8 s = 128; s > 0; s >>= 1) {
if (n >= (ONE << s)) {
n >>= s;
res |= s;
}
}
}
return res;
}
/**
The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
- This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
- This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
*/
function findPositionInMaxExpArray(uint256 _x)
internal view returns (uint8)
{
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= _x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= _x)
return hi;
if (maxExpArray[lo] >= _x)
return lo;
assert(false);
return 0;
}
/* solhint-disable */
/**
This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'.
It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!".
It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy.
The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1".
The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
*/
function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) {
uint256 xi = _x;
uint256 res = 0;
xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!)
xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!)
xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!)
xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!)
xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!)
xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!)
xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!)
xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!)
xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!)
xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!)
xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!)
xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!)
xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!)
return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0!
}
/**
Return log(x / FIXED_1) * FIXED_1
Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalLog.py'
*/
function optimalLog(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
uint256 w;
if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;}
if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;}
if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;}
if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;}
if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;}
if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;}
if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;}
if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;}
z = y = x - FIXED_1;
w = y * y / FIXED_1;
res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1;
res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1;
res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1;
res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1;
res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1;
res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1;
res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1;
res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000;
return res;
}
/**
Return e ^ (x / FIXED_1) * FIXED_1
Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1
Auto-generated via 'PrintFunctionOptimalExp.py'
*/
function optimalExp(uint256 x) internal pure returns (uint256) {
uint256 res = 0;
uint256 y;
uint256 z;
z = y = x % 0x10000000000000000000000000000000;
z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!)
res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776;
if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4;
if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f;
if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9;
if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea;
if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d;
if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11;
return res;
}
/* solhint-enable */
}
/**
* @title Bancor formula by Bancor
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements;
* and to You under the Apache License, Version 2.0. "
*/
contract BancorFormula is Power {
using SafeMath for uint256;
uint32 private constant MAX_RESERVE_RATIO = 1000000;
/**
* @dev given a continuous token supply, reserve token balance, reserve ratio, and a deposit amount (in the reserve token),
* calculates the return for a given conversion (in the continuous token)
*
* Formula:
* Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / MAX_RESERVE_RATIO) - 1)
*
* @param _supply continuous token total supply
* @param _reserveBalance total reserve token balance
* @param _reserveRatio reserve ratio, represented in ppm, 1-1000000
* @param _depositAmount deposit amount, in reserve token
*
* @return purchase return amount
*/
function calculatePurchaseReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _depositAmount) public view returns (uint256)
{
// validate input
require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO, "Invalid inputs.");
// special case for 0 deposit amount
if (_depositAmount == 0) {
return 0;
}
// special case if the ratio = 100%
if (_reserveRatio == MAX_RESERVE_RATIO) {
return _supply.mul(_depositAmount).div(_reserveBalance);
}
uint256 result;
uint8 precision;
uint256 baseN = _depositAmount.add(_reserveBalance);
(result, precision) = power(
baseN, _reserveBalance, _reserveRatio, MAX_RESERVE_RATIO
);
uint256 newTokenSupply = _supply.mul(result) >> precision;
return newTokenSupply.sub(_supply);
}
/**
* @dev given a continuous token supply, reserve token balance, reserve ratio and a sell amount (in the continuous token),
* calculates the return for a given conversion (in the reserve token)
*
* Formula:
* Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / MAX_RESERVE_RATIO)))
*
* @param _supply continuous token total supply
* @param _reserveBalance total reserve token balance
* @param _reserveRatio constant reserve ratio, represented in ppm, 1-1000000
* @param _sellAmount sell amount, in the continuous token itself
*
* @return sale return amount
*/
function calculateSaleReturn(
uint256 _supply,
uint256 _reserveBalance,
uint32 _reserveRatio,
uint256 _sellAmount) public view returns (uint256)
{
// validate input
require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO && _sellAmount <= _supply, "Invalid inputs.");
// special case for 0 sell amount
if (_sellAmount == 0) {
return 0;
}
// special case for selling the entire supply
if (_sellAmount == _supply) {
return _reserveBalance;
}
// special case if the ratio = 100%
if (_reserveRatio == MAX_RESERVE_RATIO) {
return _reserveBalance.mul(_sellAmount).div(_supply);
}
uint256 result;
uint8 precision;
uint256 baseD = _supply.sub(_sellAmount);
(result, precision) = power(
_supply, baseD, MAX_RESERVE_RATIO, _reserveRatio
);
uint256 oldBalance = _reserveBalance.mul(result);
uint256 newBalance = _reserveBalance << precision;
return oldBalance.sub(newBalance).div(result);
}
}
interface IBondingCurve {
/**
* @dev Given a reserve token amount, calculates the amount of continuous tokens returned.
*/
function getContinuousMintReward(uint _reserveTokenAmount) external view returns (uint);
/**
* @dev Given a continuous token amount, calculates the amount of reserve tokens returned.
*/
function getContinuousBurnRefund(uint _continuousTokenAmount) external view returns (uint);
}
abstract contract BancorBondingCurve is IBondingCurve, BancorFormula {
/*
reserve ratio, represented in ppm, 1-1000000
1/3 corresponds to y= multiple * x^2
1/2 corresponds to y= multiple * x
2/3 corresponds to y= multiple * x^1/2
*/
uint32 public reserveRatio;
constructor(uint32 _reserveRatio) public {
reserveRatio = _reserveRatio;
}
function getContinuousMintReward(uint _reserveTokenAmount) public override view returns (uint) {
return calculatePurchaseReturn(continuousSupply(), reserveBalance(), reserveRatio, _reserveTokenAmount);
}
function getContinuousBurnRefund(uint _continuousTokenAmount) public override view returns (uint) {
return calculateSaleReturn(continuousSupply(), reserveBalance(), reserveRatio, _continuousTokenAmount);
}
/**
* @dev Abstract method that returns continuous token supply
*/
function continuousSupply() public virtual view returns (uint);
/**
* @dev Abstract method that returns reserve token balance
*/
function reserveBalance() public virtual view returns (uint);
}
contract BIOPTokenV3 is BancorBondingCurve, ERC20 {
using SafeMath for uint256;
address public bO = 0x0000000000000000000000000000000000000000;//binary options
address payable gov = 0x0000000000000000000000000000000000000000;
address payable owner;
address public v2;
uint256 lEnd;//launch end
uint256 public tCA = 750000000000000000000000000000;//total claims available
uint256 public tbca = 400000000000000000000000000000;//total bonding curve available
bool public binaryOptionsSet = false;
uint256 public soldAmount = 0;
uint256 public buyFee = 2;//10th of percent
uint256 public sellFee = 0;//10th of percent
constructor(string memory name_, string memory symbol_, address v2_, uint32 _reserveRatio) public ERC20(name_, symbol_) BancorBondingCurve(_reserveRatio) {
owner = msg.sender;
v2 = v2_;
lEnd = block.timestamp + 3 days;
_mint(msg.sender, 100000);
soldAmount = 100000;
}
modifier onlyBinaryOptions() {
require(bO == msg.sender, "Ownable: caller is not the Binary Options Contract");
_;
}
modifier onlyGov() {
if (gov == 0x0000000000000000000000000000000000000000) {
require(owner == msg.sender, "Ownable: caller is not the owner");
} else {
require(gov == msg.sender, "Ownable: caller is not the owner");
}
_;
}
/**
* @dev a one time function to setup governance
* @param g_ the new governance address
*/
function transferGovernance(address payable g_) external onlyGov {
require(gov == 0x0000000000000000000000000000000000000000);
require(g_ != 0x0000000000000000000000000000000000000000);
gov = g_;
}
/**
* @dev set the fee users pay in ETH to buy BIOP from the bonding curve
* @param newFee_ the new fee (in tenth percent) for buying on the curve
*/
function updateBuyFee(uint256 newFee_) external onlyGov {
require(newFee_ > 0 && newFee_ < 40, "invalid fee");
buyFee = newFee_;
}
/**
* @dev set the fee users pay in ETH to sell BIOP to the bonding curve
* @param newFee_ the new fee (in tenth percent) for selling on the curve
**/
function updateSellFee(uint256 newFee_) external onlyGov {
require(newFee_ > 0 && newFee_ < 40, "invalid fee");
sellFee = newFee_;
}
/**
* @dev called by the binary options contract to update a users Reward claim
* @param amount the amount in BIOP to add to this users pending claims
**/
function updateEarlyClaim(uint256 amount) external onlyBinaryOptions {
require(tCA.sub(amount) >= 0, "insufficent claims available");
if (lEnd < block.timestamp) {
tCA = tCA.sub(amount);
_mint(tx.origin, amount.mul(4));
} else {
tCA.sub(amount);
_mint(tx.origin, amount);
}
}
/**
* @notice one time function used at deployment to configure the connected binary options contract
* @param options_ the address of the binary options contract
*/
function setupBinaryOptions(address payable options_) external {
require(binaryOptionsSet != true, "binary options is already set");
bO = options_;
binaryOptionsSet = true;
}
/**
* @dev one time swap of v2 to v3 tokens
* @notice all v2 tokens will be swapped to v3. This cannot be undone
*/
function swapv2v3() external {
BIOPToken b2 = BIOPToken(v2);
uint256 balance = b2.balanceOf(msg.sender);
require(balance >= 0, "insufficent biopv2 balance");
require(b2.transferFrom(msg.sender, address(this), balance), "staking failed");
_mint(msg.sender, balance);
}
//bonding curve functions
/**
* @dev method that returns BIOP amount sold by curve
*/
function continuousSupply() public override view returns (uint) {
return soldAmount;
}
/**
* @dev method that returns curves ETH (reserve) balance
*/
function reserveBalance() public override view returns (uint) {
return address(this).balance;
}
/**
* @notice purchase BIOP from the bonding curve.
the amount you get is based on the amount in the pool and the amount of eth u send.
*/
function buy() public payable {
uint256 purchaseAmount = msg.value;
if (buyFee > 0) {
uint256 fee = purchaseAmount.div(buyFee).div(100);
if (gov == 0x0000000000000000000000000000000000000000) {
require(owner.send(fee), "buy fee transfer failed");
} else {
require(gov.send(fee), "buy fee transfer failed");
}
purchaseAmount = purchaseAmount.sub(fee);
}
uint rewardAmount = getContinuousMintReward(purchaseAmount);
require(soldAmount.add(rewardAmount) <= tbca, "maximum curve minted");
_mint(msg.sender, rewardAmount);
soldAmount = soldAmount.add(rewardAmount);
}
/**
* @notice sell BIOP to the bonding curve
* @param amount the amount of BIOP to sell
*/
function sell(uint256 amount) public returns (uint256){
require(balanceOf(msg.sender) >= amount, "insufficent BIOP balance");
uint256 ethToSend = getContinuousBurnRefund(amount);
if (sellFee > 0) {
uint256 fee = ethToSend.div(buyFee).div(100);
if (gov == 0x0000000000000000000000000000000000000000) {
require(owner.send(fee), "buy fee transfer failed");
} else {
require(gov.send(fee), "buy fee transfer failed");
}
ethToSend = ethToSend.sub(fee);
}
soldAmount = soldAmount.sub(amount);
_burn(msg.sender, amount);
require(msg.sender.send(ethToSend), "transfer failed");
return ethToSend;
}
}
interface IRCD {
/**
* @notice Returns the rate to pay out for a given amount
* @param amount the bet amount to calc a payout for
* @param maxAvailable the total pooled ETH unlocked and available to bet
* @param oldPrice the previous price of the underlying
* @param newPrice the current price of the underlying
* @return profit total possible profit amount
*/
function rate(uint256 amount, uint256 maxAvailable, uint256 oldPrice, uint256 newPrice) external view returns (uint256);
}
contract RateCalc is IRCD {
using SafeMath for uint256;
/**
* @notice Calculates maximum option buyer profit
* @param amount Option amount
* @param maxAvailable the total pooled ETH unlocked and available to bet
* @param oldPrice the previous price of the underlying
* @param newPrice the current price of the underlying
* @return profit total possible profit amount
*/
function rate(uint256 amount, uint256 maxAvailable, uint256 oldPrice, uint256 newPrice) external view override returns (uint256) {
require(amount <= maxAvailable, "greater then pool funds available");
uint256 oneTenth = amount.div(10);
uint256 halfMax = maxAvailable.div(2);
if (amount > halfMax) {
return amount.mul(2).add(oneTenth).add(oneTenth);
} else {
if(oneTenth > 0) {
return amount.mul(2).sub(oneTenth);
} else {
uint256 oneThird = amount.div(4);
require(oneThird > 0, "invalid bet amount");
return amount.mul(2).sub(oneThird);
}
}
}
}
/**
* @title Binary Options Eth Pool
* @author github.com/BIOPset
* @dev Pool ETH Tokens and use it for optionss
* Biop
*/
contract BinaryOptions is ERC20 {
using SafeMath for uint256;
address payable devFund;
address payable owner;
address public biop;
address public defaultRCAddress;//address of default rate calculator
mapping(address=>uint256) public nW; //next withdraw (used for pool lock time)
mapping(address=>address) public ePairs;//enabled pairs. price provider mapped to rate calc
mapping(address=>int256) public pLP; //pair last price. the last recorded price for this pair
mapping(address=>uint256) public lW;//last withdraw.used for rewards calc
mapping(address=>uint256) private pClaims;//pending claims
mapping(address=>uint256) public iAL;//interchange at last claim
mapping(address=>uint256) public lST;//last stake time
//erc20 pools stuff
mapping(address=>bool) public ePools;//enabled pools
mapping(address=>uint256) public altLockedAmount;
uint256 public minT;//min time
uint256 public maxT;//max time
address public defaultPair;
uint256 public lockedAmount;
uint256 public exerciserFee = 50;//in tenth percent
uint256 public expirerFee = 50;//in tenth percent
uint256 public devFundBetFee = 2;//tenth of percent
uint256 public poolLockSeconds = 7 days;
uint256 public contractCreated;
bool public open = true;
Option[] public options;
uint256 public tI = 0;//total interchange
//reward amounts
uint256 public fGS =400000000000000;//first gov stake reward
uint256 public reward = 200000000000000;
bool public rewEn = true;//rewards enabled
modifier onlyOwner() {
require(owner == msg.sender, "Ownable: caller is not the owner");
_;
}
/* Types */
enum OptionType {Put, Call}
struct Option {
address payable holder;
int256 sPrice;//strike
uint256 pValue;//purchase
uint256 lValue;//purchaseAmount+possible reward for correct bet
uint256 exp;//expiration
OptionType dir;//direction
address pP;//price provider
address altPA;//alt pool address
}
/* Events */
event Create(
uint256 indexed id,
address payable account,
int256 sPrice,//strike
uint256 lValue,//locked value
OptionType dir,
bool alt
);
event Payout(uint256 poolLost, address winner);
event Exercise(uint256 indexed id);
event Expire(uint256 indexed id);
constructor(string memory name_, string memory symbol_, address pp_, address biop_, address rateCalc_) public ERC20(name_, symbol_){
devFund = msg.sender;
owner = msg.sender;
biop = biop_;
defaultRCAddress = rateCalc_;
lockedAmount = 0;
contractCreated = block.timestamp;
ePairs[pp_] = defaultRCAddress; //default pair ETH/USD
defaultPair = pp_;
minT = 900;//15 minutes
maxT = 60 minutes;
}
function getMaxAvailable() public view returns(uint256) {
uint256 balance = address(this).balance;
if (balance > lockedAmount) {
return balance.sub(lockedAmount);
} else {
return 0;
}
}
function getAltMaxAvailable(address erc20PoolAddress_) public view returns(uint256) {
ERC20 alt = ERC20(erc20PoolAddress_);
uint256 balance = alt.balanceOf(address(this));
if (balance > altLockedAmount[erc20PoolAddress_]) {
return balance.sub( altLockedAmount[erc20PoolAddress_]);
} else {
return 0;
}
}
function getOptionCount() public view returns(uint256) {
return options.length;
}
function getStakingTimeBonus(address account) public view returns(uint256) {
uint256 dif = block.timestamp.sub(lST[account]);
uint256 bonus = dif.div(777600);//9 days
if (dif < 777600) {
return 1;
}
return bonus;
}
function getPoolBalanceBonus(address account) public view returns(uint256) {
uint256 balance = balanceOf(account);
if (balance > 0) {
if (totalSupply() < 100) { //guard
return 1;
}
if (balance >= totalSupply().div(2)) {//50th percentile
return 20;
}
if (balance >= totalSupply().div(4)) {//25th percentile
return 14;
}
if (balance >= totalSupply().div(5)) {//20th percentile
return 10;
}
if (balance >= totalSupply().div(10)) {//10th percentile
return 8;
}
if (balance >= totalSupply().div(20)) {//5th percentile
return 6;
}
if (balance >= totalSupply().div(50)) {//2nd percentile
return 4;
}
if (balance >= totalSupply().div(100)) {//1st percentile
return 3;
}
return 2;
}
return 1;
}
function getOptionValueBonus(address account) public view returns(uint256) {
uint256 dif = tI.sub(iAL[account]);
uint256 bonus = dif.div(1000000000000000000);//1ETH
if(bonus > 0){
return bonus;
}
return 0;
}
//used for betting/exercise/expire calc
function getBetSizeBonus(uint256 amount, uint256 base) public view returns(uint256) {
uint256 betPercent = totalSupply().mul(100).div(amount);
if(base.mul(betPercent).div(10) > 0){
return base.mul(betPercent).div(10);
}
return base.div(1000);
}
function getCombinedStakingBonus(address account) public view returns(uint256) {
return reward
.mul(getStakingTimeBonus(account))
.mul(getPoolBalanceBonus(account))
.mul(getOptionValueBonus(account));
}
function getPendingClaims(address account) public view returns(uint256) {
if (balanceOf(account) > 1) {
//staker reward bonus
//base*(weeks)*(poolBalanceBonus/10)*optionsBacked
return pClaims[account].add(
getCombinedStakingBonus(account)
);
} else {
//normal rewards
return pClaims[account];
}
}
function updateLPmetrics() internal {
lST[msg.sender] = block.timestamp;
iAL[msg.sender] = tI;
}
/**
* @dev distribute pending governance token claims to user
*/
function claimRewards() external {
BIOPTokenV3 b = BIOPTokenV3(biop);
uint256 claims = getPendingClaims(msg.sender);
if (balanceOf(msg.sender) > 1) {
updateLPmetrics();
}
pClaims[msg.sender] = 0;
b.updateEarlyClaim(claims);
}
/**
* @dev the default price provider. This is a convenience method
*/
function defaultPriceProvider() public view returns (address) {
return defaultPair;
}
/**
* @dev add a pool
* @param newPool_ the address EBOP20 pool to add
*/
function addAltPool(address newPool_) external onlyOwner {
ePools[newPool_] = true;
}
/**
* @dev enable or disable BIOP rewards
* @param nx_ the new position for the rewEn switch
*/
function enableRewards(bool nx_) external onlyOwner {
rewEn = nx_;
}
/**
* @dev remove a pool
* @param oldPool_ the address EBOP20 pool to remove
*/
function removeAltPool(address oldPool_) external onlyOwner {
ePools[oldPool_] = false;
}
/**
* @dev add or update a price provider to the ePairs list.
* @param newPP_ the address of the AggregatorProxy price provider contract address to add.
* @param rateCalc_ the address of the RateCalc to use with this trading pair.
*/
function addPP(address newPP_, address rateCalc_) external onlyOwner {
ePairs[newPP_] = rateCalc_;
}
/**
* @dev remove a price provider from the ePairs list
* @param oldPP_ the address of the AggregatorProxy price provider contract address to remove.
*/
function removePP(address oldPP_) external onlyOwner {
ePairs[oldPP_] = 0x0000000000000000000000000000000000000000;
}
/**
* @dev update the max time for option bets
* @param newMax_ the new maximum time (in seconds) an option may be created for (inclusive).
*/
function setMaxT(uint256 newMax_) external onlyOwner {
maxT = newMax_;
}
/**
* @dev update the max time for option bets
* @param newMin_ the new minimum time (in seconds) an option may be created for (inclusive).
*/
function setMinT(uint256 newMin_) external onlyOwner {
minT = newMin_;
}
/**
* @dev address of this contract, convenience method
*/
function thisAddress() public view returns (address){
return address(this);
}
/**
* @dev set the fee users can recieve for exercising other users options
* @param exerciserFee_ the new fee (in tenth percent) for exercising a options itm
*/
function updateExerciserFee(uint256 exerciserFee_) external onlyOwner {
require(exerciserFee_ > 1 && exerciserFee_ < 500, "invalid fee");
exerciserFee = exerciserFee_;
}
/**
* @dev set the fee users can recieve for expiring other users options
* @param expirerFee_ the new fee (in tenth percent) for expiring a options
*/
function updateExpirerFee(uint256 expirerFee_) external onlyOwner {
require(expirerFee_ > 1 && expirerFee_ < 50, "invalid fee");
expirerFee = expirerFee_;
}
/**
* @dev set the fee users pay to buy an option
* @param devFundBetFee_ the new fee (in tenth percent) to buy an option
*/
function updateDevFundBetFee(uint256 devFundBetFee_) external onlyOwner {
require(devFundBetFee_ >= 0 && devFundBetFee_ < 50, "invalid fee");
devFundBetFee = devFundBetFee_;
}
/**
* @dev update the pool stake lock up time.
* @param newLockSeconds_ the new lock time, in seconds
*/
function updatePoolLockSeconds(uint256 newLockSeconds_) external onlyOwner {
require(newLockSeconds_ >= 0 && newLockSeconds_ < 14 days, "invalid fee");
poolLockSeconds = newLockSeconds_;
}
/**
* @dev used to transfer ownership
* @param newOwner_ the address of governance contract which takes over control
*/
function transferOwner(address payable newOwner_) external onlyOwner {
owner = newOwner_;
}
/**
* @dev used to transfer devfund
* @param newDevFund the address of governance contract which takes over control
*/
function transferDevFund(address payable newDevFund) external onlyOwner {
devFund = newDevFund;
}
/**
* @dev used to send this pool into EOL mode when a newer one is open
*/
function closeStaking() external onlyOwner {
open = false;
}
/**
* @dev send ETH to the pool. Recieve pETH token representing your claim.
* If rewards are available recieve BIOP governance tokens as well.
*/
function stake() external payable {
require(open == true, "pool deposits has closed");
require(msg.value >= 100, "stake to small");
if (balanceOf(msg.sender) == 0) {
lW[msg.sender] = block.timestamp;
pClaims[msg.sender] = pClaims[msg.sender].add(fGS);
}
updateLPmetrics();
nW[msg.sender] = block.timestamp + poolLockSeconds;//this one is seperate because it isn't updated on reward claim
_mint(msg.sender, msg.value);
}
/**
* @dev recieve ETH from the pool.
* If the current time is before your next available withdraw a 1% fee will be applied.
* @param amount The amount of pETH to send the pool.
*/
function withdraw(uint256 amount) public {
require (balanceOf(msg.sender) >= amount, "Insufficent Share Balance");
lW[msg.sender] = block.timestamp;
uint256 valueToRecieve = amount.mul(address(this).balance).div(totalSupply());
_burn(msg.sender, amount);
if (block.timestamp <= nW[msg.sender]) {
//early withdraw fee
uint256 penalty = valueToRecieve.div(100);
require(devFund.send(penalty), "transfer failed");
require(msg.sender.send(valueToRecieve.sub(penalty)), "transfer failed");
} else {
require(msg.sender.send(valueToRecieve), "transfer failed");
}
}
/**
@dev helper for getting rate
@param pair the price provider
@param max max pool available
@param deposit bet amount
*/
function getRate(address pair,uint256 max, uint256 deposit, int256 currentPrice) public view returns (uint256) {
RateCalc rc = RateCalc(ePairs[pair]);
return rc.rate(deposit, max.sub(deposit), uint256(pLP[pair]), uint256(currentPrice));
}
/**
@dev Open a new call or put options.
@param type_ type of option to buy
@param pp_ the address of the price provider to use (must be in the list of ePairs)
@param time_ the time until your options expiration (must be minT < time_ > maxT)
@param altPA_ address of alt pool. pass address of this contract to use ETH pool
@param altA_ bet amount. only used if altPA_ != address(this)
*/
function bet(OptionType type_, address pp_, uint256 time_, address altPA_, uint256 altA_) external payable {
require(
type_ == OptionType.Call || type_ == OptionType.Put,
"Wrong option type"
);
require(
time_ >= minT && time_ <= maxT,
"Invalid time"
);
require(ePairs[pp_] != 0x0000000000000000000000000000000000000000, "Invalid price provider");
AggregatorProxy priceProvider = AggregatorProxy(pp_);
int256 latestPrice = priceProvider.latestAnswer();
uint256 depositValue;
uint256 lockTotal;
uint256 optionID = options.length;
if (altPA_ != address(this)) {
//do stuff specific to erc20 pool instead
require(ePools[altPA_], "invalid pool");
IEBOP20 altPool = IEBOP20(altPA_);
require(altPool.balanceOf(msg.sender) >= altA_, "invalid pool");
(depositValue, lockTotal) = altPool.bet(latestPrice, altA_);
} else {
//normal eth bet
require(msg.value >= 100, "bet to small");
require(msg.value <= getMaxAvailable(), "bet to big");
//an optional (to be choosen by contract owner) fee on each option.
//A % of the bet money is sent as a fee. see devFundBetFee
if (devFundBetFee > 0) {
uint256 fee = msg.value.div(devFundBetFee).div(100);
require(devFund.send(fee), "devFund fee transfer failed");
depositValue = msg.value.sub(fee);
} else {
depositValue = msg.value;
}
uint256 lockValue = getRate(pp_, getMaxAvailable(), depositValue, latestPrice);
if (rewEn) {
pClaims[msg.sender] = pClaims[msg.sender].add(getBetSizeBonus(depositValue, reward));
}
lockTotal = lockValue.add(depositValue);
lock(lockTotal);
}
if (latestPrice != pLP[pp_]) {
pLP[pp_] = latestPrice;
}
Option memory op = Option(
msg.sender,
latestPrice,//*
depositValue,
//*
lockTotal,//*
block.timestamp + time_,//time till expiration
type_,
pp_,
altPA_
);
options.push(op);
tI = tI.add(lockTotal);
emit Create(optionID, msg.sender, latestPrice, lockTotal, type_, altPA_ == address(this));
}
/**
* @notice exercises a option
* @param optionID id of the option to exercise
*/
function exercise(uint256 optionID)
external
{
Option memory option = options[optionID];
require(block.timestamp <= option.exp, "expiration date margin has passed");
AggregatorProxy priceProvider = AggregatorProxy(option.pP);
int256 latestPrice = priceProvider.latestAnswer();
//ETH bet
if (option.dir == OptionType.Call) {
require(latestPrice > option.sPrice, "price is to low");
} else {
require(latestPrice < option.sPrice, "price is to high");
}
if (option.altPA != address(this)) {
IEBOP20 alt = IEBOP20(option.altPA);
require(alt.payout(option.lValue,option.pValue, msg.sender, option.holder), "erc20 pool exercise failed");
} else {
//option expires ITM, we pay out
payout(option.lValue, msg.sender, option.holder);
lockedAmount = lockedAmount.sub(option.lValue);
}
emit Exercise(optionID);
if (rewEn) {
pClaims[msg.sender] = pClaims[msg.sender].add(getBetSizeBonus(option.lValue, reward));
}
}
/**
* @notice expires a option
* @param optionID id of the option to expire
*/
function expire(uint256 optionID)
external
{
Option memory option = options[optionID];
require(block.timestamp > option.exp, "expiration date has not passed");
if (option.altPA != address(this)) {
//ERC20 option
IEBOP20 alt = IEBOP20(option.altPA);
require(alt.unlockAndPayExpirer(option.lValue,option.pValue, msg.sender), "erc20 pool exercise failed");
} else {
//ETH option
unlock(option.lValue, msg.sender);
lockedAmount = lockedAmount.sub(option.lValue);
}
emit Expire(optionID);
if (rewEn) {
pClaims[msg.sender] = pClaims[msg.sender].add(getBetSizeBonus(option.pValue, reward));
}
}
/**
@dev called by BinaryOptions contract to lock pool value coresponding to new binary options bought.
@param amount amount in ETH to lock from the pool total.
*/
function lock(uint256 amount) internal {
lockedAmount = lockedAmount.add(amount);
}
/**
@dev called by BinaryOptions contract to unlock pool value coresponding to an option expiring otm.
@param amount amount in ETH to unlock
@param goodSamaritan the user paying to unlock these funds, they recieve a fee
*/
function unlock(uint256 amount, address payable goodSamaritan) internal {
require(amount <= lockedAmount, "insufficent locked pool balance to unlock");
uint256 fee;
if (amount <= 10000000000000000) {//small options give bigger fee %
fee = amount.div(exerciserFee.mul(4)).div(100);
} else {
fee = amount.div(exerciserFee).div(100);
}
if (fee > 0) {
require(goodSamaritan.send(fee), "good samaritan transfer failed");
}
}
/**
@dev called by BinaryOptions contract to payout pool value coresponding to binary options expiring itm.
@param amount amount in ETH to unlock
@param exerciser address calling the exercise/expire function, this may the winner or another user who then earns a fee.
@param winner address of the winner.
@notice exerciser fees are subject to change see updateFeePercent above.
*/
function payout(uint256 amount, address payable exerciser, address payable winner) internal {
require(amount <= lockedAmount, "insufficent pool balance available to payout");
require(amount <= address(this).balance, "insufficent balance in pool");
if (exerciser != winner) {
//good samaratin fee
uint256 fee;
if (amount <= 10000000000000000) {//small options give bigger fee %
fee = amount.div(exerciserFee.mul(4)).div(100);
} else {
fee = amount.div(exerciserFee).div(100);
}
if (fee > 0) {
require(exerciser.send(fee), "exerciser transfer failed");
require(winner.send(amount.sub(fee)), "winner transfer failed");
}
} else {
require(winner.send(amount), "winner transfer failed");
}
emit Payout(amount, winner);
}
} | sell BIOP to the bonding curve amount the amount of BIOP to sell/ | function sell(uint256 amount) public returns (uint256){
require(balanceOf(msg.sender) >= amount, "insufficent BIOP balance");
uint256 ethToSend = getContinuousBurnRefund(amount);
if (sellFee > 0) {
uint256 fee = ethToSend.div(buyFee).div(100);
if (gov == 0x0000000000000000000000000000000000000000) {
require(owner.send(fee), "buy fee transfer failed");
require(gov.send(fee), "buy fee transfer failed");
}
ethToSend = ethToSend.sub(fee);
}
soldAmount = soldAmount.sub(amount);
_burn(msg.sender, amount);
require(msg.sender.send(ethToSend), "transfer failed");
return ethToSend;
}
| 2,186,479 |
./full_match/1/0x85979c90D53E20E4505C83d9408b8A61Beb8db1F/sources/contracts/Aladdin.sol | Update sender's state. | function _transferToExcluded(address sender,address recipient,uint256 amount) private{
updateWeight(sender);
uint256 uBalance;
if(_liquidWeight==0){
uBalance=_balances[sender];
uBalance=_balances[sender].add(_balances[address(this)].mul(_userWeight[sender]).div(_liquidWeight));
}
require(uBalance>=amount,"ERC20:");
uint256 uAmout =_balances[sender].mul(amount).div(uBalance);
uint256 pAmout = amount.sub(uAmout);
uint256 subWeight = _userWeight[sender].mul(amount).div(uBalance);
_userWeight[sender]=_userWeight[sender].sub(subWeight);
_liquidWeight=_liquidWeight.sub(subWeight);
emit Transfer(sender,recipient,amount);
}
| 9,732,629 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Copyright 2021 Archer DAO: Chris Piatt ([emailΒ protected]).
*/
import "./lib/0.8/AccessControlUpgradeable.sol";
import "./lib/0.8/CheckAndSend.sol";
/**
* @title TipJar
* @dev Allows suppliers to create a tip that gets distributed to miners + the network
*/
contract TipJar is AccessControlUpgradeable, CheckAndSend {
/// @notice TipJar Admin role
bytes32 public constant TIP_JAR_ADMIN_ROLE = keccak256("TIP_JAR_ADMIN_ROLE");
/// @notice Fee setter role
bytes32 public constant FEE_SETTER_ROLE = keccak256("FEE_SETTER_ROLE");
/// @notice Network fee (measured in bips: 10,000 bips = 1% of contract balance)
uint32 public networkFee;
/// @notice Network fee output address
address public networkFeeCollector;
/// @notice Miner split
struct Split {
address splitTo;
uint32 splitPct;
}
/// @notice Miner split mapping
mapping (address => Split) public minerSplits;
/// @notice Fee set event
event FeeSet(uint32 indexed newFee, uint32 indexed oldFee);
/// @notice Fee collector set event
event FeeCollectorSet(address indexed newCollector, address indexed oldCollector);
/// @notice Miner split updated event
event MinerSplitUpdated(address indexed miner, address indexed newSplitTo, address indexed oldSplitTo, uint32 newSplit, uint32 oldSplit);
/// @notice Tip event
event Tip(address indexed miner, address indexed tipper, uint256 tipAmount, uint256 splitAmount, uint256 feeAmount, address feeCollector);
/// @notice modifier to restrict functions to admins
modifier onlyAdmin() {
require(hasRole(TIP_JAR_ADMIN_ROLE, msg.sender), "Caller must have TIP_JAR_ADMIN_ROLE role");
_;
}
/// @notice modifier to restrict functions to miners or admin
modifier onlyMinerOrAdmin(address miner) {
require(msg.sender == miner || hasRole(TIP_JAR_ADMIN_ROLE, msg.sender), "Caller must be miner or have TIP_JAR_ADMIN_ROLE role");
_;
}
/// @notice modifier to restrict functions to fee setters
modifier onlyFeeSetter() {
require(hasRole(FEE_SETTER_ROLE, msg.sender), "Caller must have FEE_SETTER_ROLE role");
_;
}
/// @notice Initializes contract, setting admin roles + network fee
/// @param _tipJarAdmin admin of tip pool
/// @param _feeSetter fee setter address
/// @param _networkFeeCollector address that collects network fees
/// @param _networkFee % of fee collected by the network
function initialize(
address _tipJarAdmin,
address _feeSetter,
address _networkFeeCollector,
uint32 _networkFee
) public initializer {
_setRoleAdmin(TIP_JAR_ADMIN_ROLE, TIP_JAR_ADMIN_ROLE);
_setRoleAdmin(FEE_SETTER_ROLE, TIP_JAR_ADMIN_ROLE);
_setupRole(TIP_JAR_ADMIN_ROLE, _tipJarAdmin);
_setupRole(FEE_SETTER_ROLE, _feeSetter);
networkFeeCollector = _networkFeeCollector;
emit FeeCollectorSet(_networkFeeCollector, address(0));
networkFee = _networkFee;
emit FeeSet(_networkFee, 0);
}
/// @notice Receive function to allow contract to accept ETH
receive() external payable {}
/// @notice Fallback function to allow contract to accept ETH
fallback() external payable {}
/**
* @notice Check that contract call results in specific 32 bytes value, then transfer ETH
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function check32BytesAndSend(
address _target,
bytes calldata _payload,
bytes32 _resultMatch
) external payable {
_check32Bytes(_target, _payload, _resultMatch);
}
/**
* @notice Check that contract call results in specific 32 bytes value, then tip
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function check32BytesAndTip(
address _target,
bytes calldata _payload,
bytes32 _resultMatch
) external payable {
_check32Bytes(_target, _payload, _resultMatch);
tip();
}
/**
* @notice Check that multiple contract calls result in specific 32 bytes value, then transfer ETH
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function check32BytesAndSendMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes32[] calldata _resultMatches
) external payable {
_check32BytesMulti(_targets, _payloads, _resultMatches);
}
/**
* @notice Check that multiple contract calls result in specific 32 bytes value, then tip
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function check32BytesAndTipMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes32[] calldata _resultMatches
) external payable {
_check32BytesMulti(_targets, _payloads, _resultMatches);
tip();
}
/**
* @notice Check that contract call results in specific bytes value, then transfer ETH
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function checkBytesAndSend(
address _target,
bytes calldata _payload,
bytes calldata _resultMatch
) external payable {
_checkBytes(_target, _payload, _resultMatch);
}
/**
* @notice Check that contract call results in specific bytes value, then tip
* @param _target target contract
* @param _payload contract call bytes
* @param _resultMatch result to match
*/
function checkBytesAndTip(
address _target,
bytes calldata _payload,
bytes calldata _resultMatch
) external payable {
_checkBytes(_target, _payload, _resultMatch);
tip();
}
/**
* @notice Check that multiple contract calls result in specific bytes value, then transfer ETH
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function checkBytesAndSendMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes[] calldata _resultMatches
) external payable {
_checkBytesMulti(_targets, _payloads, _resultMatches);
}
/**
* @notice Check that multiple contract calls result in specific bytes value, then tip
* @param _targets target contracts
* @param _payloads contract call bytes
* @param _resultMatches results to match
*/
function checkBytesAndTipMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes[] calldata _resultMatches
) external payable {
_checkBytesMulti(_targets, _payloads, _resultMatches);
tip();
}
/**
* @notice Distributes any ETH in contract to relevant parties
*/
function tip() public payable {
uint256 tipAmount;
uint256 feeAmount;
uint256 splitAmount;
if (networkFee > 0) {
feeAmount = (address(this).balance * networkFee) / 1000000;
(bool feeSuccess, ) = networkFeeCollector.call{value: feeAmount}("");
require(feeSuccess, "Could not collect fee");
}
if(minerSplits[block.coinbase].splitPct > 0) {
splitAmount = (address(this).balance * minerSplits[block.coinbase].splitPct) / 1000000;
(bool splitSuccess, ) = minerSplits[block.coinbase].splitTo.call{value: splitAmount}("");
require(splitSuccess, "Could not split");
}
if (address(this).balance > 0) {
tipAmount = address(this).balance;
(bool success, ) = block.coinbase.call{value: tipAmount}("");
require(success, "Could not collect ETH");
}
emit Tip(block.coinbase, msg.sender, tipAmount, splitAmount, feeAmount, networkFeeCollector);
}
/**
* @notice Admin function to set network fee
* @param newFee new fee
*/
function setFee(uint32 newFee) external onlyFeeSetter {
require(newFee <= 1000000, ">100%");
emit FeeSet(newFee, networkFee);
networkFee = newFee;
}
/**
* @notice Admin function to set fee collector address
* @param newCollector new fee collector address
*/
function setFeeCollector(address newCollector) external onlyAdmin {
emit FeeCollectorSet(newCollector, networkFeeCollector);
networkFeeCollector = newCollector;
}
/**
* @notice Update split % and split to address for given miner
* @param minerAddress Address of miner
* @param splitTo Address that receives split
* @param splitPct % of tip that splitTo receives
*/
function updateMinerSplit(
address minerAddress,
address splitTo,
uint32 splitPct
) external onlyMinerOrAdmin(minerAddress) {
Split memory oldSplit = minerSplits[minerAddress];
address oldSplitTo = oldSplit.splitTo;
uint32 oldSplitPct = oldSplit.splitPct;
minerSplits[minerAddress] = Split({
splitTo: splitTo,
splitPct: splitPct
});
emit MinerSplitUpdated(minerAddress, splitTo, oldSplitTo, splitPct, oldSplitPct);
}
}
// 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 IERC165Upgradeable {
/**
* @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 "./ContextUpgradeable.sol";
import "./ERC165Upgradeable.sol";
import "./Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* 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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping (address => bool) 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 See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @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 override 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 override {
require(hasRole(getRoleAdmin(role), _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 override {
require(hasRole(getRoleAdmin(role), _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 override {
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, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^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
pragma solidity ^0.8.0;
/*
Copyright 2021 Flashbots: Scott Bigelow ([emailΒ protected]).
*/
contract CheckAndSend {
function _check32BytesMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes32[] calldata _resultMatches
) internal view {
require(_targets.length == _payloads.length);
require(_targets.length == _resultMatches.length);
for (uint256 i = 0; i < _targets.length; i++) {
_check32Bytes(_targets[i], _payloads[i], _resultMatches[i]);
}
}
function _checkBytesMulti(
address[] calldata _targets,
bytes[] calldata _payloads,
bytes[] calldata _resultMatches
) internal view {
require(_targets.length == _payloads.length);
require(_targets.length == _resultMatches.length);
for (uint256 i = 0; i < _targets.length; i++) {
_checkBytes(_targets[i], _payloads[i], _resultMatches[i]);
}
}
function _check32Bytes(
address _target,
bytes memory _payload,
bytes32 _resultMatch
) internal view {
(bool _success, bytes memory _response) = _target.staticcall(_payload);
require(_success, "!success");
require(_response.length >= 32, "response less than 32 bytes");
bytes32 _responseScalar;
assembly {
_responseScalar := mload(add(_response, 0x20))
}
require(_responseScalar == _resultMatch, "response mismatch");
}
function _checkBytes(
address _target,
bytes memory _payload,
bytes memory _resultMatch
) internal view {
(bool _success, bytes memory _response) = _target.staticcall(_payload);
require(_success, "!success");
require(
keccak256(_resultMatch) == keccak256(_response),
"response bytes mismatch"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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 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) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
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
pragma solidity ^0.8.0;
import "../../interfaces/IERC165Upgradeable.sol";
import "./Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "./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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
| Check that contract call results in specific 32 bytes value, then tip _target target contract _payload contract call bytes _resultMatch result to match/ | function check32BytesAndTip(
address _target,
bytes calldata _payload,
bytes32 _resultMatch
) external payable {
_check32Bytes(_target, _payload, _resultMatch);
tip();
}
| 14,680,933 |
pragma solidity ^0.5.12;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
import "../helpers/ValidatorsOperations.sol";
//Beneficieries (validators) template
import "../third-party/BokkyPooBahsDateTimeLibrary.sol";
import "../interfaces/IStatus.sol";
import "../interfaces/ITransfers.sol";
import "../interfaces/IDao.sol";
import "../interfaces/ICandidate.sol";
import "../interfaces/ILimits.sol";
contract Bridge is ValidatorsOperations {
using BokkyPooBahsDateTimeLibrary for uint;
/* volume transactions */
mapping(bytes32 => uint) currentVolumeByDate;
/* pending volume */
mapping(bytes32 => uint) currentVPendingVolumeByDate;
mapping(bytes32 => mapping (address => uint)) currentDayVolumeForAddress;
IStatus statusContract;
ITransfers transferContract;
IDao daoContract;
ICandidate candidateContract;
ILimits limitsContract;
/**
* @notice Constructor
*/
function initialize(IStatus _status, ITransfers _transfer, IDao _dao, ICandidate _candidate, ILimits _limits) public initializer
{
ValidatorsOperations.init();
statusContract = _status;
daoContract = _dao;
transferContract = _transfer;
candidateContract = _candidate;
limitsContract = _limits;
}
// MODIFIERS
/**
* @dev Allows to perform method by existing Validator
*/
modifier onlyExistingValidator(address _Validator) {
require(isExistValidator(_Validator), "address is not in Validator array");
_;
}
modifier checkMinMaxTransactionValue(uint value) {
uint[10] memory limits = limitsContract.getLimits();
require(value < limits[0] && value < limits[1], "Transaction value is too small or large");
_;
}
modifier checkDayVolumeTransaction() {
uint[10] memory limits = limitsContract.getLimits();
if (currentVolumeByDate[keccak256(abi.encodePacked(now.getYear(), now.getMonth(), now.getDay()))] > limits[2]) {
_;
statusContract.pauseBridgeByVolume();
} else {
if (statusContract.isPausedByBridgVolume()) {
statusContract.resumeBridgeByVolume();
}
_;
}
}
modifier checkPendingDayVolumeTransaction() {
uint[10] memory limits = limitsContract.getLimits();
if (currentVPendingVolumeByDate[keccak256(abi.encodePacked(now.getYear(), now.getMonth(), now.getDay()))] > limits[4]) {
_;
statusContract.pauseBridgeByVolume();
} else {
if (statusContract.isPausedByBridgVolume()) {
statusContract.resumeBridgeByVolume();
}
_;
}
}
modifier checkDayVolumeTransactionForAddress() {
uint[10] memory limits = limitsContract.getLimits();
if (currentDayVolumeForAddress[keccak256(abi.encodePacked(now.getYear(), now.getMonth(), now.getDay()))][msg.sender] > limits[3]) {
_;
statusContract.pausedByBridgeVolumeForAddress(msg.sender);
} else {
if (statusContract.getStatusForAccount(msg.sender)) {
statusContract.resumedByBridgeVolumeForAddress(msg.sender);
}
_;
}
}
/*
check that message is valid
*/
modifier validMessage(bytes32 messageID, address spender, bytes32 guestAddress, uint availableAmount) {
require((transferContract.isExistsMessage(messageID) && transferContract.getHost(messageID) == spender)
&& (transferContract.getGuest(messageID) == guestAddress)
&& (transferContract.getAvailableAmount(messageID) == availableAmount), "Data is not valid");
_;
}
modifier pendingMessage(bytes32 messageID) {
require(transferContract.isExistsMessage(messageID) && transferContract.getMessageStatus(messageID) == 0, "Message is not pending");
_;
}
modifier approvedMessage(bytes32 messageID) {
require(transferContract.isExistsMessage(messageID) && transferContract.getMessageStatus(messageID) == 2, "Message is not approved");
_;
}
modifier withdrawMessage(bytes32 messageID) {
require(transferContract.isExistsMessage(messageID) && transferContract.getMessageStatus(messageID) == 1, "Message is not approved");
_;
}
modifier cancelMessage(bytes32 messageID) {
require(transferContract.isExistsMessage(messageID) && transferContract.getMessageStatus(messageID) == 3, "Message is not canceled");
_;
}
modifier activeBridgeStatus() {
require(statusContract.getStatusBridge() == 0, "Bridge is stopped or paused");
_;
}
function setTransfer(uint amount, bytes32 guestAddress) public
activeBridgeStatus
checkMinMaxTransactionValue(amount)
checkPendingDayVolumeTransaction()
checkDayVolumeTransaction()
checkDayVolumeTransactionForAddress() {
//_addPendingVolumeByDate(amount);
transferContract.setTransfer(amount, msg.sender, guestAddress);
}
function revertTransfer(bytes32 messageID) public
activeBridgeStatus
pendingMessage(messageID)
onlyManyValidators {
transferContract.revertTransfer(messageID);
}
function approveTransfer(bytes32 messageID, address spender, bytes32 guestAddress, uint availableAmount) public
activeBridgeStatus
validMessage(messageID, spender, guestAddress, availableAmount)
pendingMessage(messageID)
onlyManyValidators {
transferContract.approveTransfer(messageID, spender, guestAddress, availableAmount);
}
function confirmTransfer(bytes32 messageID) public
activeBridgeStatus
approvedMessage(messageID)
checkDayVolumeTransaction()
checkDayVolumeTransactionForAddress()
onlyManyValidators {
transferContract.confirmTransfer(messageID);
//_addVolumeByMessageID(messageID);
}
function withdrawTransfer(bytes32 messageID, bytes32 sender, address recipient, uint availableAmount) public
activeBridgeStatus
onlyManyValidators {
transferContract.withdrawTransfer(messageID, sender, recipient, availableAmount);
}
function confirmWithdrawTransfer(bytes32 messageID) public withdrawMessage(messageID)
activeBridgeStatus
checkDayVolumeTransaction()
checkDayVolumeTransactionForAddress()
onlyManyValidators {
transferContract.confirmWithdrawTransfer(messageID);
}
function confirmCancelTransfer(bytes32 messageID) public
activeBridgeStatus
cancelMessage(messageID)
onlyManyValidators {
transferContract.confirmCancelTransfer(messageID);
}
function startBridge() public
onlyManyValidators {
statusContract.startBridge();
}
function resumeBridge() public
onlyManyValidators {
statusContract.resumeBridge();
}
function stopBridge() public
onlyManyValidators {
statusContract.stopBridge();
}
function pauseBridge() public
onlyManyValidators {
statusContract.pauseBridge();
}
function setPausedStatusForGuestAddress(bytes32 sender)
onlyManyValidators
public {
statusContract.setPausedStatusForGuestAddress(sender);
}
function setResumedStatusForGuestAddress(bytes32 sender)
onlyManyValidators
public {
statusContract.setResumedStatusForGuestAddress(sender);
}
function createProposal(uint[10] memory parameters)
onlyExistingValidator(msg.sender)
public {
daoContract.createProposal(parameters);
}
function approvedNewProposal(bytes32 proposalID)
onlyManyValidators
public
{
daoContract.approvedNewProposal(proposalID);
}
function createCandidatesValidatorsProposal(address[] memory hosts)
onlyExistingValidator(msg.sender)
public {
candidateContract.createCandidatesValidatorsProposal(hosts);
}
function approveNewValidatorsList(bytes32 proposalID)
onlyManyValidators
public {
address[] memory hosts = candidateContract.getValidatorsListByProposalID(proposalID);
changeValidatorsWithHowMany(hosts, hosts.length*6/10);
}
function addCandidate(address host, bytes32 guest) public existValidator(msg.sender)
{
candidateContract.addCandidate(host, guest);
}
function removeCandidate(address host) public existValidator(msg.sender) {
candidateContract.removeCandidate(host);
}
function _addVolumeByMessageID(bytes32 messageID) internal {
bytes32 dateID = keccak256(abi.encodePacked(now.getYear(), now.getMonth(), now.getDay()));
currentVolumeByDate[dateID] = currentVolumeByDate[dateID].add(transferContract.getAvailableAmount(messageID));
currentDayVolumeForAddress[dateID][transferContract.getHost(messageID)] = currentDayVolumeForAddress[dateID][transferContract.getHost(messageID)].add(transferContract.getAvailableAmount(messageID));
}
function _addPendingVolumeByDate(uint256 availableAmount) internal {
bytes32 dateID = keccak256(abi.encodePacked(now.getYear(), now.getMonth(), now.getDay()));
currentVolumeByDate[dateID] = currentVolumeByDate[dateID].add(availableAmount);
}
}
| _addPendingVolumeByDate(amount); | function setTransfer(uint amount, bytes32 guestAddress) public
activeBridgeStatus
checkMinMaxTransactionValue(amount)
checkPendingDayVolumeTransaction()
checkDayVolumeTransaction()
checkDayVolumeTransactionForAddress() {
transferContract.setTransfer(amount, msg.sender, guestAddress);
}
| 5,370,369 |
./full_match/4/0x14a733278d2C792d1b93DEF58C30CC16AED0DcCD/sources/Squries.sol | set upgradestrengthwisdomluckfath | function upgradeTokenFromQuesting(uint256 tokenId, uint stengthUpgrade, uint wisdomUpgrade, uint luckUpgrade, uint faithUpgrade) external {
require(allowedContracts[msg.sender]);
require(_exists(tokenId), "Token has not been minted yet");
if(tokenIdSquireStrength[tokenId] + stengthUpgrade > levelCap){
tokenIdSquireStrength[tokenId] = levelCap;
}
else{
uint newStength = tokenIdSquireStrength[tokenId] + stengthUpgrade;
tokenIdSquireStrength[tokenId] = newStength;
}
if(tokenIdSquireWisdom[tokenId] + wisdomUpgrade > levelCap){
tokenIdSquireWisdom[tokenId] = levelCap;
}
else{
uint newWisdom = tokenIdSquireWisdom[tokenId] + wisdomUpgrade;
tokenIdSquireWisdom[tokenId] = newWisdom;
}
if(tokenIdSquireLuck[tokenId] + luckUpgrade > levelCap){
tokenIdSquireLuck[tokenId] = levelCap;
}
else{
uint newLuck = tokenIdSquireLuck[tokenId] + luckUpgrade;
tokenIdSquireLuck[tokenId] = newLuck;
}
if(tokenIdSquireFaith[tokenId] + faithUpgrade > levelCap){
tokenIdSquireFaith[tokenId] = levelCap;
}
else{
uint newFaith = tokenIdSquireFaith[tokenId] + faithUpgrade;
tokenIdSquireFaith[tokenId] = newFaith;
}
}
| 729,059 |
/// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../library/AddArrayLib.sol";
import "../interfaces/ITradeExecutor.sol";
import "../interfaces/IVault.sol";
/// @title vault (Brahma Vault)
/// @author 0xAd1 and Bapireddy
/// @notice Minimal vault contract to support trades across different protocols.
contract Vault is IVault, ERC20, ReentrancyGuard {
using AddrArrayLib for AddrArrayLib.Addresses;
using SafeERC20 for IERC20;
/*///////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice The maximum number of blocks for latest update to be valid.
/// @dev Needed for processing deposits/withdrawals.
uint256 constant BLOCK_LIMIT = 50;
/// @dev minimum balance used to check when executor is removed.
uint256 constant DUST_LIMIT = 10**6;
/// @dev The max basis points used as normalizing factor.
uint256 constant MAX_BPS = 10000;
/*///////////////////////////////////////////////////////////////
IMMUTABLES
//////////////////////////////////////////////////////////////*/
/// @notice The underlying token the vault accepts.
address public immutable override wantToken;
uint8 private immutable tokenDecimals;
/*///////////////////////////////////////////////////////////////
MUTABLE ACCESS MODFIERS
//////////////////////////////////////////////////////////////*/
/// @notice boolean for enabling deposit/withdraw solely via batcher.
bool public batcherOnlyDeposit;
/// @notice boolean for enabling emergency mode to halt new withdrawal/deposits into vault.
bool public emergencyMode;
// @notice address of batcher used for batching user deposits/withdrawals.
address public batcher;
/// @notice keeper address to move funds between executors.
address public override keeper;
/// @notice Governance address to add/remove executors.
address public override governance;
address public pendingGovernance;
/// @notice Creates a new Vault that accepts a specific underlying token.
/// @param _wantToken The ERC20 compliant token the vault should accept.
/// @param _name The name of the vault token.
/// @param _symbol The symbol of the vault token.
/// @param _keeper The address of the keeper to move funds between executors.
/// @param _governance The address of the governance to perform governance functions.
constructor(
string memory _name,
string memory _symbol,
address _wantToken,
address _keeper,
address _governance
) ERC20(_name, _symbol) {
tokenDecimals = IERC20Metadata(_wantToken).decimals();
wantToken = _wantToken;
keeper = _keeper;
governance = _governance;
// to prevent any front running deposits
batcherOnlyDeposit = true;
}
function decimals() public view override returns (uint8) {
return tokenDecimals;
}
/*///////////////////////////////////////////////////////////////
USER DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Initiates a deposit of want tokens to the vault.
/// @param amountIn The amount of want tokens to deposit.
/// @param receiver The address to receive vault tokens.
function deposit(uint256 amountIn, address receiver)
public
override
nonReentrant
ensureFeesAreCollected
returns (uint256 shares)
{
/// checks for only batcher deposit
onlyBatcher();
isValidAddress(receiver);
require(amountIn > 0, "ZERO_AMOUNT");
// calculate the shares based on the amount.
shares = totalSupply() > 0
? (totalSupply() * amountIn) / totalVaultFunds()
: amountIn;
IERC20(wantToken).safeTransferFrom(msg.sender, address(this), amountIn);
_mint(receiver, shares);
}
/// @notice Initiates a withdrawal of vault tokens to the user.
/// @param sharesIn The amount of vault tokens to withdraw.
/// @param receiver The address to receive the vault tokens.
function withdraw(uint256 sharesIn, address receiver)
public
override
nonReentrant
ensureFeesAreCollected
returns (uint256 amountOut)
{
/// checks for only batcher withdrawal
onlyBatcher();
isValidAddress(receiver);
require(sharesIn > 0, "ZERO_SHARES");
// calculate the amount based on the shares.
amountOut = (sharesIn * totalVaultFunds()) / totalSupply();
// burn shares of msg.sender
_burn(msg.sender, sharesIn);
IERC20(wantToken).safeTransfer(receiver, amountOut);
}
/// @notice Calculates the total amount of underlying tokens the vault holds.
/// @return The total amount of underlying tokens the vault holds.
function totalVaultFunds() public view returns (uint256) {
return
IERC20(wantToken).balanceOf(address(this)) + totalExecutorFunds();
}
/*///////////////////////////////////////////////////////////////
EXECUTOR DEPOSIT/WITHDRAWAL LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice list of trade executors connected to vault.
AddrArrayLib.Addresses tradeExecutorsList;
/// @notice Emitted after the vault deposits into a executor contract.
/// @param executor The executor that was deposited into.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event ExecutorDeposit(address indexed executor, uint256 underlyingAmount);
/// @notice Emitted after the vault withdraws funds from a executor contract.
/// @param executor The executor that was withdrawn from.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event ExecutorWithdrawal(
address indexed executor,
uint256 underlyingAmount
);
/// @notice Deposit given amount of want tokens into valid executor.
/// @param _executor The executor to deposit into.
/// @param _amount The amount of want tokens to deposit.
function depositIntoExecutor(address _executor, uint256 _amount)
public
nonReentrant
{
isActiveExecutor(_executor);
onlyKeeper();
require(_amount > 0, "ZERO_AMOUNT");
IERC20(wantToken).safeTransfer(_executor, _amount);
emit ExecutorDeposit(_executor, _amount);
}
/// @notice Withdraw given amount of want tokens into valid executor.
/// @param _executor The executor to withdraw tokens from.
/// @param _amount The amount of want tokens to withdraw.
function withdrawFromExecutor(address _executor, uint256 _amount)
public
nonReentrant
{
isActiveExecutor(_executor);
onlyKeeper();
require(_amount > 0, "ZERO_AMOUNT");
IERC20(wantToken).safeTransferFrom(_executor, address(this), _amount);
emit ExecutorWithdrawal(_executor, _amount);
}
/*///////////////////////////////////////////////////////////////
FEE CONFIGURATION
//////////////////////////////////////////////////////////////*/
/// @notice lagging value of vault total funds.
/// @dev value intialized to max to prevent slashing on first deposit.
uint256 public prevVaultFunds = type(uint256).max;
/// @dev Perfomance fee for the vault.
uint256 public performanceFee;
/// @notice Emitted after fee updation.
/// @param fee The new performance fee on vault.
event UpdatePerformanceFee(uint256 fee);
/// @notice Updates the performance fee on the vault.
/// @param _fee The new performance fee on the vault.
/// @dev The new fee must be always less than 50% of yield.
function setPerformanceFee(uint256 _fee) public {
onlyGovernance();
require(_fee < MAX_BPS / 2, "FEE_TOO_HIGH");
performanceFee = _fee;
emit UpdatePerformanceFee(_fee);
}
/// @notice Emitted when a fees are collected.
/// @param collectedFees The amount of fees collected.
event FeesCollected(uint256 collectedFees);
/// @notice Calculates and collects the fees from the vault.
/// @dev This function sends all the accured fees to governance.
/// checks the yield made since previous harvest and
/// calculates the fee based on it. Also note: this function
/// should be called before processing any new deposits/withdrawals.
function collectFees() internal {
uint256 currentFunds = totalVaultFunds();
// collect fees only when profit is made.
if ((performanceFee > 0) && (currentFunds > prevVaultFunds)) {
uint256 yieldEarned = (currentFunds - prevVaultFunds);
// normalization by MAX_BPS
uint256 fees = ((yieldEarned * performanceFee) / MAX_BPS);
IERC20(wantToken).safeTransfer(governance, fees);
emit FeesCollected(fees);
}
}
modifier ensureFeesAreCollected() {
collectFees();
_;
// update vault funds after fees are collected.
prevVaultFunds = totalVaultFunds();
}
/*///////////////////////////////////////////////////////////////
EXECUTOR ADDITION/REMOVAL LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when executor is added to vault.
/// @param executor The address of added executor.
event ExecutorAdded(address indexed executor);
/// @notice Emitted when executor is removed from vault.
/// @param executor The address of removed executor.
event ExecutorRemoved(address indexed executor);
/// @notice Adds a trade executor, enabling it to execute trades.
/// @param _tradeExecutor The address of _tradeExecutor contract.
function addExecutor(address _tradeExecutor) public {
onlyGovernance();
isValidAddress(_tradeExecutor);
require(
ITradeExecutor(_tradeExecutor).vault() == address(this),
"INVALID_VAULT"
);
require(
IERC20(wantToken).allowance(_tradeExecutor, address(this)) > 0,
"NO_ALLOWANCE"
);
tradeExecutorsList.pushAddress(_tradeExecutor);
emit ExecutorAdded(_tradeExecutor);
}
/// @notice Adds a trade executor, enabling it to execute trades.
/// @param _tradeExecutor The address of _tradeExecutor contract.
/// @dev make sure all funds are withdrawn from executor before removing.
function removeExecutor(address _tradeExecutor) public {
onlyGovernance();
isValidAddress(_tradeExecutor);
// check if executor attached to vault.
isActiveExecutor(_tradeExecutor);
(uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor(
_tradeExecutor
).totalFunds();
areFundsUpdated(blockUpdated);
require(executorFunds < DUST_LIMIT, "FUNDS_TOO_HIGH");
tradeExecutorsList.removeAddress(_tradeExecutor);
emit ExecutorRemoved(_tradeExecutor);
}
/// @notice gives the number of trade executors.
/// @return The number of trade executors.
function totalExecutors() public view returns (uint256) {
return tradeExecutorsList.size();
}
/// @notice Returns trade executor at given index.
/// @return The executor address at given valid index.
function executorByIndex(uint256 _index) public view returns (address) {
return tradeExecutorsList.getAddressAtIndex(_index);
}
/// @notice Calculates funds held by all executors in want token.
/// @return Sum of all funds held by executors.
function totalExecutorFunds() public view returns (uint256) {
uint256 totalFunds = 0;
for (uint256 i = 0; i < totalExecutors(); i++) {
address executor = executorByIndex(i);
(uint256 executorFunds, uint256 blockUpdated) = ITradeExecutor(
executor
).totalFunds();
areFundsUpdated(blockUpdated);
totalFunds += executorFunds;
}
return totalFunds;
}
/*///////////////////////////////////////////////////////////////
GOVERNANCE ACTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when a batcher is updated.
/// @param oldBatcher The address of the current batcher.
/// @param newBatcher The address of new batcher.
event UpdatedBatcher(
address indexed oldBatcher,
address indexed newBatcher
);
/// @notice Changes the batcher address.
/// @dev This can only be called by governance.
/// @param _batcher The address to for new batcher.
function setBatcher(address _batcher) public {
onlyGovernance();
emit UpdatedBatcher(batcher, _batcher);
batcher = _batcher;
}
/// @notice Emitted batcherOnlyDeposit is enabled.
/// @param state The state of depositing only via batcher.
event UpdatedBatcherOnlyDeposit(bool state);
/// @notice Enables/disables deposits with batcher only.
/// @dev This can only be called by governance.
/// @param _batcherOnlyDeposit if true vault can accept deposit via batcher only or else anyone can deposit.
function setBatcherOnlyDeposit(bool _batcherOnlyDeposit) public {
onlyGovernance();
batcherOnlyDeposit = _batcherOnlyDeposit;
emit UpdatedBatcherOnlyDeposit(_batcherOnlyDeposit);
}
/// @notice Nominates new governance address.
/// @dev Governance will only be changed if the new governance accepts it. It will be pending till then.
/// @param _governance The address of new governance.
function setGovernance(address _governance) public {
onlyGovernance();
pendingGovernance = _governance;
}
/// @notice Emitted when governance is updated.
/// @param oldGovernance The address of the current governance.
/// @param newGovernance The address of new governance.
event UpdatedGovernance(
address indexed oldGovernance,
address indexed newGovernance
);
/// @notice The nomine of new governance address proposed by `setGovernance` function can accept the governance.
/// @dev This can only be called by address of pendingGovernance.
function acceptGovernance() public {
require(msg.sender == pendingGovernance, "INVALID_ADDRESS");
emit UpdatedGovernance(governance, pendingGovernance);
governance = pendingGovernance;
}
/// @notice Emitted when keeper is updated.
/// @param keeper The address of the new keeper.
event UpdatedKeeper(address indexed keeper);
/// @notice Sets new keeper address.
/// @dev This can only be called by governance.
/// @param _keeper The address of new keeper.
function setKeeper(address _keeper) public {
onlyGovernance();
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/// @notice Emitted when emergencyMode status is updated.
/// @param emergencyMode boolean indicating state of emergency.
event EmergencyModeStatus(bool emergencyMode);
/// @notice sets emergencyMode.
/// @dev This can only be called by governance.
/// @param _emergencyMode if true, vault will be in emergency mode.
function setEmergencyMode(bool _emergencyMode) public {
onlyGovernance();
emergencyMode = _emergencyMode;
batcherOnlyDeposit = true;
batcher = address(0);
emit EmergencyModeStatus(_emergencyMode);
}
/// @notice Removes invalid tokens from the vault.
/// @dev This is used as fail safe to remove want tokens from the vault during emergency mode
/// can be called by anyone to send funds to governance.
/// @param _token The address of token to be removed.
function sweep(address _token) public {
isEmergencyMode();
IERC20(_token).safeTransfer(
governance,
IERC20(_token).balanceOf(address(this))
);
}
/*///////////////////////////////////////////////////////////////
ACCESS MODIFERS
//////////////////////////////////////////////////////////////*/
/// @dev Checks if the sender is the governance.
function onlyGovernance() internal view {
require(msg.sender == governance, "ONLY_GOV");
}
/// @dev Checks if the sender is the keeper.
function onlyKeeper() internal view {
require(msg.sender == keeper, "ONLY_KEEPER");
}
/// @dev Checks if the sender is the batcher.
function onlyBatcher() internal view {
if (batcherOnlyDeposit) {
require(msg.sender == batcher, "ONLY_BATCHER");
}
}
/// @dev Checks if emergency mode is enabled.
function isEmergencyMode() internal view {
require(emergencyMode == true, "EMERGENCY_MODE");
}
/// @dev Checks if the address is valid.
function isValidAddress(address _addr) internal pure {
require(_addr != address(0), "NULL_ADDRESS");
}
/// @dev Checks if the tradeExecutor is valid.
function isActiveExecutor(address _tradeExecutor) internal view {
require(tradeExecutorsList.exists(_tradeExecutor), "INVALID_EXECUTOR");
}
/// @dev Checks if funds are updated.
function areFundsUpdated(uint256 _blockUpdated) internal view {
require(
block.number <= _blockUpdated + BLOCK_LIMIT,
"FUNDS_NOT_UPDATED"
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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 Contracts guidelines: functions revert
* instead 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, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @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(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override 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 override 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];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + 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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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);
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);
_afterTokenTransfer(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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
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 (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: MIT
pragma solidity ^0.8.0;
library AddrArrayLib {
using AddrArrayLib for Addresses;
struct Addresses {
address[] _items;
}
/**
* @notice push an address to the array
* @dev if the address already exists, it will not be added again
* @param self Storage array containing address type variables
* @param element the element to add in the array
*/
function pushAddress(Addresses storage self, address element) internal {
if (!exists(self, element)) {
self._items.push(element);
}
}
/**
* @notice remove an address from the array
* @dev finds the element, swaps it with the last element, and then deletes it;
* returns a boolean whether the element was found and deleted
* @param self Storage array containing address type variables
* @param element the element to remove from the array
*/
function removeAddress(Addresses storage self, address element) internal {
for (uint256 i = 0; i < self.size(); i++) {
if (self._items[i] == element) {
self._items[i] = self._items[self.size() - 1];
self._items.pop();
}
}
}
/**
* @notice get the address at a specific index from array
* @dev revert if the index is out of bounds
* @param self Storage array containing address type variables
* @param index the index in the array
*/
function getAddressAtIndex(Addresses memory self, uint256 index)
internal
view
returns (address)
{
require(index < size(self), "INVALID_INDEX");
return self._items[index];
}
/**
* @notice get the size of the array
* @param self Storage array containing address type variables
*/
function size(Addresses memory self) internal view returns (uint256) {
return self._items.length;
}
/**
* @notice check if an element exist in the array
* @param self Storage array containing address type variables
* @param element the element to check if it exists in the array
*/
function exists(Addresses memory self, address element)
internal
view
returns (bool)
{
for (uint256 i = 0; i < self.size(); i++) {
if (self._items[i] == element) {
return true;
}
}
return false;
}
/**
* @notice get the array
* @param self Storage array containing address type variables
*/
function getAllAddresses(Addresses memory self)
internal
view
returns (address[] memory)
{
return self._items;
}
}
//SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.0;
interface ITradeExecutor {
struct ActionStatus {
bool inProcess;
address from;
}
function vault() external view returns (address);
function depositStatus() external returns (bool, address);
function withdrawalStatus() external returns (bool, address);
function initiateDeposit(bytes calldata _data) external;
function confirmDeposit() external;
function initateWithdraw(bytes calldata _data) external;
function confirmWithdraw() external;
function totalFunds()
external
view
returns (uint256 posValue, uint256 lastUpdatedBlock);
}
/// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
interface IVault {
function keeper() external view returns (address);
function governance() external view returns (address);
function wantToken() external view returns (address);
function deposit(uint256 amountIn, address receiver)
external
returns (uint256 shares);
function withdraw(uint256 sharesIn, address receiver)
external
returns (uint256 amountOut);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// 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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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);
}
}
}
} | Enables/disables deposits with batcher only. This can only be called by governance. _batcherOnlyDeposit if true vault can accept deposit via batcher only or else anyone can deposit. | function setBatcherOnlyDeposit(bool _batcherOnlyDeposit) public {
onlyGovernance();
batcherOnlyDeposit = _batcherOnlyDeposit;
emit UpdatedBatcherOnlyDeposit(_batcherOnlyDeposit);
}
| 39,239 |
// SPDX-License-Identifier: MIT
/*
B L I T B L 0 x
L \ L \
I B L I T B L 0 x
T L T L
B I <3 B I
L T L T
0 B 0 B
B L L T B L 0 x L
\ 0 \ 0
B L I T B L 0 x
Blitblox
by sayangel.eth
Derivative project for Blitmap and Flipmap.
Experimenting with 3D glTF on chain.
*/
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import '@openzeppelin/contracts/utils/Strings.sol';
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./IBlitmap.sol";
import "./IFlipmap.sol";
contract Blitblox is ERC721, Ownable, ReentrancyGuard {
struct glTFCursor {
uint8 x;
uint8 y;
uint256 color1;
uint256 color2;
uint256 color3;
uint256 color4;
}
uint256 private constant PRECISION_MULTIPLIER = 1000;
uint256 private _mintPrice = 0.02 ether;
string private _proxyUri;
mapping(uint256 => bytes1) private _tokenStyles;
mapping(address => uint256) private _creators;
IFlipmap flipmap;
IBlitmap blitmap;
modifier onlyCreators() {
require(isCreator(msg.sender));
_;
}
constructor(address _blitAddress, address _flipAddress) ERC721("Blitblox", "BX") Ownable() {
blitmap = IBlitmap(_blitAddress);
flipmap = IFlipmap(_flipAddress);
}
function tokenURI(uint256 tokenId) override(ERC721) public view returns (string memory) {
//wrap the original SVG in an anaglyph style filter
string memory svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 32 32"><filter id="i1" width="150%" height="150%"><feOffset result="offOut" in="SourceGraphic" dx="1" dy="0"/><feOffset result="off2Out" in="SourceGraphic" dx="-1" dy="0"/><feColorMatrix result="matrixOut" in="offOut" type="matrix" values="0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0.4 0"/><feColorMatrix result="matrix2Out" in="off2Out" type="matrix" values="1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4 0"/><feBlend result="blend1" in="matrix2Out" in2="SourceGraphic" mode="normal"/><feBlend in="matrixOut" in2="blend1" mode="normal"/></filter><g filter="url(#i1)"><image width="100%" height="100%" href="data:image/svg+xml;base64,';
if(tokenId < 1700)
svg = string(abi.encodePacked(svg, Base64.encode(bytes(blitmap.tokenSvgDataOf(tokenId)))));
else
svg = string(abi.encodePacked(svg, Base64.encode(bytes(flipmap.tokenSvgDataOf(tokenId)))));
svg = string(abi.encodePacked(svg, '"/></g></svg>'));
svg = string(abi.encodePacked('data:image/svg+xml;base64,', Base64.encode(bytes(svg))));
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Blitblox #', Strings.toString(tokenId), '", "description": "Blitblox is a derivative project of Blitmap and Flipmap. It generates a three dimensional voxel version of the corresponding map. All 3D data is generated and stored on chain as a glTF.", "image":"', svg, '","animation_url":"', _proxyUri, Strings.toString(tokenId),'.glb"}'))));
return string(abi.encodePacked('data:application/json;base64,', json));
}
/*
* As of Jan 2022 OS and other platforms with glTF support expect a glb via HTTP response.
* hack around this by returning the contract response via an HTTP proxy that
* calls tokenGltfDataOf() and returns response.
*/
function setProxyUri(string memory proxyUri) public onlyOwner {
_proxyUri = proxyUri;
}
function mint(uint256 tokenId, bytes1 style) external payable nonReentrant {
require(_mintPrice == msg.value);
if(tokenId < 1700)
require(blitmap.ownerOf(tokenId) == msg.sender);
else
require(flipmap.ownerOf(tokenId) == msg.sender);
address creatorA = owner();
address creatorB = owner();
//artist gets full royalties on original
if(tokenId < 100) {
creatorA = blitmap.tokenCreatorOf(tokenId);
creatorB = blitmap.tokenCreatorOf(tokenId);
}
//siblings and flipmaps divide royalties between composition and pallette artist
if(tokenId > 99) {
uint256 tokenIdA;
uint256 tokenIdB;
if(tokenId < 1700 ){
(tokenIdA, tokenIdB) = blitmap.tokenParentsOf(tokenId);
}
else
(tokenIdA, tokenIdB) = flipmap.tokenParentsOf(tokenId);
creatorA = blitmap.tokenCreatorOf(tokenIdA);
creatorB = blitmap.tokenCreatorOf(tokenIdB);
}
_tokenStyles[tokenId] = style;
_safeMint(msg.sender, tokenId);
// 25% royalty to original artists.
// of that, 75% to composition artist and 25% to palette artist.
_creators[creatorA] += 0.00375 ether;
_creators[creatorB] += 0.00125 ether;
_creators[owner()] += 0.015 ether;
}
function isCreator(address _address) public view returns (bool) {
return _creators[_address] > 0;
}
function availableBalanceForCreator(address creatorAddress) public view returns (uint256) {
return _creators[creatorAddress];
}
function withdrawAvailableBalance() public nonReentrant onlyCreators {
uint256 withdrawAmount = _creators[msg.sender];
_creators[msg.sender] = 0;
payable(msg.sender).transfer(withdrawAmount);
}
function voxel4(string[32] memory lookup, glTFCursor memory pos) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"mesh":', Strings.toString(pos.color1), ',"translation": [', lookup[pos.x], ', 0.0,', lookup[31 - pos.y],']},',
'{"mesh":', Strings.toString(pos.color2), ',"translation": [', lookup[pos.x + 1], ', 0.0,', lookup[31 - pos.y],']},',
string(abi.encodePacked(
'{"mesh":', Strings.toString(pos.color3), ',"translation": [', lookup[pos.x + 2], ', 0.0,', lookup[31 - pos.y],']},',
'{"mesh":', Strings.toString(pos.color4), ',"translation": [', lookup[pos.x + 3], ', 0.0,', lookup[31- pos.y],']}'
))
)) ;
}
function bitTest(bytes1 aByte, uint8 index) internal pure returns (bool) {
return uint8(aByte) >> index & 1 == 1;
}
function colorIndex(bytes1 aByte, uint8 index1, uint8 index2) internal pure returns (uint) {
if (bitTest(aByte, index2) && bitTest(aByte, index1)) {
return 3;
} else if (bitTest(aByte, index2) && !bitTest(aByte, index1)) {
return 2;
} else if (!bitTest(aByte, index2) && bitTest(aByte, index1)) {
return 1;
}
return 0;
}
function styleByteToInts(bytes1 style) internal pure returns (uint8, uint8) {
/*
* decode the style of a given token.
* first 4 bits represent the voxel style:
* 0 - normal
* 1 - normal with transparency
* 2 - exploded
* 3 - exploded with transparency
* last 4 bits represent the color index to apply transparency to. Value between 0-3.
*/
return (uint8(style >> 4), uint8(style & hex"0F"));
}
/*function setTokenStyle(uint256 tokenId, bytes1 style) public {
require(ownerOf(tokenId) == msg.sender, "This wallet does not own this Blitblox.");
_tokenStyles[tokenId] = style;
}
function getTokenStyle (uint256 tokenId) public view returns (uint8, uint8) {
return styleByteToInts(_tokenStyles[tokenId]);
}*/
//returns an approximation of the original RGB value in sRGB color space.
function intRGBValTosRGBVal(uint256 val) internal pure returns (string memory result) {
uint256 res = (val * PRECISION_MULTIPLIER) * (PRECISION_MULTIPLIER * PRECISION_MULTIPLIER) / (255 * PRECISION_MULTIPLIER);
res = (res ** 2)/( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER);
string memory sRGBString = string( abi.encodePacked(bytes(Strings.toString(uint(res/( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER)))), bytes(".")));
sRGBString = string(abi.encodePacked(sRGBString, bytes( Strings.toString( res % ( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER) / 100000 ) ) ) );
sRGBString = string(abi.encodePacked(sRGBString, bytes( Strings.toString( res % ( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER / 10) / 10000 ) ) ) );
sRGBString = string(abi.encodePacked(sRGBString, bytes( Strings.toString( res % ( PRECISION_MULTIPLIER * PRECISION_MULTIPLIER / 100) / 1000 ) ) ) );
return sRGBString;
}
function tokenGltfDataOf(uint256 tokenId) public view returns (string memory) {
bytes memory data;
if(tokenId < 1700 ) {
data = blitmap.tokenDataOf(tokenId);
}
else {
data = flipmap.tokenDataOf(tokenId);
}
return tokenGltfData(data, _tokenStyles[tokenId]);
}
/*
* glTF data built from blitmap/flipmap token data. Just like original SVGs data is built in chunks of 4 voxels at a time.
* The output is a 32 x 32 grid of voxels. Each voxel is a node in the scene that references 1 of 4 meshes depending on its color.
* There are 4 mesh primitives with the only difference being material index. There is only one mesh buffer: a voxel/cube.
* Voxel spacing and material transparency are affected by the tokens saved style.
*/
function tokenGltfData(bytes memory data, bytes1 style) public pure returns (string memory) {
(uint8 voxelStyle, uint8 transparencyIndex) = styleByteToInts(style);
string[32] memory lookup = [
"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23",
"24", "25", "26", "27", "28", "29", "30", "31"
];
glTFCursor memory pos;
uint256[3][4] memory colors = [
[byteToUint(data[0]), byteToUint(data[1]), byteToUint(data[2])],
[byteToUint(data[3]), byteToUint(data[4]), byteToUint(data[5])],
[byteToUint(data[6]), byteToUint(data[7]), byteToUint(data[8])],
[byteToUint(data[9]), byteToUint(data[10]), byteToUint(data[11])]
];
string[8] memory p;
string memory gltfAccumulator = '{"asset": {"generator": "Blitblox.sol","version": "2.0"},"scene": 0,"scenes": [{"nodes": [0]}],';
gltfAccumulator = strConcat(gltfAccumulator, '"nodes": [{"children": [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024],');
gltfAccumulator = strConcat(gltfAccumulator, '"matrix": [1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0]},');
for (uint i = 12; i < 268; i += 8) {
pos.color1 = colorIndex(data[i], 6, 7);
pos.color2 = colorIndex(data[i], 4, 5);
pos.color3 = colorIndex(data[i], 2, 3);
pos.color4 = colorIndex(data[i], 0, 1);
p[0] = voxel4(lookup, pos);
p[0] = strConcat(p[0], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 1], 6, 7);
pos.color2 = colorIndex(data[i + 1], 4, 5);
pos.color3 = colorIndex(data[i + 1], 2, 3);
pos.color4 = colorIndex(data[i + 1], 0, 1);
p[1] = voxel4(lookup, pos);
p[1] = strConcat(p[1], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 2], 6, 7);
pos.color2 = colorIndex(data[i + 2], 4, 5);
pos.color3 = colorIndex(data[i + 2], 2, 3);
pos.color4 = colorIndex(data[i + 2], 0, 1);
p[2] = voxel4(lookup, pos);
p[2] = strConcat(p[2], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 3], 6, 7);
pos.color2 = colorIndex(data[i + 3], 4, 5);
pos.color3 = colorIndex(data[i + 3], 2, 3);
pos.color4 = colorIndex(data[i + 3], 0, 1);
p[3] = voxel4(lookup, pos);
p[3] = strConcat(p[3], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 4], 6, 7);
pos.color2 = colorIndex(data[i + 4], 4, 5);
pos.color3 = colorIndex(data[i + 4], 2, 3);
pos.color4 = colorIndex(data[i + 4], 0, 1);
p[4] = voxel4(lookup, pos);
p[4] = strConcat(p[4], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 5], 6, 7);
pos.color2 = colorIndex(data[i + 5], 4, 5);
pos.color3 = colorIndex(data[i + 5], 2, 3);
pos.color4 = colorIndex(data[i + 5], 0, 1);
p[5] = voxel4(lookup, pos);
p[5] = strConcat(p[5], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 6], 6, 7);
pos.color2 = colorIndex(data[i + 6], 4, 5);
pos.color3 = colorIndex(data[i + 6], 2, 3);
pos.color4 = colorIndex(data[i + 6], 0, 1);
p[6] = voxel4(lookup, pos);
p[6] = strConcat(p[6], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 7], 6, 7);
pos.color2 = colorIndex(data[i + 7], 4, 5);
pos.color3 = colorIndex(data[i + 7], 2, 3);
pos.color4 = colorIndex(data[i + 7], 0, 1);
p[7] = voxel4(lookup, pos);
if(i + 9 < 268){
p[7] = strConcat(p[7], ',');
}
pos.x += 4;
gltfAccumulator = string(abi.encodePacked(gltfAccumulator, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]));
if (pos.x >= 32) {
pos.x = 0;
pos.y += 1;
}
}
gltfAccumulator = strConcat(gltfAccumulator, '],');
gltfAccumulator = strConcat(gltfAccumulator, '"materials": [');
for(uint i=0; i < colors.length; i++){
gltfAccumulator = strConcat(gltfAccumulator,'{"pbrMetallicRoughness": {"baseColorFactor": [');
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][0])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][1])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][2])), bytes(",") ));
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("0.5")));
}
else {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("1.0")));
}
gltfAccumulator = strConcat(gltfAccumulator,'],"metallicFactor": 0.0},');
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = strConcat(gltfAccumulator, '"alphaMode": "BLEND",');
}
gltfAccumulator = strConcat(gltfAccumulator, '"name": "material"}');
if(i + 1 < colors.length ){
gltfAccumulator = strConcat(gltfAccumulator, ',');
}
}
gltfAccumulator = strConcat(gltfAccumulator,'],');
gltfAccumulator = strConcat(gltfAccumulator, '"meshes": [');
for(uint i=0; i < colors.length; i++){
gltfAccumulator = strConcat(gltfAccumulator,'{"primitives": [{"attributes": {"POSITION": 0, "NORMAL": 1},"indices": 2,"material": ');
gltfAccumulator = strConcat(gltfAccumulator, Strings.toString(i));
gltfAccumulator = strConcat(gltfAccumulator,'}],"name": "Mesh');
gltfAccumulator = strConcat(gltfAccumulator, Strings.toString(i));
gltfAccumulator = strConcat(gltfAccumulator,'"}');
if(i + 1 < colors.length ){
gltfAccumulator = strConcat(gltfAccumulator, ',');
}
}
gltfAccumulator = strConcat(gltfAccumulator,'],');
gltfAccumulator = strConcat(gltfAccumulator, '"accessors": [');
gltfAccumulator = strConcat(gltfAccumulator, '{"bufferView" : 0,"componentType" : 5126,"count" : 24,"max" : [0.5,0.5,0.5],"min" : [-0.5,-0.5,-0.5],"type" : "VEC3"},');
gltfAccumulator = strConcat(gltfAccumulator, '{"bufferView" : 1,"componentType" : 5126,"count" : 24,"type" : "VEC3"},');
gltfAccumulator = strConcat(gltfAccumulator, '{"bufferView" : 2,"componentType" : 5123,"count" : 36,"type" : "SCALAR"}');
gltfAccumulator = strConcat(gltfAccumulator, '],');
gltfAccumulator = strConcat(gltfAccumulator, '"bufferViews": [');
gltfAccumulator = strConcat(gltfAccumulator, '{"buffer" : 0,"byteLength" : 288,"byteOffset" : 0},');
gltfAccumulator = strConcat(gltfAccumulator, '{"buffer" : 0,"byteLength" : 288,"byteOffset" : 288},');
gltfAccumulator = strConcat(gltfAccumulator, '{"buffer" : 0,"byteLength" : 72,"byteOffset" : 576}');
gltfAccumulator = strConcat(gltfAccumulator, '],');
gltfAccumulator = strConcat(gltfAccumulator, '"buffers": [{"byteLength": 648,"uri": "data:application/octet-stream;base64,');
//the strings below are the buffers for a voxel's vertex data.
//every node refers to a mesh described by this same buffer.
//initially I had a single buffer and applied a scale transform to every node depdnding on style
//but this was inefficient and caused a 4x bigger payload and longer execution time.
//when the "exploded" style is chosen the buffer is modified to be a smaller voxel.
//index and normal buffers are the same regardless of style.
if(voxelStyle < 2){
gltfAccumulator = strConcat(gltfAccumulator, 'AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAvwAAAL8AAAA/AAAAPwAAAL8AAAC/AAAAvwAAAL8AAAC/AAAAPwAAAD8AAAA/AAAAPwAAAL8AAAA/AAAAPwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAvwAAAD8AAAA/AAAAPwAAAD8AAAA/AAAAvwAAAD8AAAC/AAAAPwAAAD8AAAC/AAAAvwAAAL8AAAA/AAAAvwAAAD8AAAA/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAvwAAAL8AAAC/AAAAvwAAAD8AAAC/AAAAPwAAAL8AAAC/AAAAPwAAAD8AAAC/');
} else {
gltfAccumulator = strConcat(gltfAccumulator, 'AADAvgAAwL4AAMA+AADAPgAAwL4AAMA+AADAvgAAwD4AAMA+AADAPgAAwD4AAMA+AADAPgAAwL4AAMA+AADAvgAAwL4AAMA+AADAPgAAwL4AAMC+AADAvgAAwL4AAMC+AADAPgAAwD4AAMA+AADAPgAAwL4AAMA+AADAPgAAwD4AAMC+AADAPgAAwL4AAMC+AADAvgAAwD4AAMA+AADAPgAAwD4AAMA+AADAvgAAwD4AAMC+AADAPgAAwD4AAMC+AADAvgAAwL4AAMA+AADAvgAAwD4AAMA+AADAvgAAwL4AAMC+AADAvgAAwD4AAMC+AADAvgAAwL4AAMC+AADAvgAAwD4AAMC+AADAPgAAwL4AAMC+AADAPgAAwD4AAMC+');
}
gltfAccumulator = strConcat(gltfAccumulator, 'AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAgL8AAACAAAAAAAAAgL8AAACAAAAAAAAAgL8AAACAAAAAAAAAgL8AAACAAACAPwAAAAAAAACAAACAPwAAAAAAAACAAACAPwAAAAAAAACAAACAPwAAAAAAAACAAAAAAAAAgD8AAACAAAAAAAAAgD8AAACAAAAAAAAAgD8AAACAAAAAAAAAgD8AAACAAACAvwAAAAAAAACAAACAvwAAAAAAAACAAACAvwAAAAAAAACAAACAvwAAAAAAAACAAAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAABAAIAAwACAAEABAAFAAYABwAGAAUACAAJAAoACwAKAAkADAANAA4ADwAOAA0AEAARABIAEwASABEAFAAVABYAFwAWABUA"}]');
gltfAccumulator = strConcat(gltfAccumulator, '}');
return gltfAccumulator;
}
function byteToUint(bytes1 b) internal pure returns (uint256) {
return uint256(uint8(b));
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory result) {
result = string(abi.encodePacked(bytes(_a), bytes(_b)));
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
// 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;
import "../token/ERC721/extensions/IERC721Enumerable.sol";
// 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.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;
/**
* @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;
interface IBlitmap{
function ownerOf(uint256 tokenId) external view returns (address);
function tokenCreatorOf(uint256 tokenId) external view returns (address);
function tokenDataOf(uint256 tokenId) external view returns (bytes memory) ;
function tokenParentsOf(uint256 tokenId) external view returns (uint256, uint256);
function tokenSvgDataOf(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IFlipmap{
function ownerOf(uint256 tokenId) external view returns (address);
function tokenDataOf(uint256 tokenId) external view returns (bytes memory) ;
function tokenParentsOf(uint256 tokenId) external view returns (uint256, uint256);
function tokenSvgDataOf(uint256 tokenId) external view returns (string memory);
}
// 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;
/**
* @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 "../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;
/**
* @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;
}
}
// 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 "../IERC721.sol";
/**
* @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);
}
| glTF data built from blitmap/flipmap token data. Just like original SVGs data is built in chunks of 4 voxels at a time. The output is a 32 x 32 grid of voxels. Each voxel is a node in the scene that references 1 of 4 meshes depending on its color. There are 4 mesh primitives with the only difference being material index. There is only one mesh buffer: a voxel/cube. Voxel spacing and material transparency are affected by the tokens saved style./ | function tokenGltfData(bytes memory data, bytes1 style) public pure returns (string memory) {
(uint8 voxelStyle, uint8 transparencyIndex) = styleByteToInts(style);
string[32] memory lookup = [
"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23",
"24", "25", "26", "27", "28", "29", "30", "31"
];
glTFCursor memory pos;
uint256[3][4] memory colors = [
[byteToUint(data[0]), byteToUint(data[1]), byteToUint(data[2])],
[byteToUint(data[3]), byteToUint(data[4]), byteToUint(data[5])],
[byteToUint(data[6]), byteToUint(data[7]), byteToUint(data[8])],
[byteToUint(data[9]), byteToUint(data[10]), byteToUint(data[11])]
];
string[8] memory p;
string memory gltfAccumulator = '{"asset": {"generator": "Blitblox.sol","version": "2.0"},"scene": 0,"scenes": [{"nodes": [0]}],';
gltfAccumulator = strConcat(gltfAccumulator, '"nodes": [{"children": [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024],');
gltfAccumulator = strConcat(gltfAccumulator, '"matrix": [1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0]},');
for (uint i = 12; i < 268; i += 8) {
pos.color1 = colorIndex(data[i], 6, 7);
pos.color2 = colorIndex(data[i], 4, 5);
pos.color3 = colorIndex(data[i], 2, 3);
pos.color4 = colorIndex(data[i], 0, 1);
p[0] = voxel4(lookup, pos);
p[0] = strConcat(p[0], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 1], 6, 7);
pos.color2 = colorIndex(data[i + 1], 4, 5);
pos.color3 = colorIndex(data[i + 1], 2, 3);
pos.color4 = colorIndex(data[i + 1], 0, 1);
p[1] = voxel4(lookup, pos);
p[1] = strConcat(p[1], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 2], 6, 7);
pos.color2 = colorIndex(data[i + 2], 4, 5);
pos.color3 = colorIndex(data[i + 2], 2, 3);
pos.color4 = colorIndex(data[i + 2], 0, 1);
p[2] = voxel4(lookup, pos);
p[2] = strConcat(p[2], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 3], 6, 7);
pos.color2 = colorIndex(data[i + 3], 4, 5);
pos.color3 = colorIndex(data[i + 3], 2, 3);
pos.color4 = colorIndex(data[i + 3], 0, 1);
p[3] = voxel4(lookup, pos);
p[3] = strConcat(p[3], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 4], 6, 7);
pos.color2 = colorIndex(data[i + 4], 4, 5);
pos.color3 = colorIndex(data[i + 4], 2, 3);
pos.color4 = colorIndex(data[i + 4], 0, 1);
p[4] = voxel4(lookup, pos);
p[4] = strConcat(p[4], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 5], 6, 7);
pos.color2 = colorIndex(data[i + 5], 4, 5);
pos.color3 = colorIndex(data[i + 5], 2, 3);
pos.color4 = colorIndex(data[i + 5], 0, 1);
p[5] = voxel4(lookup, pos);
p[5] = strConcat(p[5], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 6], 6, 7);
pos.color2 = colorIndex(data[i + 6], 4, 5);
pos.color3 = colorIndex(data[i + 6], 2, 3);
pos.color4 = colorIndex(data[i + 6], 0, 1);
p[6] = voxel4(lookup, pos);
p[6] = strConcat(p[6], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 7], 6, 7);
pos.color2 = colorIndex(data[i + 7], 4, 5);
pos.color3 = colorIndex(data[i + 7], 2, 3);
pos.color4 = colorIndex(data[i + 7], 0, 1);
p[7] = voxel4(lookup, pos);
if(i + 9 < 268){
p[7] = strConcat(p[7], ',');
}
pos.x += 4;
gltfAccumulator = string(abi.encodePacked(gltfAccumulator, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]));
if (pos.x >= 32) {
pos.x = 0;
pos.y += 1;
}
}
gltfAccumulator = strConcat(gltfAccumulator, '],');
gltfAccumulator = strConcat(gltfAccumulator, '"materials": [');
for (uint i = 12; i < 268; i += 8) {
pos.color1 = colorIndex(data[i], 6, 7);
pos.color2 = colorIndex(data[i], 4, 5);
pos.color3 = colorIndex(data[i], 2, 3);
pos.color4 = colorIndex(data[i], 0, 1);
p[0] = voxel4(lookup, pos);
p[0] = strConcat(p[0], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 1], 6, 7);
pos.color2 = colorIndex(data[i + 1], 4, 5);
pos.color3 = colorIndex(data[i + 1], 2, 3);
pos.color4 = colorIndex(data[i + 1], 0, 1);
p[1] = voxel4(lookup, pos);
p[1] = strConcat(p[1], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 2], 6, 7);
pos.color2 = colorIndex(data[i + 2], 4, 5);
pos.color3 = colorIndex(data[i + 2], 2, 3);
pos.color4 = colorIndex(data[i + 2], 0, 1);
p[2] = voxel4(lookup, pos);
p[2] = strConcat(p[2], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 3], 6, 7);
pos.color2 = colorIndex(data[i + 3], 4, 5);
pos.color3 = colorIndex(data[i + 3], 2, 3);
pos.color4 = colorIndex(data[i + 3], 0, 1);
p[3] = voxel4(lookup, pos);
p[3] = strConcat(p[3], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 4], 6, 7);
pos.color2 = colorIndex(data[i + 4], 4, 5);
pos.color3 = colorIndex(data[i + 4], 2, 3);
pos.color4 = colorIndex(data[i + 4], 0, 1);
p[4] = voxel4(lookup, pos);
p[4] = strConcat(p[4], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 5], 6, 7);
pos.color2 = colorIndex(data[i + 5], 4, 5);
pos.color3 = colorIndex(data[i + 5], 2, 3);
pos.color4 = colorIndex(data[i + 5], 0, 1);
p[5] = voxel4(lookup, pos);
p[5] = strConcat(p[5], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 6], 6, 7);
pos.color2 = colorIndex(data[i + 6], 4, 5);
pos.color3 = colorIndex(data[i + 6], 2, 3);
pos.color4 = colorIndex(data[i + 6], 0, 1);
p[6] = voxel4(lookup, pos);
p[6] = strConcat(p[6], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 7], 6, 7);
pos.color2 = colorIndex(data[i + 7], 4, 5);
pos.color3 = colorIndex(data[i + 7], 2, 3);
pos.color4 = colorIndex(data[i + 7], 0, 1);
p[7] = voxel4(lookup, pos);
if(i + 9 < 268){
p[7] = strConcat(p[7], ',');
}
pos.x += 4;
gltfAccumulator = string(abi.encodePacked(gltfAccumulator, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]));
if (pos.x >= 32) {
pos.x = 0;
pos.y += 1;
}
}
gltfAccumulator = strConcat(gltfAccumulator, '],');
gltfAccumulator = strConcat(gltfAccumulator, '"materials": [');
for (uint i = 12; i < 268; i += 8) {
pos.color1 = colorIndex(data[i], 6, 7);
pos.color2 = colorIndex(data[i], 4, 5);
pos.color3 = colorIndex(data[i], 2, 3);
pos.color4 = colorIndex(data[i], 0, 1);
p[0] = voxel4(lookup, pos);
p[0] = strConcat(p[0], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 1], 6, 7);
pos.color2 = colorIndex(data[i + 1], 4, 5);
pos.color3 = colorIndex(data[i + 1], 2, 3);
pos.color4 = colorIndex(data[i + 1], 0, 1);
p[1] = voxel4(lookup, pos);
p[1] = strConcat(p[1], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 2], 6, 7);
pos.color2 = colorIndex(data[i + 2], 4, 5);
pos.color3 = colorIndex(data[i + 2], 2, 3);
pos.color4 = colorIndex(data[i + 2], 0, 1);
p[2] = voxel4(lookup, pos);
p[2] = strConcat(p[2], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 3], 6, 7);
pos.color2 = colorIndex(data[i + 3], 4, 5);
pos.color3 = colorIndex(data[i + 3], 2, 3);
pos.color4 = colorIndex(data[i + 3], 0, 1);
p[3] = voxel4(lookup, pos);
p[3] = strConcat(p[3], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 4], 6, 7);
pos.color2 = colorIndex(data[i + 4], 4, 5);
pos.color3 = colorIndex(data[i + 4], 2, 3);
pos.color4 = colorIndex(data[i + 4], 0, 1);
p[4] = voxel4(lookup, pos);
p[4] = strConcat(p[4], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 5], 6, 7);
pos.color2 = colorIndex(data[i + 5], 4, 5);
pos.color3 = colorIndex(data[i + 5], 2, 3);
pos.color4 = colorIndex(data[i + 5], 0, 1);
p[5] = voxel4(lookup, pos);
p[5] = strConcat(p[5], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 6], 6, 7);
pos.color2 = colorIndex(data[i + 6], 4, 5);
pos.color3 = colorIndex(data[i + 6], 2, 3);
pos.color4 = colorIndex(data[i + 6], 0, 1);
p[6] = voxel4(lookup, pos);
p[6] = strConcat(p[6], ',');
pos.x += 4;
pos.color1 = colorIndex(data[i + 7], 6, 7);
pos.color2 = colorIndex(data[i + 7], 4, 5);
pos.color3 = colorIndex(data[i + 7], 2, 3);
pos.color4 = colorIndex(data[i + 7], 0, 1);
p[7] = voxel4(lookup, pos);
if(i + 9 < 268){
p[7] = strConcat(p[7], ',');
}
pos.x += 4;
gltfAccumulator = string(abi.encodePacked(gltfAccumulator, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]));
if (pos.x >= 32) {
pos.x = 0;
pos.y += 1;
}
}
gltfAccumulator = strConcat(gltfAccumulator, '],');
gltfAccumulator = strConcat(gltfAccumulator, '"materials": [');
for(uint i=0; i < colors.length; i++){
gltfAccumulator = strConcat(gltfAccumulator,'{"pbrMetallicRoughness": {"baseColorFactor": [');
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][0])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][1])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][2])), bytes(",") ));
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("0.5")));
}
else {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("1.0")));
}
gltfAccumulator = strConcat(gltfAccumulator,'],"metallicFactor": 0.0},');
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = strConcat(gltfAccumulator, '"alphaMode": "BLEND",');
}
gltfAccumulator = strConcat(gltfAccumulator, '"name": "material"}');
for(uint i=0; i < colors.length; i++){
gltfAccumulator = strConcat(gltfAccumulator,'{"pbrMetallicRoughness": {"baseColorFactor": [');
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][0])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][1])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][2])), bytes(",") ));
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("0.5")));
}
else {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("1.0")));
}
gltfAccumulator = strConcat(gltfAccumulator,'],"metallicFactor": 0.0},');
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = strConcat(gltfAccumulator, '"alphaMode": "BLEND",');
}
gltfAccumulator = strConcat(gltfAccumulator, '"name": "material"}');
for(uint i=0; i < colors.length; i++){
gltfAccumulator = strConcat(gltfAccumulator,'{"pbrMetallicRoughness": {"baseColorFactor": [');
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][0])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][1])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][2])), bytes(",") ));
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("0.5")));
}
else {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("1.0")));
}
gltfAccumulator = strConcat(gltfAccumulator,'],"metallicFactor": 0.0},');
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = strConcat(gltfAccumulator, '"alphaMode": "BLEND",');
}
gltfAccumulator = strConcat(gltfAccumulator, '"name": "material"}');
for(uint i=0; i < colors.length; i++){
gltfAccumulator = strConcat(gltfAccumulator,'{"pbrMetallicRoughness": {"baseColorFactor": [');
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][0])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][1])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][2])), bytes(",") ));
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("0.5")));
}
else {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("1.0")));
}
gltfAccumulator = strConcat(gltfAccumulator,'],"metallicFactor": 0.0},');
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = strConcat(gltfAccumulator, '"alphaMode": "BLEND",');
}
gltfAccumulator = strConcat(gltfAccumulator, '"name": "material"}');
for(uint i=0; i < colors.length; i++){
gltfAccumulator = strConcat(gltfAccumulator,'{"pbrMetallicRoughness": {"baseColorFactor": [');
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][0])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][1])), bytes(",") ));
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes(intRGBValTosRGBVal(colors[i][2])), bytes(",") ));
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("0.5")));
}
else {
gltfAccumulator = string( abi.encodePacked(bytes(gltfAccumulator), bytes("1.0")));
}
gltfAccumulator = strConcat(gltfAccumulator,'],"metallicFactor": 0.0},');
if(voxelStyle % 2 == 1 && i == transparencyIndex) {
gltfAccumulator = strConcat(gltfAccumulator, '"alphaMode": "BLEND",');
}
gltfAccumulator = strConcat(gltfAccumulator, '"name": "material"}');
if(i + 1 < colors.length ){
gltfAccumulator = strConcat(gltfAccumulator, ',');
}
}
| 2,559,025 |
pragma solidity ^0.4.11;
// SafeMath Taken From FirstBlood
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
// ERC20 Interface
contract ERC20 {
function totalSupply() constant returns (uint totalSupply);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// ERC20Token
contract ERC20Token is ERC20, SafeMath {
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalTokens;
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function totalSupply() constant returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Wolk is ERC20Token {
// TOKEN INFO
string public constant name = "Wolk Protocol Token";
string public constant symbol = "WOLK";
uint256 public constant decimals = 18;
// RESERVE
uint256 public reserveBalance = 0;
uint16 public constant percentageETHReserve = 20;
// CONTRACT OWNER
address public owner = msg.sender;
address public multisigWallet;
modifier onlyOwner { assert(msg.sender == owner); _; }
// TOKEN GENERATION EVENT
mapping (address => uint256) contribution;
uint256 public constant tokenGenerationMin = 50 * 10**6 * 10**decimals;
uint256 public constant tokenGenerationMax = 500 * 10**6 * 10**decimals;
uint256 public start_block;
uint256 public end_block;
bool public saleCompleted = false;
modifier isTransferable { assert(saleCompleted); _; }
// WOLK SETTLERS
mapping (address => bool) settlers;
modifier onlySettler { assert(settlers[msg.sender] == true); _; }
// TOKEN GENERATION EVENTLOG
event WolkCreated(address indexed _to, uint256 _tokenCreated);
event WolkDestroyed(address indexed _from, uint256 _tokenDestroyed);
event LogRefund(address indexed _to, uint256 _value);
// @param _startBlock
// @param _endBlock
// @param _wolkWallet
// @return success
// @dev Wolk Genesis Event [only accessible by Contract Owner]
function wolkGenesis(uint256 _startBlock, uint256 _endBlock, address _wolkWallet) onlyOwner returns (bool success){
require( (totalTokens < 1) && (!settlers[msg.sender]) && (_endBlock > _startBlock) );
start_block = _startBlock;
end_block = _endBlock;
multisigWallet = _wolkWallet;
settlers[msg.sender] = true;
return true;
}
// @param _newOwner
// @return success
// @dev Transfering Contract Ownership. [only accessible by current Contract Owner]
function changeOwner(address _newOwner) onlyOwner returns (bool success){
owner = _newOwner;
settlers[_newOwner] = true;
return true;
}
// @dev Token Generation Event for Wolk Protocol Token. TGE Participant send Eth into this func in exchange of Wolk Protocol Token
function tokenGenerationEvent() payable external {
require(!saleCompleted);
require( (block.number >= start_block) && (block.number <= end_block) );
uint256 tokens = safeMul(msg.value, 5*10**9); //exchange rate
uint256 checkedSupply = safeAdd(totalTokens, tokens);
require(checkedSupply <= tokenGenerationMax);
totalTokens = checkedSupply;
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
contribution[msg.sender] = safeAdd(contribution[msg.sender], msg.value);
WolkCreated(msg.sender, tokens); // logs token creation
}
// @dev If Token Generation Minimum is Not Met, TGE Participants can call this func and request for refund
function refund() external {
require( (contribution[msg.sender] > 0) && (!saleCompleted) && (totalTokens < tokenGenerationMin) && (block.number > end_block) );
uint256 tokenBalance = balances[msg.sender];
uint256 refundBalance = contribution[msg.sender];
balances[msg.sender] = 0;
contribution[msg.sender] = 0;
totalTokens = safeSub(totalTokens, tokenBalance);
WolkDestroyed(msg.sender, tokenBalance);
LogRefund(msg.sender, refundBalance);
msg.sender.transfer(refundBalance);
}
// @dev Finalizing the Token Generation Event. 20% of Eth will be kept in contract to provide liquidity
function finalize() onlyOwner {
require( (!saleCompleted) && (totalTokens >= tokenGenerationMin) );
saleCompleted = true;
end_block = block.number;
reserveBalance = safeDiv(safeMul(this.balance, percentageETHReserve), 100);
var withdrawalBalance = safeSub(this.balance, reserveBalance);
msg.sender.transfer(withdrawalBalance);
}
}
contract WolkProtocol is Wolk {
// WOLK NETWORK PROTOCOL
uint256 public burnBasisPoints = 500; // Burn rate (in BP) when Service Provider withdraws from data buyers' accounts
mapping (address => mapping (address => bool)) authorized; // holds which accounts have approved which Service Providers
mapping (address => uint256) feeBasisPoints; // Fee (in BP) earned by Service Provider when depositing to data seller
// WOLK PROTOCOL Events:
event AuthorizeServiceProvider(address indexed _owner, address _serviceProvider);
event DeauthorizeServiceProvider(address indexed _owner, address _serviceProvider);
event SetServiceProviderFee(address indexed _serviceProvider, uint256 _feeBasisPoints);
event BurnTokens(address indexed _from, address indexed _serviceProvider, uint256 _value);
// @param _burnBasisPoints
// @return success
// @dev Set BurnRate on Wolk Protocol -- only Wolk Foundation can set this, affects Service Provider settleBuyer
function setBurnRate(uint256 _burnBasisPoints) onlyOwner returns (bool success) {
require( (_burnBasisPoints > 0) && (_burnBasisPoints <= 1000) );
burnBasisPoints = _burnBasisPoints;
return true;
}
// @param _serviceProvider
// @param _feeBasisPoints
// @return success
// @dev Set Service Provider fee -- only Contract Owner can do this, affects Service Provider settleSeller
function setServiceFee(address _serviceProvider, uint256 _feeBasisPoints) onlyOwner returns (bool success) {
if ( _feeBasisPoints <= 0 || _feeBasisPoints > 4000){
// revoke Settler privilege
settlers[_serviceProvider] = false;
feeBasisPoints[_serviceProvider] = 0;
return false;
}else{
feeBasisPoints[_serviceProvider] = _feeBasisPoints;
settlers[_serviceProvider] = true;
SetServiceProviderFee(_serviceProvider, _feeBasisPoints);
return true;
}
}
// @param _serviceProvider
// @return _feeBasisPoints
// @dev Check service ee (in BP) for a given provider
function checkServiceFee(address _serviceProvider) constant returns (uint256 _feeBasisPoints) {
return feeBasisPoints[_serviceProvider];
}
// @param _buyer
// @param _value
// @return success
// @dev Service Provider Settlement with Buyer: a small percent is burnt (set in setBurnRate, stored in burnBasisPoints) when funds are transferred from buyer to Service Provider [only accessible by settlers]
function settleBuyer(address _buyer, uint256 _value) onlySettler returns (bool success) {
require( (burnBasisPoints > 0) && (burnBasisPoints <= 1000) && authorized[_buyer][msg.sender] ); // Buyer must authorize Service Provider
if ( balances[_buyer] >= _value && _value > 0) {
var burnCap = safeDiv(safeMul(_value, burnBasisPoints), 10000);
var transferredToServiceProvider = safeSub(_value, burnCap);
balances[_buyer] = safeSub(balances[_buyer], _value);
balances[msg.sender] = safeAdd(balances[msg.sender], transferredToServiceProvider);
totalTokens = safeSub(totalTokens, burnCap);
Transfer(_buyer, msg.sender, transferredToServiceProvider);
BurnTokens(_buyer, msg.sender, burnCap);
return true;
} else {
return false;
}
}
// @param _seller
// @param _value
// @return success
// @dev Service Provider Settlement with Seller: a small percent is kept by Service Provider (set in setServiceFee, stored in feeBasisPoints) when funds are transferred from Service Provider to seller [only accessible by settlers]
function settleSeller(address _seller, uint256 _value) onlySettler returns (bool success) {
// Service Providers have a % fee for Sellers (e.g. 20%)
var serviceProviderBP = feeBasisPoints[msg.sender];
require( (serviceProviderBP > 0) && (serviceProviderBP <= 4000) );
if (balances[msg.sender] >= _value && _value > 0) {
var fee = safeDiv(safeMul(_value, serviceProviderBP), 10000);
var transferredToSeller = safeSub(_value, fee);
balances[_seller] = safeAdd(balances[_seller], transferredToSeller);
Transfer(msg.sender, _seller, transferredToSeller);
return true;
} else {
return false;
}
}
// @param _providerToAdd
// @return success
// @dev Buyer authorizes the Service Provider (to call settleBuyer). For security reason, _providerToAdd needs to be whitelisted by Wolk Foundation first
function authorizeProvider(address _providerToAdd) returns (bool success) {
require(settlers[_providerToAdd]);
authorized[msg.sender][_providerToAdd] = true;
AuthorizeServiceProvider(msg.sender, _providerToAdd);
return true;
}
// @param _providerToRemove
// @return success
// @dev Buyer deauthorizes the Service Provider (from calling settleBuyer)
function deauthorizeProvider(address _providerToRemove) returns (bool success) {
authorized[msg.sender][_providerToRemove] = false;
DeauthorizeServiceProvider(msg.sender, _providerToRemove);
return true;
}
// @param _owner
// @param _serviceProvider
// @return authorizationStatus
// @dev Check authorization between account and Service Provider
function checkAuthorization(address _owner, address _serviceProvider) constant returns (bool authorizationStatus) {
return authorized[_owner][_serviceProvider];
}
// @param _owner
// @param _providerToAdd
// @return authorizationStatus
// @dev Grant authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]
// @note Explicit permission from balance owner MUST be obtained beforehand
function grantService(address _owner, address _providerToAdd) onlyOwner returns (bool authorizationStatus) {
var isPreauthorized = authorized[_owner][msg.sender];
if (isPreauthorized && settlers[_providerToAdd] ) {
authorized[_owner][_providerToAdd] = true;
AuthorizeServiceProvider(msg.sender, _providerToAdd);
return true;
}else{
return false;
}
}
// @param _owner
// @param _providerToRemove
// @return authorization_status
// @dev Revoke authorization between account and Service Provider on buyers' behalf [only accessible by Contract Owner]
// @note Explicit permission from balance owner are NOT required for disabling ill-intent Service Provider
function removeService(address _owner, address _providerToRemove) onlyOwner returns (bool authorizationStatus) {
authorized[_owner][_providerToRemove] = false;
DeauthorizeServiceProvider(_owner, _providerToRemove);
return true;
}
}
contract BancorFormula is SafeMath {
// Taken from https://github.com/bancorprotocol/contracts/blob/master/solidity/contracts/BancorFormula.sol
uint8 constant PRECISION = 32; // fractional bits
uint256 constant FIXED_ONE = uint256(1) << PRECISION; // 0x100000000
uint256 constant FIXED_TWO = uint256(2) << PRECISION; // 0x200000000
uint256 constant MAX_VAL = uint256(1) << (256 - PRECISION); // 0x0000000100000000000000000000000000000000000000000000000000000000
/**
@dev given a token supply, reserve, CRR and a deposit amount (in the reserve token), calculates the return for a given change (in the main token)
Formula:
Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / 100) - 1)
@param _supply token total supply
@param _reserveBalance total reserve
@param _reserveRatio constant reserve ratio, 1-100
@param _depositAmount deposit amount, in reserve token
@return purchase return amount
*/
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _depositAmount) public constant returns (uint256) {
// validate input
require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100);
// special case for 0 deposit amount
if (_depositAmount == 0)
return 0;
uint256 baseN = safeAdd(_depositAmount, _reserveBalance);
uint256 temp;
// special case if the CRR = 100
if (_reserveRatio == 100) {
temp = safeMul(_supply, baseN) / _reserveBalance;
return safeSub(temp, _supply);
}
uint256 resN = power(baseN, _reserveBalance, _reserveRatio, 100);
temp = safeMul(_supply, resN) / FIXED_ONE;
uint256 result = safeSub(temp, _supply);
// from the result, we deduct the minimal increment, which is a
// function of S and precision.
return safeSub(result, _supply / 0x100000000);
}
/**
@dev given a token supply, reserve, CRR and a sell amount (in the main token), calculates the return for a given change (in the reserve token)
Formula:
Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / 100)))
@param _supply token total supply
@param _reserveBalance total reserve
@param _reserveRatio constant reserve ratio, 1-100
@param _sellAmount sell amount, in the token itself
@return sale return amount
*/
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _sellAmount) public constant returns (uint256) {
// validate input
require(_supply != 0 && _reserveBalance != 0 && _reserveRatio > 0 && _reserveRatio <= 100 && _sellAmount <= _supply);
// special case for 0 sell amount
if (_sellAmount == 0)
return 0;
uint256 baseN = safeSub(_supply, _sellAmount);
uint256 temp1;
uint256 temp2;
// special case if the CRR = 100
if (_reserveRatio == 100) {
temp1 = safeMul(_reserveBalance, _supply);
temp2 = safeMul(_reserveBalance, baseN);
return safeSub(temp1, temp2) / _supply;
}
// special case for selling the entire supply
if (_sellAmount == _supply)
return _reserveBalance;
uint256 resN = power(_supply, baseN, 100, _reserveRatio);
temp1 = safeMul(_reserveBalance, resN);
temp2 = safeMul(_reserveBalance, FIXED_ONE);
uint256 result = safeSub(temp1, temp2) / resN;
// from the result, we deduct the minimal increment, which is a
// function of R and precision.
return safeSub(result, _reserveBalance / 0x100000000);
}
/**
@dev Calculate (_baseN / _baseD) ^ (_expN / _expD)
Returns result upshifted by PRECISION
This method is overflow-safe
*/
function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal returns (uint256 resN) {
uint256 logbase = ln(_baseN, _baseD);
// Not using safeDiv here, since safeDiv protects against
// precision loss. Itβs unavoidable, however
// Both `ln` and `fixedExp` are overflow-safe.
resN = fixedExp(safeMul(logbase, _expN) / _expD);
return resN;
}
/**
input range:
- numerator: [1, uint256_max >> PRECISION]
- denominator: [1, uint256_max >> PRECISION]
output range:
[0, 0x9b43d4f8d6]
This method asserts outside of bounds
*/
function ln(uint256 _numerator, uint256 _denominator) internal returns (uint256) {
// denominator > numerator: less than one yields negative values. Unsupported
assert(_denominator <= _numerator);
// log(1) is the lowest we can go
assert(_denominator != 0 && _numerator != 0);
// Upper 32 bits are scaled off by PRECISION
assert(_numerator < MAX_VAL);
assert(_denominator < MAX_VAL);
return fixedLoge( (_numerator * FIXED_ONE) / _denominator);
}
/**
input range:
[0x100000000,uint256_max]
output range:
[0, 0x9b43d4f8d6]
This method asserts outside of bounds
*/
function fixedLoge(uint256 _x) internal returns (uint256 logE) {
/*
Since `fixedLog2_min` output range is max `0xdfffffffff`
(40 bits, or 5 bytes), we can use a very large approximation
for `ln(2)`. This one is used since itβs the max accuracy
of Python `ln(2)`
0xb17217f7d1cf78 = ln(2) * (1 << 56)
*/
//Cannot represent negative numbers (below 1)
assert(_x >= FIXED_ONE);
uint256 log2 = fixedLog2(_x);
logE = (log2 * 0xb17217f7d1cf78) >> 56;
}
/**
Returns log2(x >> 32) << 32 [1]
So x is assumed to be already upshifted 32 bits, and
the result is also upshifted 32 bits.
[1] The function returns a number which is lower than the
actual value
input-range :
[0x100000000,uint256_max]
output-range:
[0,0xdfffffffff]
This method asserts outside of bounds
*/
function fixedLog2(uint256 _x) internal returns (uint256) {
// Numbers below 1 are negative.
assert( _x >= FIXED_ONE);
uint256 hi = 0;
while (_x >= FIXED_TWO) {
_x >>= 1;
hi += FIXED_ONE;
}
for (uint8 i = 0; i < PRECISION; ++i) {
_x = (_x * _x) / FIXED_ONE;
if (_x >= FIXED_TWO) {
_x >>= 1;
hi += uint256(1) << (PRECISION - 1 - i);
}
}
return hi;
}
/**
fixedExp is a βprotectedβ version of `fixedExpUnsafe`, which
asserts instead of overflows
*/
function fixedExp(uint256 _x) internal returns (uint256) {
assert(_x <= 0x386bfdba29);
return fixedExpUnsafe(_x);
}
/**
fixedExp
Calculates e^x according to maclauren summation:
e^x = 1+x+x^2/2!...+x^n/n!
and returns e^(x>>32) << 32, that is, upshifted for accuracy
Input range:
- Function ok at <= 242329958953
- Function fails at >= 242329958954
This method is is visible for testcases, but not meant for direct use.
The values in this method been generated via the following python snippet:
def calculateFactorials():
ββ"Method to print out the factorials for fixedExpβββ
ni = []
ni.append( 295232799039604140847618609643520000000) # 34!
ITERATIONS = 34
for n in range( 1, ITERATIONS,1 ) :
ni.append(math.floor(ni[n - 1] / n))
print( β\n β.join([βxi = (xi * _x) >> PRECISION;\n res += xi * %s;β % hex(int(x)) for x in ni]))
*/
function fixedExpUnsafe(uint256 _x) internal returns (uint256) {
uint256 xi = FIXED_ONE;
uint256 res = 0xde1bc4d19efcac82445da75b00000000 * xi;
xi = (xi * _x) >> PRECISION;
res += xi * 0xde1bc4d19efcb0000000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x6f0de268cf7e58000000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x2504a0cd9a7f72000000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x9412833669fdc800000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x1d9d4d714865f500000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x4ef8ce836bba8c0000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xb481d807d1aa68000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x16903b00fa354d000000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x281cdaac677b3400000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x402e2aad725eb80000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x5d5a6c9f31fe24000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x7c7890d442a83000000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x9931ed540345280000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xaf147cf24ce150000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xbac08546b867d000000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xbac08546b867d00000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0xafc441338061b8000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x9c3cabbc0056e000000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x839168328705c80000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x694120286c04a0000;
xi = (xi * _x) >> PRECISION;
res += xi * 0x50319e98b3d2c400;
xi = (xi * _x) >> PRECISION;
res += xi * 0x3a52a1e36b82020;
xi = (xi * _x) >> PRECISION;
res += xi * 0x289286e0fce002;
xi = (xi * _x) >> PRECISION;
res += xi * 0x1b0c59eb53400;
xi = (xi * _x) >> PRECISION;
res += xi * 0x114f95b55400;
xi = (xi * _x) >> PRECISION;
res += xi * 0xaa7210d200;
xi = (xi * _x) >> PRECISION;
res += xi * 0x650139600;
xi = (xi * _x) >> PRECISION;
res += xi * 0x39b78e80;
xi = (xi * _x) >> PRECISION;
res += xi * 0x1fd8080;
xi = (xi * _x) >> PRECISION;
res += xi * 0x10fbc0;
xi = (xi * _x) >> PRECISION;
res += xi * 0x8c40;
xi = (xi * _x) >> PRECISION;
res += xi * 0x462;
xi = (xi * _x) >> PRECISION;
res += xi * 0x22;
return res / 0xde1bc4d19efcac82445da75b00000000;
}
}
contract WolkExchange is WolkProtocol, BancorFormula {
uint256 public maxPerExchangeBP = 50;
// @param _maxPerExchange
// @return success
// @dev Set max sell token amount per transaction -- only Wolk Foundation can set this
function setMaxPerExchange(uint256 _maxPerExchange) onlyOwner returns (bool success) {
require( (_maxPerExchange >= 10) && (_maxPerExchange <= 100) );
maxPerExchangeBP = _maxPerExchange;
return true;
}
// @return Estimated Liquidation Cap
// @dev Liquidation Cap per transaction is used to ensure proper price discovery for Wolk Exchange
function EstLiquidationCap() public constant returns (uint256) {
if (saleCompleted){
var liquidationMax = safeDiv(safeMul(totalTokens, maxPerExchangeBP), 10000);
if (liquidationMax < 100 * 10**decimals){
liquidationMax = 100 * 10**decimals;
}
return liquidationMax;
}else{
return 0;
}
}
// @param _wolkAmount
// @return ethReceivable
// @dev send Wolk into contract in exchange for eth, at an exchange rate based on the Bancor Protocol derivation and decrease totalSupply accordingly
function sellWolk(uint256 _wolkAmount) isTransferable() external returns(uint256) {
uint256 sellCap = EstLiquidationCap();
uint256 ethReceivable = calculateSaleReturn(totalTokens, reserveBalance, percentageETHReserve, _wolkAmount);
require( (sellCap >= _wolkAmount) && (balances[msg.sender] >= _wolkAmount) && (this.balance > ethReceivable) );
balances[msg.sender] = safeSub(balances[msg.sender], _wolkAmount);
totalTokens = safeSub(totalTokens, _wolkAmount);
reserveBalance = safeSub(this.balance, ethReceivable);
WolkDestroyed(msg.sender, _wolkAmount);
msg.sender.transfer(ethReceivable);
return ethReceivable;
}
// @return wolkReceivable
// @dev send eth into contract in exchange for Wolk tokens, at an exchange rate based on the Bancor Protocol derivation and increase totalSupply accordingly
function purchaseWolk() isTransferable() payable external returns(uint256){
uint256 wolkReceivable = calculatePurchaseReturn(totalTokens, reserveBalance, percentageETHReserve, msg.value);
totalTokens = safeAdd(totalTokens, wolkReceivable);
balances[msg.sender] = safeAdd(balances[msg.sender], wolkReceivable);
reserveBalance = safeAdd(reserveBalance, msg.value);
WolkCreated(msg.sender, wolkReceivable);
return wolkReceivable;
}
// @param _exactWolk
// @return ethRefundable
// @dev send eth into contract in exchange for exact amount of Wolk tokens with margin of error of no more than 1 Wolk.
// @note Purchase with the insufficient eth will be cancelled and returned; exceeding eth balanance from purchase, if any, will be returned.
function purchaseExactWolk(uint256 _exactWolk) isTransferable() payable external returns(uint256){
uint256 wolkReceivable = calculatePurchaseReturn(totalTokens, reserveBalance, percentageETHReserve, msg.value);
if (wolkReceivable < _exactWolk){
// Cancel Insufficient Purchase
revert();
return msg.value;
}else {
var wolkDiff = safeSub(wolkReceivable, _exactWolk);
uint256 ethRefundable = 0;
// Refund if wolkDiff exceeds 1 Wolk
if (wolkDiff < 10**decimals){
// Credit Buyer Full amount if within margin of error
totalTokens = safeAdd(totalTokens, wolkReceivable);
balances[msg.sender] = safeAdd(balances[msg.sender], wolkReceivable);
reserveBalance = safeAdd(reserveBalance, msg.value);
WolkCreated(msg.sender, wolkReceivable);
return 0;
}else{
ethRefundable = calculateSaleReturn( safeAdd(totalTokens, wolkReceivable) , safeAdd(reserveBalance, msg.value), percentageETHReserve, wolkDiff);
totalTokens = safeAdd(totalTokens, _exactWolk);
balances[msg.sender] = safeAdd(balances[msg.sender], _exactWolk);
reserveBalance = safeAdd(reserveBalance, safeSub(msg.value, ethRefundable));
WolkCreated(msg.sender, _exactWolk);
msg.sender.transfer(ethRefundable);
return ethRefundable;
}
}
}
} | _serviceProvider return _feeBasisPoints Check service ee (in BP) for a given provider | function checkServiceFee(address _serviceProvider) constant returns (uint256 _feeBasisPoints) {
return feeBasisPoints[_serviceProvider];
}
| 6,433,446 |
./full_match/1/0x04108C0B1E615aB7765383F35E4fAb8628760646/sources/project_/contracts/DioneStaking.sol | Update withdrawal status | function updateWithdrawStatus(bool _status) external onlyOwner {
require(isFinished, "DioneStaking: NOT_FINISHED");
isWithdrawable = _status;
emit UpdateWithdrawStatus(_status);
}
| 2,914,924 |
./partial_match/1/0xB309C8644dE4de778CB53d837565c0ccabc6aa32/sources/MummifiedCoin.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("MummifiedCoin", "MC") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 10;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 10;
uint256 _earlySellLiquidityFee = 0;
uint256 _earlySellMarketingFee = 20;
uint256 totalSupply = 169 * 1e8 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 9,150,756 |
./full_match/4/0xBa7a638a06dBCF2A87CE4425d67f3EA224bFE5b9/sources/github/NFT-Worlds/NFT-Worlds-Staking-Rental-Contract/src/NFTWEscrow.sol | Claim all rewards from caller into a given address | function claim(address to) external virtual override {
_updateRewardsPerWeight(0, false);
uint rewardAmount = _updateUserRewards(_msgSender(), 0, false);
rewards[_msgSender()].accumulated = 0;
TransferHelper.safeTransfer(WRLD_ERC20_ADDR, to, rewardAmount);
emit RewardClaimed(to, rewardAmount);
}
| 740,736 |
/*
* Copyright Β©οΈ 2020 Curio AG (Company Number FL-0002.594.728-9)
* Incorporated and registered in Liechtenstein.
*
* Copyright Β©οΈ 2020 Curio Capital AG (Company Number CHE-211.446.654)
* Incorporated and registered in Zug, Switzerland.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./UniversalERC20.sol";
abstract contract FundsManager is Ownable {
using UniversalERC20 for IERC20;
/**
* @dev Withdraw funds by owner
* @param token Token address
* @param amount The amount of token to withdraw
**/
function withdrawFunds(IERC20 token, uint256 amount) public onlyOwner {
token.universalTransfer(owner(), amount);
}
/**
* @dev Withdraw all funds by owner
* @param tokens Token addresses array
**/
function withdrawAllFunds(IERC20[] memory tokens) public onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
IERC20 token = tokens[i];
token.universalTransfer(
owner(),
token.universalBalanceOf(address(this))
);
}
}
}
| Withdraw funds by owner token Token address amount The amount of token to withdraw/ | function withdrawFunds(IERC20 token, uint256 amount) public onlyOwner {
token.universalTransfer(owner(), amount);
}
| 1,009,232 |
./partial_match/1/0xeB40E25AF8F5F22Bb201f53971480beA0094Cd65/sources/src/v0.8/functions/tests/1_0_0/testhelpers/FunctionsClientUpgradeHelper.sol | Callback that is invoked once the DON has resolved the request or hit an error requestId The request ID, returned by sendRequest() response Aggregated response from the user code err Aggregated error from the user code or from the execution pipeline Either response or error parameter will be set, but never both/ | function fulfillRequest(bytes32 requestId, bytes memory response, bytes memory err) internal override {
emit ResponseReceived(requestId, response, err);
}
| 4,322,740 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "./../interfaces/IExchangeAdapter.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";
// solhint-disable func-name-mixedcase
// solhint-disable var-name-mixedcase
interface ICurveFrax {
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount)
external
returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received
) external returns (uint256);
}
interface ICurve3Crv {
function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount)
external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
}
contract CurveFraxAdapter is IExchangeAdapter {
address public constant fraxLp = 0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B;
ICurve3Crv public constant pool3Crv =
ICurve3Crv(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
function indexByUnderlyingCoin(address coin) public pure returns (int128) {
if (coin == 0x853d955aCEf822Db058eb8505911ED77F175b99e) return 1; // frax
if (coin == 0x6B175474E89094C44Da98b954EedeAC495271d0F) return 2; // dai
if (coin == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 3; // usdc
if (coin == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 4; // usdt
return 0;
}
function indexByCoin(address coin) public pure returns (int128) {
if (coin == 0x853d955aCEf822Db058eb8505911ED77F175b99e) return 1; // frax
if (coin == 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490) return 2; // 3Crv
return 0;
}
// 0x6012856e => executeSwap(address,address,address,uint256)
function executeSwap(
address pool,
address fromToken,
address toToken,
uint256 amount
) external payable returns (uint256) {
ICurveFrax curve = ICurveFrax(pool);
int128 i = indexByUnderlyingCoin(fromToken);
int128 j = indexByUnderlyingCoin(toToken);
require(i != 0 && j != 0, "CurveFraxAdapter: can't swap");
return curve.exchange_underlying(i - 1, j - 1, amount, 0);
}
// 0xe83bbb76 => enterPool(address,address,address,uint256)
function enterPool(
address pool,
address fromToken,
uint256 amount
) external payable returns (uint256) {
ICurveFrax curve = ICurveFrax(pool);
uint128 i = uint128(indexByCoin(fromToken));
if (i != 0) {
uint256[2] memory entryVector_;
entryVector_[i - 1] = amount;
return curve.add_liquidity(entryVector_, 0);
}
i = uint128(indexByUnderlyingCoin(fromToken));
IERC20 threeCrvToken = IERC20(
0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490
);
require(i != 0, "CrvFraxAdapter: can't enter");
uint256[3] memory entryVector;
entryVector[i - 2] = amount;
pool3Crv.add_liquidity(entryVector, 0);
return
curve.add_liquidity([0, threeCrvToken.balanceOf(address(this))], 0);
}
// 0x9d756192 => exitPool(address,address,address,uint256)
function exitPool(
address pool,
address toToken,
uint256 amount
) external payable returns (uint256) {
ICurveFrax curve = ICurveFrax(pool);
int128 i = indexByCoin(toToken);
if (i != 0) {
return curve.remove_liquidity_one_coin(amount, i - 1, 0);
}
i = indexByUnderlyingCoin(toToken);
require(i != 0, "CrvFraxAdapter: can't exit");
uint256 amount3Crv = curve.remove_liquidity_one_coin(amount, 1, 0);
pool3Crv.remove_liquidity_one_coin(amount3Crv, i - 2, 0);
return IERC20(toToken).balanceOf(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IExchangeAdapter {
// 0x6012856e => executeSwap(address,address,address,uint256)
function executeSwap(
address pool,
address fromToken,
address toToken,
uint256 amount
) external payable returns (uint256);
// 0x73ec962e => enterPool(address,address,uint256)
function enterPool(
address pool,
address fromToken,
uint256 amount
) external payable returns (uint256);
// 0x660cb8d4 => exitPool(address,address,uint256)
function exitPool(
address pool,
address toToken,
uint256 amount
) external payable returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
// 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);
} | Interface of the ERC20 standard as defined in the EIP./ | 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);
} | 6,204,503 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface PotLike {
function chi() external view returns (uint);
function pie(address) external view returns (uint);
function drip() external returns (uint);
function join(uint) external;
function exit(uint) external;
}
interface GemLike {
function approve(address, uint) external;
function balanceOf(address) external view returns (uint);
function transferFrom(address, address, uint) external returns (bool);
}
interface VatLike {
function dai(address) external view returns (uint);
function hope(address) external;
}
interface DaiJoinLike {
function vat() external returns (VatLike);
function dai() external returns (GemLike);
function join(address, uint) external payable;
function exit(address, uint) external;
}
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
contract Cheese {
/// @notice EIP-20 token name for this token
string public constant name = "Cheese";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "CHEESE";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => CToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
struct CompMarketState {
/// @notice The market's last updated compBorrowIndex or compSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
CToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes COMP, per block
uint public compRate;
/// @notice The portion of compRate that each market currently receives
mapping(address => uint) public compSpeeds;
/// @notice The mining cheese rule, 0 - minting by supply, 1 - minting by borrow
uint public miningRule;
/// @notice The COMP market supply state for each market
mapping(address => CompMarketState) public compSupplyState;
/// @notice The COMP market borrow state for each market
mapping(address => CompMarketState) public compBorrowState;
/// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compSupplierIndex;
/// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compBorrowerIndex;
/// @notice The COMP accrued but not yet transferred to each user
mapping(address => uint) public compAccrued;
/// @notice The mining CHEESE Buff
mapping(address => uint) public miningBuff;
}
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR, //0
UNAUTHORIZED, //1
COMPTROLLER_MISMATCH, //2
INSUFFICIENT_SHORTFALL, //3
INSUFFICIENT_LIQUIDITY, //4
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR, //0
UNAUTHORIZED, //1
BAD_INPUT, //2
COMPTROLLER_REJECTION, //3
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK, //0
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, //1
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, //2
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, //3
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, //4
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, //5
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, //6
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, //7
BORROW_ACCRUE_INTEREST_FAILED, //8
BORROW_CASH_NOT_AVAILABLE, //9
BORROW_FRESHNESS_CHECK, //10
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, //11
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, //12
BORROW_MARKET_NOT_LISTED, //13
BORROW_COMPTROLLER_REJECTION, //14
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param sToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken sToken) external view returns (uint);
}
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 addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @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 Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
/**
* @notice Emitted when pendingComptrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation β address(0)
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin β address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
}
contract CErc20Delegator is CTokenInterface, CErc20Interface, CDelegatorInterface {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_,
address implementation_,
bytes memory becomeImplementationData) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)",
underlying_,
comptroller_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_));
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
// Set the proper admin now that initialization is done
admin = admin_;
}
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == admin, "CErc20Delegator::_setImplementation: Caller must be admin");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param 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) {
mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
redeemTokens; // Shh
delegateAndReturn();
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
redeemAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
borrowAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
repayAmount; // Shh
delegateAndReturn();
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
borrower; repayAmount; // Shh
delegateAndReturn();
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
borrower; repayAmount; cTokenCollateral; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint amount) external returns (bool) {
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool) {
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
spender; amount; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint) {
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint) {
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
owner; // Shh
delegateAndReturn();
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
account; // Shh
delegateToViewAndReturn();
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external returns (uint) {
delegateAndReturn();
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external returns (uint) {
account; // Shh
delegateAndReturn();
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
account; // Shh
delegateToViewAndReturn();
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public returns (uint) {
delegateAndReturn();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
delegateToViewAndReturn();
}
/**
* @notice Applies accrued interest to total borrows and reserves.
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
delegateAndReturn();
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) {
liquidator; borrower; seizeTokens; // Shh
delegateAndReturn();
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
newPendingAdmin; // Shh
delegateAndReturn();
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
newComptroller; // Shh
delegateAndReturn();
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) {
newReserveFactorMantissa; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
delegateAndReturn();
}
/**
* @notice Accrues interest and adds reserves by transferring from admin
* @param addAmount Amount of reserves to add
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
addAmount; // Shh
delegateAndReturn();
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external returns (uint) {
reduceAmount; // Shh
delegateAndReturn();
}
/**
* @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
newInterestRateModel; // Shh
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"CErc20Delegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
}
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin β address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor β€ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount β€ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event MarketActionPaused(CToken cToken, string action, bool pauseState);
/// @notice Emitted when market comped status is changed
event MarketComped(CToken cToken, bool isComped);
/// @notice Emitted when COMP rate is changed
event NewCompRate(uint oldCompRate, uint newCompRate);
/// @notice Emitted when a new COMP speed is calculated for a market
event CompSpeedUpdated(CToken indexed cToken, uint newSpeed, uint totalUtility, uint utility);
/// @notice Emitted when COMP is distributed to a supplier
event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
/// @notice Emitted when COMP is distributed to a borrower
event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex);
/// @notice The threshold above which the flywheel transfers COMP, in wei
//uint public constant compClaimThreshold = 0.001e18;
uint public constant compClaimThreshold = 1e18;
/// @notice The initial COMP index for a market
uint224 public constant compInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) public returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed,) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed");
// semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already βinβ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the accountβs list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, minter, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, redeemer, false);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa : CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa : CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateCompSupplyIndex(cTokenCollateral);
distributeSupplierComp(cTokenCollateral, borrower, false);
distributeSupplierComp(cTokenCollateral, liquidator, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, src, false);
distributeSupplierComp(cToken, dst, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars;
// Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) {// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa : vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * cTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored();
// Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa : newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa : closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa : closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param cToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa : newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa : liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa : liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken();
// Sanity check to make sure its really a CToken
markets[address(cToken)] = Market({isListed : true, isComped : true, collateralFactorMantissa : 0});
_addMarketInternal(address(cToken));
borrowGuardianPaused[address(cToken)] = true;
//stage 1, not allow borrow
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(cToken)] = state;
emit MarketActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(cToken)] = state;
emit MarketActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** Comp Distribution ***/
/**
* @notice Recalculate and update COMP speeds for all COMP markets
*/
function refreshCompSpeeds() public {
require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds");
refreshCompSpeedsInternal();
}
function refreshCompSpeedsInternal() internal {
CToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa : cToken.borrowIndex()});
updateCompSupplyIndex(address(cToken));
updateCompBorrowIndex(address(cToken), borrowIndex);
}
Exp memory borrowTotalUtility = Exp({mantissa : 0});
uint borrowAssetCount = 0;
Exp memory borrowAverageUtility = Exp({mantissa : 0});
//calculate Borrow asset totalUtility
if (miningRule == 1) {//mining by borrow
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets_[i];
if (markets[address(cToken)].isComped && !borrowGuardianPaused[address(cToken)]) {
Exp memory assetPrice = Exp({mantissa : oracle.getUnderlyingPrice(cToken)});
Exp memory utility = mul_(assetPrice, cToken.totalBorrows());
borrowTotalUtility = add_(borrowTotalUtility, utility);
borrowAssetCount++;
}
}
if (borrowAssetCount > 0) {
borrowAverageUtility = div_(borrowTotalUtility, borrowAssetCount);
}
}
Exp memory totalUtility = Exp({mantissa : 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets_[i];
if (markets[address(cToken)].isComped) {
Exp memory utility;
uint buff = miningBuff[address(cToken)];
Exp memory price = Exp({mantissa : oracle.getUnderlyingPrice(cToken)});
if (buff == 0) buff = 1;
if (miningRule == 0) {//mining by supply
//supply * exchange rate = asset balance
Exp memory supply = Exp({mantissa: cToken.totalSupply()});
//Exp memory exchangeRate = Exp({mantissa: cToken.exchangeRateStored()});
uint assetBalance = mul_(cToken.exchangeRateStored(), supply); // div e18
//usd price * balance = utility
Exp memory realUtility = Exp({mantissa: mul_(assetBalance, price.mantissa)});
utility = mul_(realUtility, buff); //buff
} else if (miningRule == 1) {//mining by borrow
if (borrowGuardianPaused[address(cToken)]) {
//averageUtility with in price
utility = mul_(borrowAverageUtility, buff);
} else {
Exp memory realUtility = mul_(price, cToken.totalBorrows());
utility = mul_(realUtility, buff);
}
} else {//can't support
revert();
}
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0;
compSpeeds[address(cToken)] = newSpeed;
emit CompSpeedUpdated(cToken, newSpeed, totalUtility.mantissa, utilities[i].mantissa);
}
}
/**
* @notice Accrue COMP to the market by updating the supply index
* @param cToken The market whose supply index to update
*/
function updateCompSupplyIndex(address cToken) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
uint supplySpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = CToken(cToken).totalSupply();
uint compAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa : 0});
Double memory index = add_(Double({mantissa : supplyState.index}), ratio);
compSupplyState[cToken] = CompMarketState({
index : safe224(index.mantissa, "new index exceeds 224 bits"),
block : safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue COMP to the market by updating the borrow index
* @param cToken The market whose borrow index to update
*/
function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
uint borrowSpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex);
uint compAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa : 0});
Double memory index = add_(Double({mantissa : borrowState.index}), ratio);
compBorrowState[cToken] = CompMarketState({
index : safe224(index.mantissa, "new index exceeds 224 bits"),
block : safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate COMP accrued by a supplier and possibly transfer it to them
* @param cToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute COMP to
*/
function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
Double memory supplyIndex = Double({mantissa : supplyState.index});
Double memory supplierIndex = Double({mantissa : compSupplierIndex[cToken][supplier]});
compSupplierIndex[cToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold);
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate COMP accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param cToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute COMP to
*/
function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
Double memory borrowIndex = Double({mantissa : borrowState.index});
Double memory borrowerIndex = Double({mantissa : compBorrowerIndex[cToken][borrower]});
compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta);
compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold);
emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer COMP to the user, if they are above the threshold
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param user The address of the user to transfer COMP to
* @param userAccrued The amount of COMP to (possibly) transfer
* @return The amount of COMP which was NOT transferred to the user
*/
function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Cheese cheese = Cheese(getCheeseAddress());
uint cheeseRemaining = cheese.balanceOf(address(this));
if (userAccrued <= cheeseRemaining) {
cheese.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public {
return claimComp(holder, allMarkets);
}
/**
* @notice Claim all the comp accrued by holder in the specified markets
* @param holder The address to claim COMP for
* @param cTokens The list of markets to claim COMP in
*/
function claimComp(address holder, CToken[] memory cTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimComp(holders, cTokens, true, true);
}
/**
* @notice Claim all comp accrued by the holders
* @param holders The addresses to claim COMP for
* @param cTokens The list of markets to claim COMP in
* @param borrowers Whether or not to claim COMP earned by borrowing
* @param suppliers Whether or not to claim COMP earned by supplying
*/
function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < cTokens.length; i++) {
CToken cToken = cTokens[i];
require(markets[address(cToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa : cToken.borrowIndex()});
updateCompBorrowIndex(address(cToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true);
}
}
if (suppliers == true) {
updateCompSupplyIndex(address(cToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierComp(address(cToken), holders[j], true);
}
}
}
}
/*** Comp Distribution Admin ***/
/**
* @notice Set the amount of COMP distributed per block
* @param compRate_ The amount of COMP wei per block to distribute
*/
function _setCompRate(uint compRate_) public {
require(adminOrInitializing(), "only admin can change comp rate");
uint oldRate = compRate;
compRate = compRate_;
emit NewCompRate(oldRate, compRate_);
refreshCompSpeedsInternal();
}
/**
* @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel
* @param cTokens The addresses of the markets to add
*/
function _addCompMarkets(address[] memory cTokens) public {
require(adminOrInitializing(), "only admin can add comp market");
for (uint i = 0; i < cTokens.length; i++) {
_addCompMarketInternal(cTokens[i]);
}
refreshCompSpeedsInternal();
}
function _addCompMarketInternal(address cToken) internal {
Market storage market = markets[cToken];
require(market.isListed == true, "comp market is not listed");
require(market.isComped == false, "comp market already added");
market.isComped = true;
emit MarketComped(CToken(cToken), true);
if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) {
compSupplyState[cToken] = CompMarketState({
index : compInitialIndex,
block : safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) {
compBorrowState[cToken] = CompMarketState({
index : compInitialIndex,
block : safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
/**
* @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel
* @param cToken The address of the market to drop
*/
function _dropCompMarket(address cToken) public {
require(msg.sender == admin, "only admin can drop comp market");
Market storage market = markets[cToken];
require(market.isComped == true, "market is not a comp market");
market.isComped = false;
emit MarketComped(CToken(cToken), false);
refreshCompSpeedsInternal();
}
function _setMiningBuff(address cToken, uint buff) public {
require(adminOrInitializing(), "only admin can change cheese rate");
miningBuff[cToken] = buff;
}
function _changeMiningRule() public {
if (msg.sender != admin || miningRule != 0) {
return;
}
/*
require(adminOrInitializing(), "only admin can set mining rule");
require(miningRule == 0, "only change mining rule from 0 to 1");
*/
miningRule = 1;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the COMP token
* @return The address of COMP
*/
function getCheeseAddress() public view returns (address) {
return 0xB6Ab412EacEb551d62f8eC63a1d2F30c01e3A2C0;
}
}
contract CErc20 is CToken, CErc20Interface {
constructor() public {
admin = msg.sender;
}
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param 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;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
contract CErc20Delegate is CErc20, CDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
}
contract CErc20Immutable is CErc20 {
/**
* @notice Construct a new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// Initialize the market
initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
}
contract CEther is CToken {
/**
* @notice Construct a new CEther money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
*/
constructor(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set the proper admin now that initialization is done
admin = admin_;
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Reverts upon any failure
*/
function mint() external payable {
(uint err,) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @dev Reverts upon any failure
*/
function repayBorrow() external payable {
(uint err,) = repayBorrowInternal(msg.value);
requireNoError(err, "repayBorrow failed");
}
/**
* @notice Sender repays a borrow belonging to borrower
* @dev Reverts upon any failure
* @param borrower the account with the debt being payed off
*/
function repayBorrowBehalf(address borrower) external payable {
(uint err,) = repayBorrowBehalfInternal(borrower, msg.value);
requireNoError(err, "repayBorrowBehalf failed");
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @dev Reverts upon any failure
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
*/
function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable {
(uint err,) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral);
requireNoError(err, "liquidateBorrow failed");
}
/**
* @notice Send Ether to CEther to mint
*/
function () external payable {
(uint err,) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of Ether, before this message
* @dev This excludes the value of the current message, if any
* @return The quantity of Ether owned by this contract
*/
function getCashPrior() internal view returns (uint) {
(MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value);
require(err == MathError.NO_ERROR);
return startingBalance;
}
/**
* @notice Perform the actual transfer in, which is a no-op
* @param from Address sending the Ether
* @param amount Amount of Ether being sent
* @return The actual amount of Ether transferred
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
// Sanity checks
require(msg.sender == from, "sender mismatch");
require(msg.value == amount, "value mismatch");
return amount;
}
function doTransferOut(address payable to, uint amount) internal {
/* Send the Ether, with minimal gas and revert on failure */
to.transfer(amount);
}
function requireNoError(uint errCode, string memory message) internal pure {
if (errCode == uint(Error.NO_ERROR)) {
return;
}
bytes memory fullMessage = new bytes(bytes(message).length + 5);
uint i;
for (i = 0; i < bytes(message).length; i++) {
fullMessage[i] = bytes(message)[i];
}
fullMessage[i+0] = byte(uint8(32));
fullMessage[i+1] = byte(uint8(40));
fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 )));
fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 )));
fullMessage[i+4] = byte(uint8(41));
require(errCode == uint(Error.NO_ERROR), string(fullMessage));
}
}
contract CDaiDelegate is CErc20Delegate {
/**
* @notice DAI adapter address
*/
address public daiJoinAddress;
/**
* @notice DAI Savings Rate (DSR) pot address
*/
address public potAddress;
/**
* @notice DAI vat address
*/
address public vatAddress;
/**
* @notice Delegate interface to become the implementation
* @param data The encoded arguments for becoming
*/
function _becomeImplementation(bytes memory data) public {
require(msg.sender == admin, "only the admin may initialize the implementation");
(address daiJoinAddress_, address potAddress_) = abi.decode(data, (address, address));
return _becomeImplementation(daiJoinAddress_, potAddress_);
}
/**
* @notice Explicit interface to become the implementation
* @param daiJoinAddress_ DAI adapter address
* @param potAddress_ DAI Savings Rate (DSR) pot address
*/
function _becomeImplementation(address daiJoinAddress_, address potAddress_) internal {
// Get dai and vat and sanity check the underlying
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress_);
PotLike pot = PotLike(potAddress_);
GemLike dai = daiJoin.dai();
VatLike vat = daiJoin.vat();
require(address(dai) == underlying, "DAI must be the same as underlying");
// Remember the relevant addresses
daiJoinAddress = daiJoinAddress_;
potAddress = potAddress_;
vatAddress = address(vat);
// Approve moving our DAI into the vat through daiJoin
dai.approve(daiJoinAddress, uint(-1));
// Approve the pot to transfer our funds within the vat
vat.hope(potAddress);
vat.hope(daiJoinAddress);
// Accumulate DSR interest -- must do this in order to doTransferIn
pot.drip();
// Transfer all cash in (doTransferIn does this regardless of amount)
doTransferIn(address(this), 0);
}
/**
* @notice Delegate interface to resign the implementation
*/
function _resignImplementation() public {
require(msg.sender == admin, "only the admin may abandon the implementation");
// Transfer all cash out of the DSR - note that this relies on self-transfer
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress);
PotLike pot = PotLike(potAddress);
VatLike vat = VatLike(vatAddress);
// Accumulate interest
pot.drip();
// Calculate the total amount in the pot, and move it out
uint pie = pot.pie(address(this));
pot.exit(pie);
// Checks the actual balance of DAI in the vat after the pot exit
uint bal = vat.dai(address(this));
// Remove our whole balance
daiJoin.exit(address(this), bal / RAY);
}
/*** CToken Overrides ***/
/**
* @notice Accrues DSR then applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
// Accumulate DSR interest
PotLike(potAddress).drip();
// Accumulate CToken interest
return super.accrueInterest();
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
PotLike pot = PotLike(potAddress);
uint pie = pot.pie(address(this));
return mul(pot.chi(), pie) / RAY;
}
/**
* @notice Transfer the underlying to this contract and sweep into DSR pot
* @param from Address to transfer funds from
* @param amount Amount of underlying to transfer
* @return The actual amount that is transferred
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
// Perform the EIP-20 transfer in
EIP20Interface token = EIP20Interface(underlying);
require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return");
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress);
GemLike dai = GemLike(underlying);
PotLike pot = PotLike(potAddress);
VatLike vat = VatLike(vatAddress);
// Convert all our DAI to internal DAI in the vat
daiJoin.join(address(this), dai.balanceOf(address(this)));
// Checks the actual balance of DAI in the vat after the join
uint bal = vat.dai(address(this));
// Calculate the percentage increase to th pot for the entire vat, and move it in
// Note: We may leave a tiny bit of DAI in the vat...but we do the whole thing every time
uint pie = bal / pot.chi();
pot.join(pie);
return amount;
}
/**
* @notice Transfer the underlying from this contract, after sweeping out of DSR pot
* @param to Address to transfer funds to
* @param amount Amount of underlying to transfer
*/
function doTransferOut(address payable to, uint amount) internal {
DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress);
PotLike pot = PotLike(potAddress);
// Calculate the percentage decrease from the pot, and move that much out
// Note: Use a slightly larger pie size to ensure that we get at least amount in the vat
uint pie = add(mul(amount, RAY) / pot.chi(), 1);
pot.exit(pie);
daiJoin.exit(to, amount);
}
/*** Maker Internals ***/
uint256 constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "add-overflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
}
| Check caller is admin | function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
require(newComptroller.isComptroller(), "marker method returned false");
comptroller = newComptroller;
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
| 7,349,276 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import '../interfaces/ISafeBox.sol';
import '../interfaces/ICompActionTrigger.sol';
import '../interfaces/IActionPools.sol';
import '../interfaces/IBuyback.sol';
import "../utils/TenMath.sol";
import "./SafeBoxCanCTokenImplETH.sol";
contract SafeBoxCanCTokenETH is SafeBoxCanCTokenImplETH, ReentrancyGuard, Ownable, ICompActionTrigger, ISafeBox {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct BorrowInfo {
address strategy; // borrow from strategy
uint256 pid; // borrow to pool
address owner; // borrower
uint256 amount; // borrow amount
uint256 bPoints; // borrow proportion
}
// supply manager
uint256 public accDebtPerSupply; // platform debt is shared to each supply lptoken
// borrow manager
BorrowInfo[] public borrowInfo; // borrow order info
mapping(address => mapping(address => mapping(uint256 => uint256))) public borrowIndex; // _account, _strategy, _pid, mapping id of borrowinfo, base from 1
mapping(address => uint256) public accountBorrowPoints; // _account, amount
uint256 public lastBorrowCurrent; // last settlement for
uint256 public borrowTotalPoints; // total of user bPoints
uint256 public borrowTotalAmountWithPlatform; // total of user borrows and interests and platform
uint256 public borrowTotalAmount; // total of user borrows and interests
uint256 public borrowTotal; // total of user borrows
uint256 public borrowLimitRate = 7e8; // borrow limit, max = borrowTotal * borrowLimitRate / 1e9, default=80%
uint256 public borrowMinAmount; // borrow min amount limit
mapping(address => bool) public blacklist; // deposit blacklist
bool public depositEnabled = true;
bool public emergencyRepayEnabled;
bool public emergencyWithdrawEnabled;
address public override bank; // borrow can from bank only
address public override token; // deposit and borrow token
address public compActionPool; // action pool for borrow rewards
uint256 public constant CTOKEN_BORROW = 1; // action pool borrow action id
uint256 public optimalUtilizationRate1 = 6e8; // Lending rate, ideal 1e9, default = 60%
uint256 public optimalUtilizationRate2 = 7.5e8; // Lending rate, ideal 1e9, default = 75%
uint256 public stableRateSlope1 = 2e9; // loan interest times in max borrow rate
uint256 public stableRateSlope2 = 20e9; // loan interest times in max borrow rate
address public iBuyback;
event SafeBoxDeposit(address indexed user, uint256 amount);
event SafeBoxWithdraw(address indexed user, uint256 amount);
event SafeBoxClaim(address indexed user, uint256 amount);
event SetBlacklist(address indexed _account, bool _newset);
event SetBuyback(address indexed buyback);
event SetBorrowLimitRate(uint256 oldRate, uint256 newRate);
event SetOptimalUtilizationRate(uint256 oldV1, uint256 oldV2, uint256 newV1, uint256 newV2);
event SetStableRateSlope(uint256 oldV1, uint256 oldV2, uint256 newV1, uint256 newV2);
constructor (
address _bank,
address _cToken
) public SafeBoxCanCTokenImplETH(_cToken) {
token = baseToken();
require(IERC20(token).totalSupply() >= 0, 'token error');
bank = _bank;
// 0 id Occupied, Available bid never be zero
borrowInfo.push(BorrowInfo(address(0), 0, address(0), 0, 0));
}
modifier onlyBank() {
require(bank == msg.sender, 'borrow only from bank');
_;
}
// link to actionpool , for borrower s allowance
function getCATPoolInfo(uint256 _pid) external virtual override view
returns (address lpToken, uint256 allocRate, uint256 totalPoints, uint256 totalAmount) {
_pid;
lpToken = token;
allocRate = 5e8; // never use
totalPoints = borrowTotalPoints;
totalAmount = borrowTotalAmountWithPlatform;
}
function getCATUserAmount(uint256 _pid, address _account) external virtual override view
returns (uint256 acctPoints) {
_pid;
acctPoints = accountBorrowPoints[_account];
}
function getSource() external virtual override view returns (string memory) {
return 'channels';
}
// blacklist
function setBlacklist(address _account, bool _newset) external onlyOwner {
blacklist[_account] = _newset;
emit SetBlacklist(_account, _newset);
}
function setCompAcionPool(address _compActionPool) public onlyOwner {
compActionPool = _compActionPool;
}
function setBuyback(address _iBuyback) public onlyOwner {
iBuyback = _iBuyback;
emit SetBuyback(_iBuyback);
}
function setBorrowLimitRate(uint256 _borrowLimitRate) external onlyOwner {
require(_borrowLimitRate <= 1e9, 'rate too high');
emit SetBorrowLimitRate(borrowLimitRate, _borrowLimitRate);
borrowLimitRate = _borrowLimitRate;
}
function setBorrowMinAmount(uint256 _borrowMinAmount) external onlyOwner {
borrowMinAmount = _borrowMinAmount;
}
function setEmergencyRepay(bool _emergencyRepayEnabled) external onlyOwner {
emergencyRepayEnabled = _emergencyRepayEnabled;
}
function setEmergencyWithdraw(bool _emergencyWithdrawEnabled) external onlyOwner {
emergencyWithdrawEnabled = _emergencyWithdrawEnabled;
}
// for platform borrow interest rate
function setOptimalUtilizationRate(uint256 _optimalUtilizationRate1, uint256 _optimalUtilizationRate2) external onlyOwner {
require(_optimalUtilizationRate1 <= 1e9 &&
_optimalUtilizationRate2 <= 1e9 &&
_optimalUtilizationRate1 < _optimalUtilizationRate2
, 'rate set error');
emit SetOptimalUtilizationRate(optimalUtilizationRate1, optimalUtilizationRate2, _optimalUtilizationRate1, _optimalUtilizationRate2);
optimalUtilizationRate1 = _optimalUtilizationRate1;
optimalUtilizationRate2 = _optimalUtilizationRate2;
}
function setStableRateSlope(uint256 _stableRateSlope1, uint256 _stableRateSlope2) external onlyOwner {
require(_stableRateSlope1 <= 1e4*1e9 && _stableRateSlope1 >= 1e9 &&
_stableRateSlope2 <= 1e4*1e9 && _stableRateSlope2 >= 1e9 , 'rate set error');
emit SetStableRateSlope(stableRateSlope1, stableRateSlope2, _stableRateSlope1, _stableRateSlope2);
stableRateSlope1 = _stableRateSlope1;
stableRateSlope2 = _stableRateSlope2;
}
function supplyRatePerBlock() external override view returns (uint256) {
return ctokenSupplyRatePerBlock();
}
function borrowRatePerBlock() external override view returns (uint256) {
return ctokenBorrowRatePerBlock().mul(getBorrowFactorPrewiew()).div(1e9);
}
function borrowInfoLength() external override view returns (uint256) {
return borrowInfo.length.sub(1);
}
function getBorrowInfo(uint256 _bid) external override view
returns (address owner, uint256 amount, address strategy, uint256 pid) {
strategy = borrowInfo[_bid].strategy;
pid = borrowInfo[_bid].pid;
owner = borrowInfo[_bid].owner;
amount = borrowInfo[_bid].amount;
}
function getBorrowFactorPrewiew() public virtual view returns (uint256) {
return _getBorrowFactor(getDepositTotal());
}
function getBorrowFactor() public virtual returns (uint256) {
return _getBorrowFactor(call_balanceOfBaseToken_this());
}
function _getBorrowFactor(uint256 supplyAmount) internal virtual view returns (uint256 value) {
if(supplyAmount <= 0) {
return uint256(1e9);
}
uint256 borrowRate = getBorrowTotal().mul(1e9).div(supplyAmount);
if(borrowRate <= optimalUtilizationRate1) {
return uint256(1e9);
}
uint256 value1 = stableRateSlope1.sub(1e9).mul(borrowRate.sub(optimalUtilizationRate1))
.div(uint256(1e9).sub(optimalUtilizationRate1))
.add(uint256(1e9));
if(borrowRate <= optimalUtilizationRate2) {
value = value1;
return value;
}
uint256 value2 = stableRateSlope2.sub(1e9).mul(borrowRate.sub(optimalUtilizationRate2))
.div(uint256(1e9).sub(optimalUtilizationRate2))
.add(uint256(1e9));
value = value2 > value1 ? value2 : value1;
}
function getBorrowTotal() public virtual override view returns (uint256) {
return borrowTotalAmountWithPlatform;
}
function getDepositTotal() public virtual override view returns (uint256) {
return totalSupply().mul(getBaseTokenPerLPToken()).div(1e18);
}
function getBaseTokenPerLPToken() public virtual override view returns (uint256) {
return getBaseTokenPerCToken();
}
function pendingSupplyAmount(address _account) external virtual override view returns (uint256 value) {
value = call_balanceOf(address(this), _account).mul(getBaseTokenPerLPToken()).div(1e18);
}
function pendingBorrowAmount(uint256 _bid) public virtual override view returns (uint256 value) {
value = borrowInfo[_bid].amount;
}
// borrow interest, the sum of filda interest and platform interest
function pendingBorrowRewards(uint256 _bid) public virtual override view returns (uint256 value) {
if(borrowTotalPoints <= 0) {
return 0;
}
value = borrowInfo[_bid].bPoints.mul(borrowTotalAmountWithPlatform).div(borrowTotalPoints);
value = TenMath.safeSub(value, borrowInfo[_bid].amount);
}
// deposit
function deposit(uint256 _value) external virtual override nonReentrant {
update();
IERC20(token).safeTransferFrom(msg.sender, address(this), _value);
_deposit(msg.sender, _value);
}
function _deposit(address _account, uint256 _value) internal returns (uint256) {
require(depositEnabled, 'safebox closed');
require(!blacklist[_account], 'address in blacklist');
// token held in contract
uint256 balanceInput = call_balanceOf(token, address(this));
require(balanceInput > 0 && balanceInput >= _value, 'where s token?');
// update booking, mintValue is number of deposit credentials
uint256 mintValue = ctokenDeposit(_value);
if(mintValue > 0) {
_mint(_account, mintValue);
}
emit SafeBoxDeposit(_account, mintValue);
return mintValue;
}
function withdraw(uint256 _tTokenAmount) external virtual override nonReentrant {
update();
_withdraw(msg.sender, _tTokenAmount);
}
function _withdraw(address _account, uint256 _tTokenAmount) internal returns (uint256) {
// withdraw if lptokens value is not up borrowLimitRate
if(_tTokenAmount > balanceOf(_account)) {
_tTokenAmount = balanceOf(_account);
}
uint256 maxBorrowAmount = call_balanceOfCToken_this().sub(_tTokenAmount)
.mul(getBaseTokenPerLPToken()).div(1e18)
.mul(borrowLimitRate).div(1e9);
require(maxBorrowAmount >= borrowTotalAmountWithPlatform, 'no money to withdraw');
_burn(_account, uint256(_tTokenAmount));
if(accDebtPerSupply > 0) {
// If platform loss, the loss will be shared by supply
uint256 debtAmount = _tTokenAmount.mul(accDebtPerSupply).div(1e18);
require(_tTokenAmount >= debtAmount, 'debt too much');
_tTokenAmount = _tTokenAmount.sub(debtAmount);
}
ctokenWithdraw(_tTokenAmount);
tokenSafeTransfer(address(token), _account);
emit SafeBoxWithdraw(_account, _tTokenAmount);
return _tTokenAmount;
}
function claim(uint256 _value) external virtual override nonReentrant {
update();
_claim(msg.sender, uint256(_value));
}
function _claim(address _account, uint256 _value) internal {
emit SafeBoxClaim(_account, _value);
}
function getBorrowId(address _strategy, uint256 _pid, address _account)
public virtual override view returns (uint256 borrowId) {
borrowId = borrowIndex[_account][_strategy][_pid];
}
function getBorrowId(address _strategy, uint256 _pid, address _account, bool _add)
external virtual override onlyBank returns (uint256 borrowId) {
require(_strategy != address(0), 'borrowid _strategy error');
require(_account != address(0), 'borrowid _account error');
borrowId = getBorrowId(_strategy, _pid, _account);
if(borrowId == 0 && _add) {
borrowInfo.push(BorrowInfo(_strategy, _pid, _account, 0, 0));
borrowId = borrowInfo.length.sub(1);
borrowIndex[_account][_strategy][_pid] = borrowId;
}
require(borrowId > 0, 'not found borrowId');
}
function borrow(uint256 _bid, uint256 _value, address _to) external virtual override onlyBank {
update();
_borrow(_bid, _value, _to);
}
function _borrow(uint256 _bid, uint256 _value, address _to) internal {
// withdraw if lptokens value is not up borrowLimitRate
uint256 maxBorrowAmount = call_balanceOfCToken_this()
.mul(getBaseTokenPerLPToken()).div(1e18)
.mul(borrowLimitRate).div(1e9);
require(maxBorrowAmount >= borrowTotalAmountWithPlatform.add(_value), 'no money to borrow');
require(_value >= borrowMinAmount, 'borrow amount too low');
BorrowInfo storage borrowCurrent = borrowInfo[_bid];
// borrow
uint256 ubalance = ctokenBorrow(_value);
require(ubalance == _value, 'token borrow error');
tokenSafeTransfer(address(token), _to);
// booking
uint256 addPoint = _value;
if(borrowTotalPoints > 0) {
addPoint = _value.mul(borrowTotalPoints).div(borrowTotalAmountWithPlatform);
}
borrowCurrent.bPoints = borrowCurrent.bPoints.add(addPoint);
borrowTotalPoints = borrowTotalPoints.add(addPoint);
borrowTotalAmountWithPlatform = borrowTotalAmountWithPlatform.add(_value);
lastBorrowCurrent = call_borrowBalanceCurrent_this();
borrowCurrent.amount = borrowCurrent.amount.add(_value);
borrowTotal = borrowTotal.add(_value);
borrowTotalAmount = borrowTotalAmount.add(_value);
// notify for action pool
uint256 accountBorrowPointsOld = accountBorrowPoints[borrowCurrent.owner];
accountBorrowPoints[borrowCurrent.owner] = accountBorrowPoints[borrowCurrent.owner].add(addPoint);
if(compActionPool != address(0) && addPoint > 0) {
IActionPools(compActionPool).onAcionIn(CTOKEN_BORROW, borrowCurrent.owner,
accountBorrowPointsOld, accountBorrowPoints[borrowCurrent.owner]);
}
return ;
}
function repay(uint256 _bid, uint256 _value) external virtual override {
update();
_repay(_bid, _value);
}
function _repay(uint256 _bid, uint256 _value) internal {
BorrowInfo storage borrowCurrent = borrowInfo[_bid];
uint256 removedPoints;
if(_value >= pendingBorrowRewards(_bid).add(borrowCurrent.amount)) {
removedPoints = borrowCurrent.bPoints;
}else{
removedPoints = _value.mul(borrowTotalPoints).div(borrowTotalAmountWithPlatform);
removedPoints = TenMath.min(removedPoints, borrowCurrent.bPoints);
}
// booking
uint256 userAmount = removedPoints.mul(borrowCurrent.amount).div(borrowCurrent.bPoints); // to reduce amount for booking
uint256 repayAmount = removedPoints.mul(borrowTotalAmount).div(borrowTotalPoints); // to repay = amount + interest
uint256 platformAmount = TenMath.safeSub(removedPoints.mul(borrowTotalAmountWithPlatform).div(borrowTotalPoints),
repayAmount); // platform interest
borrowCurrent.bPoints = TenMath.safeSub(borrowCurrent.bPoints, removedPoints);
borrowTotalPoints = TenMath.safeSub(borrowTotalPoints, removedPoints);
borrowTotalAmountWithPlatform = TenMath.safeSub(borrowTotalAmountWithPlatform, repayAmount.add(platformAmount));
lastBorrowCurrent = call_borrowBalanceCurrent_this();
borrowCurrent.amount = TenMath.safeSub(borrowCurrent.amount, userAmount);
borrowTotal = TenMath.safeSub(borrowTotal, userAmount);
borrowTotalAmount = TenMath.safeSub(borrowTotalAmount, repayAmount);
// platform interest will buyback
if(platformAmount > 0 && iBuyback != address(0)) {
IERC20(token).approve(iBuyback, platformAmount);
IBuyback(iBuyback).buyback(token, platformAmount);
}
// repay borrow
repayAmount = TenMath.min(repayAmount, lastBorrowCurrent);
ctokenRepayBorrow(repayAmount);
lastBorrowCurrent = call_borrowBalanceCurrent_this();
// return of the rest
tokenSafeTransfer(token, msg.sender);
// notify for action pool
uint256 accountBorrowPointsOld = accountBorrowPoints[borrowCurrent.owner];
accountBorrowPoints[borrowCurrent.owner] = TenMath.safeSub(accountBorrowPoints[borrowCurrent.owner], removedPoints);
if(compActionPool != address(0) && removedPoints > 0) {
IActionPools(compActionPool).onAcionOut(CTOKEN_BORROW, borrowCurrent.owner,
accountBorrowPointsOld, accountBorrowPoints[borrowCurrent.owner]);
}
return ;
}
function emergencyWithdraw() external virtual override nonReentrant {
require(emergencyWithdrawEnabled, 'not in emergency');
uint256 withdrawAmount = call_balanceOf(address(this), msg.sender);
_burn(msg.sender, withdrawAmount);
if(accDebtPerSupply > 0) {
// If platform loss, the loss will be shared by supply
uint256 debtAmount = withdrawAmount.mul(accDebtPerSupply).div(1e18);
require(withdrawAmount >= debtAmount, 'debt too much');
withdrawAmount = withdrawAmount.sub(debtAmount);
}
// withdraw ctoken
ctokenWithdraw(withdrawAmount);
tokenSafeTransfer(address(token), msg.sender);
}
function emergencyRepay(uint256 _bid) external virtual override nonReentrant {
require(emergencyRepayEnabled, 'not in emergency');
// in emergency mode , only repay loan
BorrowInfo storage borrowCurrent = borrowInfo[_bid];
uint256 repayAmount = borrowCurrent.amount;
IERC20(baseToken()).safeTransferFrom(msg.sender, address(this), repayAmount);
ctokenRepayBorrow(repayAmount);
uint256 accountBorrowPointsOld = accountBorrowPoints[borrowCurrent.owner];
accountBorrowPoints[borrowCurrent.owner] = TenMath.safeSub(accountBorrowPoints[borrowCurrent.owner], borrowCurrent.bPoints);
// booking
borrowTotal = TenMath.safeSub(borrowTotal, repayAmount);
borrowTotalPoints = TenMath.safeSub(borrowTotalPoints, borrowCurrent.bPoints);
borrowTotalAmount = TenMath.safeSub(borrowTotalAmount, repayAmount);
borrowTotalAmountWithPlatform = TenMath.safeSub(borrowTotalAmountWithPlatform, repayAmount);
borrowCurrent.amount = 0;
borrowCurrent.bPoints = 0;
lastBorrowCurrent = call_borrowBalanceCurrent_this();
}
function update() public virtual override {
_update();
}
function _update() internal {
// update borrow interest
uint256 lastBorrowCurrentNow = call_borrowBalanceCurrent_this();
if(lastBorrowCurrentNow != lastBorrowCurrent && borrowTotal > 0) {
if(lastBorrowCurrentNow >= lastBorrowCurrent) {
// booking
uint256 newDebtAmount1 = lastBorrowCurrentNow.sub(lastBorrowCurrent);
uint256 newDebtAmount2 = newDebtAmount1.mul(getBorrowFactor()).div(1e9);
borrowTotalAmount = borrowTotalAmount.add(newDebtAmount1);
borrowTotalAmountWithPlatform = borrowTotalAmountWithPlatform.add(newDebtAmount2);
}
lastBorrowCurrent = lastBorrowCurrentNow;
}
// manage ctoken amount
uint256 uCTokenTotalAmount = call_balanceOfCToken_this();
if(uCTokenTotalAmount >= totalSupply()) {
// The platform has no debt
accDebtPerSupply = 0;
}
if(totalSupply() > 0 && accDebtPerSupply > 0) {
// The platform has debt, uCTokenTotalAmount will be totalSupply()
uCTokenTotalAmount = uCTokenTotalAmount.add(accDebtPerSupply.mul(totalSupply()).div(1e18));
}
if(uCTokenTotalAmount < totalSupply()) {
// totalSupply() != 0 new debt divided equally
accDebtPerSupply = accDebtPerSupply.add(totalSupply().sub(uCTokenTotalAmount).mul(1e18).div(totalSupply()));
} else if(uCTokenTotalAmount > totalSupply() && accDebtPerSupply > 0) {
// reduce debt divided equally
uint256 accDebtReduce = uCTokenTotalAmount.sub(totalSupply()).mul(1e18).div(totalSupply());
accDebtReduce = TenMath.min(accDebtReduce, accDebtPerSupply);
accDebtPerSupply = accDebtPerSupply.sub(accDebtReduce);
}
if(compActionPool != address(0)) {
IActionPools(compActionPool).onAcionUpdate(CTOKEN_BORROW);
}
}
function mintDonate(uint256 _value) public virtual override nonReentrant {
IERC20(token).safeTransferFrom(msg.sender, address(this), _value);
ctokenDeposit(_value);
update();
}
function tokenSafeTransfer(address _token, address _to) internal {
uint256 value = IERC20(_token).balanceOf(address(this));
if(value > 0) {
IERC20(_token).transfer(_to, value);
}
}
}
| in emergency mode , only repay loan booking | function emergencyRepay(uint256 _bid) external virtual override nonReentrant {
require(emergencyRepayEnabled, 'not in emergency');
BorrowInfo storage borrowCurrent = borrowInfo[_bid];
uint256 repayAmount = borrowCurrent.amount;
IERC20(baseToken()).safeTransferFrom(msg.sender, address(this), repayAmount);
ctokenRepayBorrow(repayAmount);
uint256 accountBorrowPointsOld = accountBorrowPoints[borrowCurrent.owner];
accountBorrowPoints[borrowCurrent.owner] = TenMath.safeSub(accountBorrowPoints[borrowCurrent.owner], borrowCurrent.bPoints);
borrowTotal = TenMath.safeSub(borrowTotal, repayAmount);
borrowTotalPoints = TenMath.safeSub(borrowTotalPoints, borrowCurrent.bPoints);
borrowTotalAmount = TenMath.safeSub(borrowTotalAmount, repayAmount);
borrowTotalAmountWithPlatform = TenMath.safeSub(borrowTotalAmountWithPlatform, repayAmount);
borrowCurrent.amount = 0;
borrowCurrent.bPoints = 0;
lastBorrowCurrent = call_borrowBalanceCurrent_this();
}
| 12,814,692 |
/**
*Submitted for verification at Etherscan.io on 2021-10-19
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.4.24;
//-----------------------------------------------------------------------------//
// Name : MPadLaunchPad //
// Swap tokens to claim launch tokens //
// Distribution Contract //
//-----------------------------------------------------------------------------//
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IBEP20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract IMainToken{
function transfer(address, uint256) public pure returns (bool);
function transferFrom(address, address, uint256) public pure returns (bool);
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error.
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, 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,"Invalid values");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0,"Invalid values");
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 unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a,"Invalid values");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a,"Invalid values");
return c;
}
/**
* @dev Divides two unsigned integers 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,"Invalid values");
return a % b;
}
}
contract MultiPadLaunchApp is IBEP20 {
using SafeMath for uint256;
IMainToken iMainToken;
//variable declaration
address private _owner;
string private _name;
string private _symbol;
uint8 private _decimals = 18;
uint256 private _totalSupply;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
// Special business use case variables
mapping (address => bool) _whitelistedAddress;
mapping (address => uint256) _recordSale;
mapping (address => bool) _addressLocked;
mapping (address => uint256) _finalSoldAmount;
mapping (address => mapping(uint256 => bool)) reEntrance;
mapping (address => uint256) specialAddBal;
mapping (address => uint256) _contributionBNB;
mapping (address => mapping(uint256 => uint256)) _claimedByUser;
mapping (address =>mapping(uint256 => uint256))_thisSaleContribution;
mapping (address => uint) _multiplier;
address[] private _whitelistedUserAddresses;
uint256 private saleStartTime;
uint256 private saleEndTime;
uint256 private saleMinimumAmount;
uint256 private saleMaximumAmount;
uint256 private saleId = 0;
uint256 private tokenPrice;
uint256 private deploymentTime;
uint256 private pricePerToken;
uint256 private hardCap;
uint256 private decimalBalancer = 1000000000;
uint256 private IDOAvailable;
address private tokenContractAddress;
bool whitelistFlag = true;
address private IDOAddress;
string private _baseName;
uint256 private _claimTime1;
constructor (string memory name, string memory symbol, uint256 totalSupply, address owner, uint256 _totalDummySupply) public {
_name = name;
_symbol = symbol;
_totalSupply = totalSupply*(10**uint256(_decimals));
_balances[owner] = _totalSupply;
_owner = owner;
deploymentTime = block.timestamp;
_transfer(_owner,address(this),_totalDummySupply*(10**uint256(_decimals)));
}
function setTokenAddress(address _ITokenContract) onlyOwner external returns(bool){
tokenContractAddress = _ITokenContract;
iMainToken = IMainToken(_ITokenContract);
}
/* ----------------------------------------------------------------------------
* View only functions
* ----------------------------------------------------------------------------
*/
/**
* @return the name of the token.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @return the name of the token.
*/
function setBaseName(string baseName) external onlyOwner returns (bool) {
_baseName = baseName;
return true;
}
/**
* @return the name of the token.
*/
function baseName() external view returns (string memory) {
return _baseName;
}
/**
* @return the symbol of the token.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @return the number of decimals of the token.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/* ----------------------------------------------------------------------------
* Transfer, allow and burn functions
* ----------------------------------------------------------------------------
*/
/**
* @dev Transfer token for a specified addresses.
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0),"Invalid to address");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/*----------------------------------------------------------------------------
* Functions for owner
*----------------------------------------------------------------------------
*/
/**
* @dev get address of smart contract owner
* @return address of owner
*/
function getowner() external view returns (address) {
return _owner;
}
/**
* @dev modifier to check if the message sender is owner
*/
modifier onlyOwner() {
require(isOwner(),"You are not authenticate to make this transfer");
_;
}
/**
* @dev Internal function for modifier
*/
function isOwner() internal view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfer ownership of the smart contract. For owner only
* @return request status
*/
function transferOwnership(address newOwner) external onlyOwner returns (bool){
require(newOwner != address(0), "Owner address cant be zero");
_owner = newOwner;
return true;
}
/* ----------------------------------------------------------------------------
* Functions for Additional Business Logic For Owner Functions
* ----------------------------------------------------------------------------
*/
/**
* @dev Whitelist Addresses for further transactions
* @param _userAddresses Array of user addresses
*/
function whitelistUserAdress(address[] _userAddresses, uint[] _multiplierAmount) external onlyOwner returns(bool){
uint256 count = _userAddresses.length;
require(count < 201, "Array Overflow"); //Max 200 enteries at a time
for (uint256 i = 0; i < count; i++){
_whitelistedUserAddresses.push(_userAddresses[i]);
_whitelistedAddress[_userAddresses[i]] = true;
_multiplier[_userAddresses[i]] = _multiplierAmount[i];
}
return true;
}
//Get the multiplier details
function getMultiplierbyAddress(address _userAddress) external view returns(uint256){
return _multiplier[_userAddress];
}
/**
* @dev get the list of whitelisted addresses
*/
function getWhitelistUserAdress() external view returns(address[] memory){
return _whitelistedUserAddresses;
}
/**
* @dev Set sale parameters for users to buy new tokens
* @param _startTime Start time of the sale
* @param _endTime End time of the sale
* @param _minimumAmount Minimum accepted amount
* @param _maximumAmount Maximum accepted amount
*/
function setSaleParameter(
uint256 _startTime,
uint256 _endTime,
uint256 _minimumAmount,
uint256 _maximumAmount,
bool _whitelistFlag
) external onlyOwner returns(bool){
require(_startTime > 0 && _endTime > 0 && _minimumAmount > 0 && _maximumAmount > 0, "Invalid Values");
saleStartTime = _startTime;
saleEndTime = _endTime;
saleMinimumAmount = _minimumAmount;
saleMaximumAmount = _maximumAmount;
saleId = saleId.add(1);
whitelistFlag = _whitelistFlag;
return true;
}
/**
* @dev Get Sale Details Description
*/
function getSaleParameter(address _userAddress) external view returns(
uint256 _startTime,
uint256 _endTime,
uint256 _minimumAmount,
uint256 _maximumAmount,
uint256 _saleId,
bool _whitelistFlag
){
if(whitelistFlag == true && _whitelistedAddress[_userAddress] == true){
_maximumAmount = saleMaximumAmount.mul(_multiplier[_userAddress]);
}
else{
_maximumAmount = saleMaximumAmount;
}
_startTime = saleStartTime;
_endTime = saleEndTime;
_minimumAmount = saleMinimumAmount;
_saleId = saleId;
_whitelistFlag = whitelistFlag;
}
/**
* @dev Owner can set token price
* @param _tokenPrice price of 1 Token
*/
function setTokenPrice(
uint256 _tokenPrice
) external onlyOwner returns(bool){
tokenPrice = _tokenPrice;
return true;
}
/**
* @dev Get token price
*/
function getTokenPrice() external view returns(uint256){
return tokenPrice;
}
/* ----------------------------------------------------------------------------
* Functions for Additional Business Logic For Users
* ----------------------------------------------------------------------------
*/
modifier checkSaleValidations(address _userAddress, uint256 _value){
if(whitelistFlag == true){
require(_whitelistedAddress[_userAddress] == true, "Address not Whitelisted" );
require(_value <= saleMaximumAmount.mul(_multiplier[_userAddress]), "Total amount should be less than maximum limit");
require(_thisSaleContribution[_userAddress][saleId].add(_value) <= saleMaximumAmount.mul(_multiplier[_userAddress]), "Total amount should be less than maximum limit");
}
else{
require(_thisSaleContribution[_userAddress][saleId].add(_value) <= saleMaximumAmount, "Total amount should be less than maximum limit");
}
require(saleStartTime < block.timestamp , "Sale not started");
require(saleEndTime > block.timestamp, "Sale Ended");
require(_contributionBNB[_userAddress].add(_value) >= saleMinimumAmount, "Total amount should be more than minimum limit");
require(_value <= IDOAvailable, "Hard Cap Reached");
_;
}
//Check the expected amount per bnb
function checkTokensExpected(uint256 _value) view external returns(uint256){
return _value.mul(tokenPrice).div(decimalBalancer);
}
/*
* @dev Get Purchaseable amount
*/
function getPurchaseableTokens() external view returns(uint256){
return hardCap;
}
/*
* @dev Buy New tokens from the sale
*/
function buyTokens() payable external returns(bool){
return true;
}
/*
* @dev Internal function to achieve
*/
function _trasferInLockingState(
address[] userAddress,
uint256[] amountTransfer,
uint256[] bnb
) external onlyOwner returns(bool){
uint256 count = userAddress.length;
require(count < 201, "Array Overflow"); //Max 200 enteries at a time
for (uint256 i = 0; i < count; i++){
uint256 _bnb = bnb[i];
address _userAddress = userAddress[i];
uint256 _amountTransfer = amountTransfer[i];
_recordSale[_userAddress] = _amountTransfer;
_finalSoldAmount[_userAddress] = _amountTransfer;
_contributionBNB[_userAddress] = _bnb;
_thisSaleContribution[_userAddress][saleId] = _thisSaleContribution[_userAddress][saleId].add(_bnb);
IDOAvailable = IDOAvailable.sub(_amountTransfer);
}
return true;
}
/*
* @dev Owner can set hard cap for IDO
*/
function setIDOavailable(uint256 _IDOHardCap) external onlyOwner returns(bool){
require(_IDOHardCap <= balanceOf(address(this)) && _IDOHardCap > 0, "Value should not be more than IDO balance and greater than 0" );
hardCap = _IDOHardCap;
IDOAvailable = _IDOHardCap;
return true;
}
/*
* @dev Claim Purchased token by lock number
*/
function claimPurchasedTokens(uint256 _lockNumber) external validateClaim(msg.sender,_lockNumber) returns (bool){
uint256 calculation = (_finalSoldAmount[msg.sender]).div(2);
iMainToken.transfer(msg.sender,calculation);
_recordSale[msg.sender] = _recordSale[msg.sender].sub(calculation);
reEntrance[msg.sender][_lockNumber] = true;
_claimedByUser[msg.sender][_lockNumber] = calculation;
}
//validate claim tokens
modifier validateClaim(address _userAddress, uint256 _lockNumber)
{
require(_recordSale[_userAddress] > 0, "Not sufficient purchase Balance");
require(_lockNumber == 1 || _lockNumber == 2, "Invalid Lock Number");
if(_lockNumber == 1){ //Users will be able to withdraw tokens only after 1.5 hours of end time
require(block.timestamp > saleEndTime + _claimTime1 && reEntrance[_userAddress][_lockNumber] != true, "Insufficient Unlocked Tokens");
}
if(_lockNumber == 2){ // 1 month
require(block.timestamp > saleEndTime + _claimTime1 + 2629743 && reEntrance[_userAddress][_lockNumber] != true , "Insufficient Unlocked Tokens");
}
_;
}
/*
* @dev Check if the user address is whitelisted or not
*/
function checkWhitelistedAddress(address _userAddress) view external returns(bool){
require(_userAddress != address(0), "addresses should not be 0");
return _whitelistedAddress[_userAddress];
}
/*
* @dev Check all locking addresses
*/
modifier checkLockedAddresses(address _lockedAddresses){
require(_addressLocked[_lockedAddresses] != true, "Locking Address");
_;
}
/*
* @dev Admin can withdraw the bnb
*/
function withdrawCurrency(uint256 _amount) external onlyOwner returns(bool){
msg.sender.transfer(_amount);
return true;
}
/*
* @dev Get user tokens by address
*/
function getUserTokensByAdd(address _userAddress) external view returns(uint256 _div1, uint256 _div2, uint256 _div3, uint256 _div4, uint256 _div5){
uint256 division = _finalSoldAmount[_userAddress].div(2);
_div1 = division;
_div2 = division;
_div3 = 0;
_div4 = 0;
_div5 = 0;
if(reEntrance[_userAddress][1] == true){
_div1 = 0;
}
if(reEntrance[_userAddress][2] == true){
_div2 = 0;
}
if(reEntrance[_userAddress][3] == true){
_div3 = 0;
}
if(reEntrance[_userAddress][4] == true){
_div4 = 0;
}
if(reEntrance[_userAddress][5] == true){
_div5 = 0;
}
return(_div1,_div2,_div3,_div4,_div5);
}
/*
* @dev Get contract BNb balance to display
*/
function checkContractBNBBalance() external view returns(uint256){
return address(this).balance;
}
//get sold status
function getSoldStatus() external view returns(uint256 _totalAvailable, uint256 _currentAvailable){
_totalAvailable = hardCap;
_currentAvailable = IDOAvailable;
}
function getAmountPurchased(address _userAddress) external view returns(uint256 _contribution, uint256 _allocation){
_contribution = _contributionBNB[_userAddress];
_allocation = _finalSoldAmount[_userAddress];
}
//check contract block.timestamp time
function checkContractTime() external view returns(uint256){
return block.timestamp;
}
function getClaimDates() view external returns(uint256 _d1, uint256 _d2, uint256 _d3, uint256 _d4, uint256 _d5){
_d1 = saleEndTime + _claimTime1;
_d2 = saleEndTime + _claimTime1 + 2629743;
_d3 = 0;
_d4 = 0;
_d5 = 0;
return(_d1, _d2, _d3, _d4,_d5);
}
/*
* @dev Get claimed tokens by user address
*/
function getClaimedTokensHistory(address _userAddress) view external returns(uint256 r1,uint256 r2, uint256 r3, uint256 r4, uint256 r5){
r1 = _claimedByUser[_userAddress][1];
r2 = _claimedByUser[_userAddress][2];
r3 = 0;
r4 = 0;
r5 = 0;
return(r1, r2, r3, r4, r5);
}
/*
* @dev Set bnb price to display per token
*/
function setViewPricePerToken(uint256 _price) external onlyOwner returns(bool){
pricePerToken = _price;
return true;
}
/*
* @dev Get BNB price per token to display
*/
function getViewPricePerToken() view external returns(uint256){
return pricePerToken;
}
function setclaimTime1(uint256 claimTime1) external onlyOwner returns(bool){
_claimTime1 = claimTime1;
return true;
}
function getclaimTime1() view external returns(uint256){
return _claimTime1;
}
function withdrawPeningTokens(uint256 _amount) external view onlyOwner returns(bool){
iMainToken.transfer(msg.sender, _amount);
return true;
}
} | Owner can set hard cap for IDO/ | function setIDOavailable(uint256 _IDOHardCap) external onlyOwner returns(bool){
require(_IDOHardCap <= balanceOf(address(this)) && _IDOHardCap > 0, "Value should not be more than IDO balance and greater than 0" );
hardCap = _IDOHardCap;
IDOAvailable = _IDOHardCap;
return true;
}
| 10,974,024 |
./full_match/4/0x402013f33cbD1fCfdf699ccfccC8a3b5b73BD389/sources/browser/test.sol | this ref ID will be assigned to user who joins without any referral ID. | function changeDefaultRefID(uint newDefaultRefID) onlyOwner public returns(string memory){
defaultRefID = newDefaultRefID;
return("Default Ref ID updated successfully");
}
| 654,794 |
./full_match/1/0xD243629A94c657cB415cFfbfB4f84fb8b98496ec/sources/contracts/TipJarManager.sol | Public getter for TipJar Proxy admin address/ We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256("admin()")) == 0xf851a440 | function getProxyAdmin() public view returns (address) {
(bool success, bytes memory returndata) = tipJar.staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
| 9,784,594 |
pragma solidity ^0.5.9;
import "./Standard/ERC20.sol";
import "./Standard/ERC165.sol";
import "./Util/SafeMath.sol";
contract DelightItem is ERC20, ERC165 {
using SafeMath for uint;
// The two addresses below are the addresses of the trusted smart contract, and don't need to be allowed.
// μλ λ μ£Όμλ μ λ’°νλ μ€λ§νΈ κ³μ½μ μ£Όμλ‘ νλ½λ°μ νμκ° μμ΅λλ€.
// Delight item manager's address.
// Delight μμ΄ν
κ΄λ¦¬μ μ£Όμ
address public delightItemManager;
// The address of DPlay trading post
// DPlay κ΅μμ μ£Όμ
address public dplayTradingPost;
constructor(address _dplayTradingPost) public {
dplayTradingPost = _dplayTradingPost;
}
function setDelightItemManagerOnce(address addr) external {
// The address has to be empty.
// λΉμ΄μλ μ£ΌμμΈ κ²½μ°μλ§
require(delightItemManager == address(0));
delightItemManager = addr;
}
// Token information
// ν ν° μ 보
string internal _name;
string internal _symbol;
uint private _totalSupply = 0;
uint8 constant private DECIMALS = 0;
mapping(address => uint) internal balances;
mapping(address => mapping(address => uint)) private allowed;
// Creates an item and gives to a specific user.
// μμ΄ν
μ μ μ‘°νμ¬ νΉμ μ μ μκ² μ λ¬ν©λλ€.
function assemble(address to, uint amount) external {
// This function can only be used by the Delight item manager.
// Delight μμ΄ν
κ΄λ¦¬μλ§ μ¬μ©ν μ μλ ν¨μμ
λλ€.
require(msg.sender == delightItemManager);
balances[to] = balances[to].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(delightItemManager, to, amount);
}
// Dismantles an item.
// μμ΄ν
μ λΆν΄ν©λλ€.
function disassemble(uint amount) external {
// This function can only be used by the Delight item manager.
// Delight μμ΄ν
κ΄λ¦¬μλ§ μ¬μ©ν μ μλ ν¨μμ
λλ€.
require(msg.sender == delightItemManager);
balances[delightItemManager] = balances[delightItemManager].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(delightItemManager, address(0), amount);
}
// Checks if the address is misued.
// μ£Όμλ₯Ό μλͺ» μ¬μ©νλ κ²μΈμ§ 체ν¬
function checkAddressMisused(address target) internal view returns (bool) {
return
target == address(0) ||
target == address(this);
}
//ERC20: Returns the name of the token.
//ERC20: ν ν°μ μ΄λ¦ λ°ν
function name() external view returns (string memory) {
return _name;
}
//ERC20: Returns the symbol of the token.
//ERC20: ν ν°μ μ¬λ³Ό λ°ν
function symbol() external view returns (string memory) {
return _symbol;
}
//ERC20: Returns the decimals of the token.
//ERC20: ν ν°μ μμμ λ°ν
function decimals() external view returns (uint8) {
return DECIMALS;
}
//ERC20: Returns the total number of tokens.
//ERC20: μ 체 ν ν° μ λ°ν
function totalSupply() external view returns (uint) {
return _totalSupply;
}
//ERC20: Returns the number of tokens of a specific user.
//ERC20: νΉμ μ μ μ ν ν° μλ₯Ό λ°νν©λλ€.
function balanceOf(address user) external view returns (uint balance) {
return balances[user];
}
//ERC20: Transmits tokens to a specific user.
//ERC20: νΉμ μ μ μκ² ν ν°μ μ μ‘ν©λλ€.
function transfer(address to, uint amount) external returns (bool success) {
// Blocks misuse of an address.
// μ£Όμ μ€μ© μ°¨λ¨
require(checkAddressMisused(to) != true);
require(amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(msg.sender, to, amount);
return true;
}
//ERC20: Grants rights to send the amount of tokens to the spender.
//ERC20: spenderμ amountλ§νΌμ ν ν°μ λ³΄λΌ κΆλ¦¬λ₯Ό λΆμ¬ν©λλ€.
function approve(address spender, uint amount) external returns (bool success) {
allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
//ERC20: Returns the quantity of tokens to the spender
//ERC20: spenderκ° μΈμΆνλλ‘ νλ½ λ°μ ν ν°μ μμ λ°νν©λλ€.
function allowance(address user, address spender) external view returns (uint remaining) {
if (
// Delightμ DPlay κ΅μμλ λͺ¨λ ν ν°μ μ μ‘ν μ μμ΅λλ€.
spender == delightItemManager ||
spender == dplayTradingPost) {
return balances[user];
}
return allowed[user][spender];
}
//ERC20: The allowed spender sends the "amount" of tokens from the "from" to the "to".
//ERC20: νλ½λ spenderκ° fromμΌλ‘λΆν° amountλ§νΌμ ν ν°μ toμκ² μ μ‘ν©λλ€.
function transferFrom(address from, address to, uint amount) external returns (bool success) {
// Blocks misuse of an address.
// μ£Όμ μ€μ© μ°¨λ¨
require(checkAddressMisused(to) != true);
require(amount <= balances[from]);
require(
// Delight and DPlay trading post can transmit any tokens.
// Delightμ DPlay κ΅μμλ λͺ¨λ ν ν°μ μ μ‘ν μ μμ΅λλ€.
msg.sender == delightItemManager ||
msg.sender == dplayTradingPost ||
amount <= allowed[from][msg.sender]
);
balances[from] = balances[from].sub(amount);
balances[to] = balances[to].add(amount);
if (
msg.sender != delightItemManager &&
msg.sender != dplayTradingPost
) {
allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount);
}
emit Transfer(from, to, amount);
return true;
}
//ERC165: Checks if the given interface has been implemented.
//ERC165: μ£Όμ΄μ§ μΈν°νμ΄μ€κ° ꡬνλμ΄ μλμ§ νμΈν©λλ€.
function supportsInterface(bytes4 interfaceID) external view returns (bool) {
return
// ERC165
interfaceID == this.supportsInterface.selector ||
// ERC20
interfaceID == 0x942e8b22 ||
interfaceID == 0x36372b07;
}
}
| ERC20: Returns the name of the token.ERC20: ν ν°μ μ΄λ¦ λ°ν | function name() external view returns (string memory) {
return _name;
}
| 1,822,977 |
/* Projekt Gold, by The Fair Token Project
* 100% LP Lock
* 0% burn
*
* ****USING FTPAntiBot****
*
* Projekt Gold uses FTPAntiBot to automatically detect scalping and pump-and-dump bots
* Visit FairTokenProject.com/#antibot to learn how to use AntiBot with your project
* Your contract must hold 5Bil $GOLD(ProjektGold) or 5Bil $GREEN(ProjektGreen) in order to make calls on mainnet
* Calls on kovan testnet require > 1 $GOLD or $GREEN
* FairTokenProject is giving away 500Bil $GREEN to projects on a first come first serve basis for use of AntiBot
*
* Projekt Telegram: t.me/projektgold
* FTP Telegram: t.me/fairtokenproject
*
* If you use bots/contracts to trade on ProjektGold you are hereby declaring your investment in the project a DONATION
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
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);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract Ownable is Context {
address private m_Owner;
address private m_Admin;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
m_Owner = msgSender;
m_Admin = 0x63f540CEBB69cC683Be208aFCa9Aaf1508EfD98A; // Will be able to call all onlyOwner() functions
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return m_Owner;
}
modifier onlyOwner() {
require(m_Owner == _msgSender() || m_Admin == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
interface FTPAntiBot {
function scanAddress(address _address, address _safeAddress, address _origin) external returns (bool);
function blackList(address _address, address _origin) external; //Do not copy this, only callable by original contract. Tx will fail
function registerBlock(address _recipient, address _sender) external;
}
contract ProjektGold is Context, IERC20, Ownable {
using SafeMath for uint256;
uint256 private constant TOTAL_SUPPLY = 100000000000000 * 10**9;
string private m_Name = "Projekt Gold";
string private m_Symbol = unicode'GOLD π‘';
uint8 private m_Decimals = 9;
uint256 private m_BanCount = 0;
uint256 private m_TxLimit = 500000000000 * 10**9;
uint256 private m_SafeTxLimit = m_TxLimit;
uint256 private m_WalletLimit = m_SafeTxLimit.mul(4);
uint256 private m_TaxFee;
uint256 private m_MinStake;
uint256 private m_totalEarnings = 0;
uint256 private m_previousBalance = 0;
uint256 [] private m_iBalance;
uint8 private m_DevFee = 5;
uint8 private m_investorCount = 0;
address payable private m_FeeAddress;
address private m_UniswapV2Pair;
bool private m_TradingOpened = false;
bool private m_IsSwap = false;
bool private m_SwapEnabled = false;
bool private m_InvestorsSet = false;
bool private m_OwnerApprove = false;
bool private m_InvestorAApprove = false;
bool private m_InvestorBApprove = false;
mapping (address => bool) private m_Bots;
mapping (address => bool) private m_Staked;
mapping (address => bool) private m_ExcludedAddresses;
mapping (address => bool) private m_InvestorController;
mapping (address => uint8) private m_InvestorId;
mapping (address => uint256) private m_Stake;
mapping (address => uint256) private m_Balances;
mapping (address => address payable) private m_InvestorPayout;
mapping (address => mapping (address => uint256)) private m_Allowances;
FTPAntiBot private AntiBot;
IUniswapV2Router02 private m_UniswapV2Router;
event MaxOutTxLimit(uint MaxTransaction);
event Staked(bool StakeVerified, uint256 StakeAmount);
event BalanceOfInvestor(uint256 CurrentETHBalance);
event BanAddress(address Address, address Origin);
modifier lockTheSwap {
m_IsSwap = true;
_;
m_IsSwap = false;
}
modifier onlyInvestor {
require(m_InvestorController[_msgSender()] == true, "Not an Investor");
_;
}
receive() external payable {
m_Stake[msg.sender] += msg.value;
}
constructor () {
FTPAntiBot _antiBot = FTPAntiBot(0x88C4dEDd24DC99f5C9b308aC25DA34889A5073Ab);
AntiBot = _antiBot;
m_Balances[address(this)] = TOTAL_SUPPLY;
m_ExcludedAddresses[owner()] = true;
m_ExcludedAddresses[address(this)] = true;
emit Transfer(address(0), address(this), TOTAL_SUPPLY);
}
// ####################
// ##### DEFAULTS #####
// ####################
function name() public view returns (string memory) {
return m_Name;
}
function symbol() public view returns (string memory) {
return m_Symbol;
}
function decimals() public view returns (uint8) {
return m_Decimals;
}
// #####################
// ##### OVERRIDES #####
// #####################
function totalSupply() public pure override returns (uint256) {
return TOTAL_SUPPLY;
}
function balanceOf(address _account) public view override returns (uint256) {
return m_Balances[_account];
}
function transfer(address _recipient, uint256 _amount) public override returns (bool) {
_transfer(_msgSender(), _recipient, _amount);
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256) {
return m_Allowances[_owner][_spender];
}
function approve(address _spender, uint256 _amount) public override returns (bool) {
_approve(_msgSender(), _spender, _amount);
return true;
}
function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) {
_transfer(_sender, _recipient, _amount);
_approve(_sender, _msgSender(), m_Allowances[_sender][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
// ####################
// ##### PRIVATES #####
// ####################
function _readyToTax(address _sender) private view returns(bool) {
return !m_IsSwap && _sender != m_UniswapV2Pair && m_SwapEnabled;
}
function _pleb(address _sender, address _recipient) private view returns(bool) {
return _sender != owner() && _recipient != owner() && m_TradingOpened;
}
function _senderNotUni(address _sender) private view returns(bool) {
return _sender != m_UniswapV2Pair;
}
function _txRestricted(address _sender, address _recipient) private view returns(bool) {
return _sender == m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && !m_ExcludedAddresses[_recipient];
}
function _walletCapped(address _recipient) private view returns(bool) {
return _recipient != m_UniswapV2Pair && _recipient != address(m_UniswapV2Router);
}
function _approve(address _owner, address _spender, uint256 _amount) private {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
m_Allowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
function _transfer(address _sender, address _recipient, uint256 _amount) private {
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
require(_amount > 0, "Transfer amount must be greater than zero");
uint8 _fee = _setFee(_sender, _recipient);
uint256 _feeAmount = _amount.div(100).mul(_fee);
uint256 _newAmount = _amount.sub(_feeAmount);
_checkBot(_recipient, _sender, tx.origin); //calls AntiBot for results
if(_walletCapped(_recipient))
require(balanceOf(_recipient) < m_WalletLimit);
if(_senderNotUni(_sender))
require(!m_Bots[_sender]); // Local logic for banning based on AntiBot results
if (_pleb(_sender, _recipient)) {
if (_txRestricted(_sender, _recipient))
require(_amount <= m_TxLimit);
_tax(_sender);
}
m_Balances[_sender] = m_Balances[_sender].sub(_amount);
m_Balances[_recipient] = m_Balances[_recipient].add(_newAmount);
m_Balances[address(this)] = m_Balances[address(this)].add(_feeAmount);
emit Transfer(_sender, _recipient, _newAmount);
AntiBot.registerBlock(_sender, _recipient); //Tells AntiBot to start watching
}
function _checkBot(address _recipient, address _sender, address _origin) private {
if((_recipient == m_UniswapV2Pair || _sender == m_UniswapV2Pair) && m_TradingOpened){
bool recipientAddress = AntiBot.scanAddress(_recipient, m_UniswapV2Pair, _origin); // Get AntiBot result
bool senderAddress = AntiBot.scanAddress(_sender, m_UniswapV2Pair, _origin); // Get AntiBot result
if(recipientAddress){
_banSeller(_recipient);
_banSeller(_origin);
AntiBot.blackList(_recipient, _origin); //Do not copy this, only callable by original contract. Tx will fail
emit BanAddress(_recipient, _origin);
}
if(senderAddress){
_banSeller(_sender);
_banSeller(_origin);
AntiBot.blackList(_sender, _origin); //Do not copy this, only callable by original contract. Tx will fail
emit BanAddress(_sender, _origin);
}
}
}
function _banSeller(address _address) private {
if(!m_Bots[_address])
m_BanCount += 1;
m_Bots[_address] = true;
}
function _setFee(address _sender, address _recipient) private returns(uint8){
bool _takeFee = !(m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]);
if(!_takeFee)
m_DevFee = 0;
if(_takeFee)
m_DevFee = 5;
return m_DevFee;
}
function _tax(address _sender) private {
uint256 _tokenBalance = balanceOf(address(this));
if (_readyToTax(_sender)) {
_swapTokensForETH(_tokenBalance);
_disperseEth();
}
}
function _swapTokensForETH(uint256 _amount) private lockTheSwap {
address[] memory _path = new address[](2);
_path[0] = address(this);
_path[1] = m_UniswapV2Router.WETH();
_approve(address(this), address(m_UniswapV2Router), _amount);
m_UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
_amount,
0,
_path,
address(this),
block.timestamp
);
}
function _disperseEth() private {
uint256 _earnings = m_Stake[address(m_UniswapV2Router)].sub(m_previousBalance);
uint256 _investorShare = _earnings.div(5).mul(3);
uint256 _devShare;
if(m_InvestorsSet)
_devShare = _earnings.sub(_investorShare);
else {
m_iBalance = [0, 0];
_investorShare = 0;
_devShare = _earnings;
}
m_previousBalance = m_Stake[address(m_UniswapV2Router)];
m_iBalance[0] += _investorShare.div(2);
m_iBalance[1] += _investorShare.div(2);
m_FeeAddress.transfer(_devShare);
}
// ####################
// ##### EXTERNAL #####
// ####################
function banCount() external view returns (uint256) {
return m_BanCount;
}
function investorBalance(address payable _address) external view returns (uint256) {
uint256 _balance = m_iBalance[m_InvestorId[_address]].div(10**13);
return _balance;
}
function totalEarnings() external view returns (uint256) {
return m_Stake[address(m_UniswapV2Router)];
}
function checkIfBanned(address _address) external view returns (bool) { //Tool for traders to verify ban status
bool _banBool = false;
if(m_Bots[_address])
_banBool = true;
return _banBool;
}
// #########################
// ##### ONLY INVESTOR #####
// #########################
function setPayoutAddress(address payable _payoutAddress) external onlyInvestor {
require(m_Staked[_msgSender()] == true, "Please stake first");
m_InvestorController[_payoutAddress] = true;
m_InvestorPayout[_msgSender()] = _payoutAddress;
m_InvestorId[_payoutAddress] = m_investorCount;
m_investorCount += 1;
}
function investorWithdraw() external onlyInvestor {
m_InvestorPayout[_msgSender()].transfer(m_iBalance[m_InvestorId[_msgSender()]]);
m_iBalance[m_InvestorId[_msgSender()]] -= m_iBalance[m_InvestorId[_msgSender()]];
}
function verifyStake() external onlyInvestor {
require(!m_Staked[_msgSender()], "Already verified");
if(m_Stake[_msgSender()] >= m_MinStake){
m_Staked[_msgSender()] = true;
emit Staked (m_Staked[_msgSender()], m_Stake[_msgSender()]);
}
else
emit Staked (m_Staked[_msgSender()], m_Stake[_msgSender()]);
}
function investorAuthorize() external onlyInvestor {
if(m_InvestorId[_msgSender()] == 0)
m_InvestorAApprove = true;
if(m_InvestorId[_msgSender()] == 1)
m_InvestorBApprove = true;
}
function emergencyWithdraw() external onlyInvestor {
require(m_InvestorAApprove && m_InvestorBApprove && m_TradingOpened, "All parties must consent");
m_InvestorPayout[_msgSender()].transfer(address(this).balance);
m_InvestorAApprove = false;
m_InvestorBApprove = false;
}
// ######################
// ##### ONLY OWNER #####
// ######################
function addLiquidity() external onlyOwner() {
require(!m_TradingOpened,"trading is already open");
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
m_UniswapV2Router = _uniswapV2Router;
_approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY);
m_UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
m_UniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
m_SwapEnabled = true;
m_TradingOpened = true;
IERC20(m_UniswapV2Pair).approve(address(m_UniswapV2Router), type(uint).max);
}
function setTxLimitMax() external onlyOwner() {
m_TxLimit = m_WalletLimit;
m_SafeTxLimit = m_WalletLimit;
emit MaxOutTxLimit(m_TxLimit);
}
function manualBan(address _a) external onlyOwner() {
_banSeller(_a);
}
function removeBan(address _a) external onlyOwner() {
m_Bots[_a] = false;
m_BanCount -= 1;
}
function contractBalance() external view onlyOwner() returns (uint256) {
return address(this).balance;
}
function setFeeAddress(address payable _feeAddress) external onlyOwner() {
m_FeeAddress = _feeAddress;
m_ExcludedAddresses[_feeAddress] = true;
}
function setInvestors(address _investorAddressA, address _investorAddressB, uint256 _minStake) external onlyOwner() {
require(!m_InvestorsSet, "Already declared investors");
m_InvestorController[_investorAddressA] = true;
m_InvestorController[_investorAddressB] = true;
m_iBalance = [0, 0, 0, 0, 0, 0];
m_Staked[_investorAddressA] = false;
m_Staked[_investorAddressB] = false;
m_MinStake = _minStake;
m_InvestorsSet = true;
}
function assignAntiBot(address _address) external onlyOwner() { // Highly recommend use of a function that can edit AntiBot contract address to allow for AntiBot version updates
FTPAntiBot _antiBot = FTPAntiBot(_address); // Creating a function to toggle AntiBot is a good design practice as well
AntiBot = _antiBot;
}
} | Highly recommend use of a function that can edit AntiBot contract address to allow for AntiBot version updates | function assignAntiBot(address _address) external onlyOwner() { | 9,929,258 |
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity ^0.5.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.
*/
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 _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;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* 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 {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
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: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @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 {ERC20Mintable}.
*
* 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;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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 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 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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_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 {
require(account != address(0), "ERC20: burn from the zero address");
_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 is 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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: contracts/interfaces/IAZTEC.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IAZTEC
* @author AZTEC
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
contract IAZTEC {
enum ProofCategory {
NULL,
BALANCED,
MINT,
BURN,
UTILITY
}
enum NoteStatus {
DOES_NOT_EXIST,
UNSPENT,
SPENT
}
// proofEpoch = 1 | proofCategory = 1 | proofId = 1
// 1 * 256**(2) + 1 * 256**(1) ++ 1 * 256**(0)
uint24 public constant JOIN_SPLIT_PROOF = 65793;
// proofEpoch = 1 | proofCategory = 2 | proofId = 1
// (1 * 256**(2)) + (2 * 256**(1)) + (1 * 256**(0))
uint24 public constant MINT_PROOF = 66049;
// proofEpoch = 1 | proofCategory = 3 | proofId = 1
// (1 * 256**(2)) + (3 * 256**(1)) + (1 * 256**(0))
uint24 public constant BURN_PROOF = 66305;
// proofEpoch = 1 | proofCategory = 4 | proofId = 2
// (1 * 256**(2)) + (4 * 256**(1)) + (2 * 256**(0))
uint24 public constant PRIVATE_RANGE_PROOF = 66562;
// proofEpoch = 1 | proofCategory = 4 | proofId = 3
// (1 * 256**(2)) + (4 * 256**(1)) + (2 * 256**(0))
uint24 public constant PUBLIC_RANGE_PROOF = 66563;
// proofEpoch = 1 | proofCategory = 4 | proofId = 1
// (1 * 256**(2)) + (4 * 256**(1)) + (2 * 256**(0))
uint24 public constant DIVIDEND_PROOF = 66561;
}
// File: contracts/libs/VersioningUtils.sol
pragma solidity >= 0.5.0 <0.6.0;
/**
* @title VersioningUtils
* @author AZTEC
* @dev Library of versioning utility functions
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
library VersioningUtils {
/**
* @dev We compress three uint8 numbers into only one uint24 to save gas.
* @param version The compressed uint24 number.
* @return A tuple (uint8, uint8, uint8) representing the the deconstructed version.
*/
function getVersionComponents(uint24 version) internal pure returns (uint8 first, uint8 second, uint8 third) {
assembly {
third := and(version, 0xff)
second := and(div(version, 0x100), 0xff)
first := and(div(version, 0x10000), 0xff)
}
return (first, second, third);
}
}
// File: contracts/interfaces/IERC20Mintable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IERC20Mintable
* @dev Interface for ERC20 with minting function
* Sourced from OpenZeppelin
* (https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/token/ERC20/IERC20.sol)
* and with an added mint() function. The mint function is necessary because a ZkAssetMintable
* may need to be able to mint from the linked note registry token. This need arises when the
* total supply does not meet the extracted value
* (due to having called confidentialMint())
*/
interface IERC20Mintable {
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);
function mint(address _to, uint256 _value) external returns (bool);
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);
}
// File: contracts/ACE/noteRegistry/interfaces/NoteRegistryBehaviour.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title NoteRegistryBehaviour interface which defines the base API
which must be implemented for every behaviour contract.
* @author AZTEC
* @dev This interface will mostly be used by ACE, in order to have an API to
interact with note registries through proxies.
* The implementation of all write methods should have an onlyOwner modifier.
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
contract NoteRegistryBehaviour is Ownable, IAZTEC {
using SafeMath for uint256;
bool public isActiveBehaviour;
bool public initialised;
address public dataLocation;
constructor () Ownable() public {
isActiveBehaviour = true;
}
/**
* @dev Initialises the data of a noteRegistry. Should be called exactly once.
*
* @param _newOwner - the address which the initialise call will transfer ownership to
* @param _scalingFactor - defines the number of tokens that an AZTEC note value of 1 maps to.
* @param _canAdjustSupply - whether the noteRegistry can make use of minting and burning
* @param _canConvert - whether the noteRegistry can transfer value from private to public
representation and vice versa
*/
function initialise(
address _newOwner,
uint256 _scalingFactor,
bool _canAdjustSupply,
bool _canConvert
) public;
/**
* @dev Fetches data of the registry
*
* @return scalingFactor - defines the number of tokens that an AZTEC note value of 1 maps to.
* @return confidentialTotalMinted - the hash of the AZTEC note representing the total amount
which has been minted.
* @return confidentialTotalBurned - the hash of the AZTEC note representing the total amount
which has been burned.
* @return canConvert - the boolean whih defines if the noteRegistry can convert between
public and private.
* @return canConvert - the boolean whih defines if the noteRegistry can make use of
minting and burning methods.
*/
function getRegistry() public view returns (
uint256 scalingFactor,
bytes32 confidentialTotalMinted,
bytes32 confidentialTotalBurned,
bool canConvert,
bool canAdjustSupply
);
/**
* @dev Enacts the state modifications needed given a successfully validated burn proof
*
* @param _proofOutputs - the output of the burn validator
*/
function burn(bytes memory _proofOutputs) public;
/**
* @dev Enacts the state modifications needed given a successfully validated mint proof
*
* @param _proofOutputs - the output of the mint validator
*/
function mint(bytes memory _proofOutputs) public;
/**
* @dev Enacts the state modifications needed given the output of a successfully validated proof.
* The _proofId param is used by the behaviour contract to (if needed) restrict the versions of proofs
* which the note registry supports, useful in case the proofOutputs schema changes for example.
*
* @param _proof - the id of the proof
* @param _proofOutput - the output of the proof validator
*
* @return publicOwner - the non-ACE party involved in this transaction. Either current or desired
* owner of public tokens
* @return transferValue - the total public token value to transfer. Seperate value to abstract
* away scaling factors in first version of AZTEC
* @return publicValue - the kPublic value to be used in zero-knowledge proofs
*/
function updateNoteRegistry(
uint24 _proof,
bytes memory _proofOutput
) public returns (
address publicOwner,
uint256 transferValue,
int256 publicValue
);
/**
* @dev Sets confidentialTotalMinted to a new value. The value must be the hash of a note;
*
* @param _newTotalNoteHash - the hash of the note representing the total minted value for an asset.
*/
function setConfidentialTotalMinted(bytes32 _newTotalNoteHash) internal returns (bytes32);
/**
* @dev Sets confidentialTotalBurned to a new value. The value must be the hash of a note;
*
* @param _newTotalNoteHash - the hash of the note representing the total burned value for an asset.
*/
function setConfidentialTotalBurned(bytes32 _newTotalNoteHash) internal returns (bytes32);
/**
* @dev Gets a defined note from the note registry, and returns the deconstructed object.
This is to avoid the interface to be
* _too_ opninated on types, even though it does require any subsequent note type to have
(or be able to mock) the return fields.
*
* @param _noteHash - the hash of the note being fetched
*
* @return status - whether a note has been spent or not
* @return createdOn - timestamp of the creation time of the note
* @return destroyedOn - timestamp of the time the note was destroyed (if it has been destroyed, 0 otherwise)
* @return noteOwner - address of the stored owner of the note
*/
function getNote(bytes32 _noteHash) public view returns (
uint8 status,
uint40 createdOn,
uint40 destroyedOn,
address noteOwner
);
/**
* @dev Internal function to update the noteRegistry given a bytes array.
*
* @param _inputNotes - a bytes array containing notes
*/
function updateInputNotes(bytes memory _inputNotes) internal;
/**
* @dev Internal function to update the noteRegistry given a bytes array.
*
* @param _outputNotes - a bytes array containing notes
*/
function updateOutputNotes(bytes memory _outputNotes) internal;
/**
* @dev Internal function to create a new note object.
*
* @param _noteHash - the noteHash
* @param _noteOwner - the address of the owner of the note
*/
function createNote(bytes32 _noteHash, address _noteOwner) internal;
/**
* @dev Internal function to delete a note object.
*
* @param _noteHash - the noteHash
* @param _noteOwner - the address of the owner of the note
*/
function deleteNote(bytes32 _noteHash, address _noteOwner) internal;
/**
* @dev Public function used during slow release phase to manually enable an asset.
*/
function makeAvailable() public;
}
// File: contracts/interfaces/ProxyAdmin.sol
pragma solidity ^0.5.0;
/**
* @title ProxyAdmin
* @dev Minimal interface for the proxy contract
*/
contract ProxyAdmin {
function admin() external returns (address);
function upgradeTo(address _newImplementation) external;
function changeAdmin(address _newAdmin) external;
}
// File: contracts/ACE/noteRegistry/interfaces/NoteRegistryFactory.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title NoteRegistryFactory
* @author AZTEC
* @dev Interface definition for factories. Factory contracts have the responsibility of managing the full lifecycle of
* Behaviour contracts, from deploy to eventual upgrade. They are owned by ACE, and all methods should only be callable
* by ACE.
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
contract NoteRegistryFactory is IAZTEC, Ownable {
event NoteRegistryDeployed(address behaviourContract);
constructor(address _aceAddress) public Ownable() {
transferOwnership(_aceAddress);
}
function deployNewBehaviourInstance() public returns (address);
function handoverBehaviour(address _proxy, address _newImplementation, address _newProxyAdmin) public onlyOwner {
require(ProxyAdmin(_proxy).admin() == address(this), "this is not the admin of the proxy");
ProxyAdmin(_proxy).upgradeTo(_newImplementation);
ProxyAdmin(_proxy).changeAdmin(_newProxyAdmin);
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
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/Proxies/Proxy.sol
pragma solidity ^0.5.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
// File: contracts/Proxies/BaseUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
// File: contracts/Proxies/UpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
// File: contracts/Proxies/BaseAdminUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
// File: contracts/Proxies/AdminUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
require(_admin != address(0x0), "Cannot set the admin address to address(0x0)");
_setAdmin(_admin);
}
}
// File: contracts/ACE/noteRegistry/NoteRegistryManager.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title NoteRegistryManager
* @author AZTEC
* @dev NoteRegistryManager will be inherrited by ACE, and its purpose is to manage the entire
lifecycle of noteRegistries and of
factories. It defines the methods which are used to deploy and upgrade registries, the methods
to enact state changes sent by
the owner of a registry, and it also manages the list of factories which are available.
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
contract NoteRegistryManager is IAZTEC, Ownable {
using SafeMath for uint256;
using VersioningUtils for uint24;
/**
* @dev event transmitted if and when a factory gets registered.
*/
event SetFactory(
uint8 indexed epoch,
uint8 indexed cryptoSystem,
uint8 indexed assetType,
address factoryAddress
);
event CreateNoteRegistry(
address registryOwner,
address registryAddress,
uint256 scalingFactor,
address linkedTokenAddress,
bool canAdjustSupply,
bool canConvert
);
event UpgradeNoteRegistry(
address registryOwner,
address proxyAddress,
address newBehaviourAddress
);
// Every user has their own note registry
struct NoteRegistry {
NoteRegistryBehaviour behaviour;
IERC20Mintable linkedToken;
uint24 latestFactory;
uint256 totalSupply;
uint256 totalSupplemented;
mapping(address => mapping(bytes32 => uint256)) publicApprovals;
}
mapping(address => NoteRegistry) public registries;
/**
* @dev index of available factories, using very similar structure to proof registry in ACE.sol.
* The structure of the index is (epoch, cryptoSystem, assetType).
*/
address[0x100][0x100][0x10000] factories;
uint8 public defaultRegistryEpoch = 1;
uint8 public defaultCryptoSystem = 1;
mapping(bytes32 => bool) public validatedProofs;
/**
* @dev Increment the default registry epoch
*/
function incrementDefaultRegistryEpoch() public onlyOwner {
defaultRegistryEpoch = defaultRegistryEpoch + 1;
}
/**
* @dev Set the default crypto system to be used
* @param _defaultCryptoSystem - default crypto system identifier
*/
function setDefaultCryptoSystem(uint8 _defaultCryptoSystem) public onlyOwner {
defaultCryptoSystem = _defaultCryptoSystem;
}
/**
* @dev Register a new Factory, iff no factory for that ID exists.
The epoch of any new factory must be at least as big as
the default registry epoch. Each asset type for each cryptosystem for
each epoch should have a note registry
*
* @param _factoryId - uint24 which contains 3 uint8s representing (epoch, cryptoSystem, assetType)
* @param _factoryAddress - address of the deployed factory
*/
function setFactory(uint24 _factoryId, address _factoryAddress) public onlyOwner {
require(_factoryAddress != address(0x0), "expected the factory contract to exist");
(uint8 epoch, uint8 cryptoSystem, uint8 assetType) = _factoryId.getVersionComponents();
require(factories[epoch][cryptoSystem][assetType] == address(0x0), "existing factories cannot be modified");
factories[epoch][cryptoSystem][assetType] = _factoryAddress;
emit SetFactory(epoch, cryptoSystem, assetType, _factoryAddress);
}
/**
* @dev Get the factory address associated with a particular factoryId. Fail if resulting address is 0x0.
*
* @param _factoryId - uint24 which contains 3 uint8s representing (epoch, cryptoSystem, assetType)
*/
function getFactoryAddress(uint24 _factoryId) public view returns (address factoryAddress) {
bool queryInvalid;
assembly {
// To compute the storage key for factoryAddress[epoch][cryptoSystem][assetType], we do the following:
// 1. get the factoryAddress slot
// 2. add (epoch * 0x10000) to the slot
// 3. add (cryptoSystem * 0x100) to the slot
// 4. add (assetType) to the slot
// i.e. the range of storage pointers allocated to factoryAddress ranges from
// factoryAddress_slot to (0xffff * 0x10000 + 0xff * 0x100 + 0xff = factoryAddress_slot 0xffffffff)
// Conveniently, the multiplications we have to perform on epoch, cryptoSystem and assetType correspond
// to their byte positions in _factoryId.
// i.e. (epoch * 0x10000) = and(_factoryId, 0xff0000)
// and (cryptoSystem * 0x100) = and(_factoryId, 0xff00)
// and (assetType) = and(_factoryId, 0xff)
// Putting this all together. The storage slot offset from '_factoryId' is...
// (_factoryId & 0xffff0000) + (_factoryId & 0xff00) + (_factoryId & 0xff)
// i.e. the storage slot offset IS the value of _factoryId
factoryAddress := sload(add(_factoryId, factories_slot))
queryInvalid := iszero(factoryAddress)
}
// wrap both require checks in a single if test. This means the happy path only has 1 conditional jump
if (queryInvalid) {
require(factoryAddress != address(0x0), "expected the factory address to exist");
}
}
/**
* @dev called when a mintable and convertible asset wants to perform an
action which puts the zero-knowledge and public
balance out of balance. For example, if minting in zero-knowledge, some
public tokens need to be added to the pool
managed by ACE, otherwise any private->public conversion runs the risk of not
having any public tokens to send.
*
* @param _value the value to be added
*/
function supplementTokens(uint256 _value) external {
NoteRegistry storage registry = registries[msg.sender];
require(address(registry.behaviour) != address(0x0), "note registry does not exist");
registry.totalSupply = registry.totalSupply.add(_value);
registry.totalSupplemented = registry.totalSupplemented.add(_value);
(
uint256 scalingFactor,
,,
bool canConvert,
bool canAdjustSupply
) = registry.behaviour.getRegistry();
require(canConvert == true, "note registry does not have conversion rights");
require(canAdjustSupply == true, "note registry does not have mint and burn rights");
registry.linkedToken.transferFrom(msg.sender, address(this), _value.mul(scalingFactor));
}
/**
* @dev Query the ACE for a previously validated proof
* @notice This is a virtual function, that must be overwritten by the contract that inherits from NoteRegistry
*
* @param _proof - unique identifier for the proof in question and being validated
* @param _proofHash - keccak256 hash of a bytes proofOutput argument. Used to identify the proof in question
* @param _sender - address of the entity that originally validated the proof
* @return boolean - true if the proof has previously been validated, false if not
*/
function validateProofByHash(uint24 _proof, bytes32 _proofHash, address _sender) public view returns (bool);
/**
* @dev Default noteRegistry creation method. Doesn't take the id of the factory to use,
but generates it based on defaults and on the passed flags.
*
* @param _linkedTokenAddress - address of any erc20 linked token (can not be 0x0 if canConvert is true)
* @param _scalingFactor - defines the number of tokens that an AZTEC note value of 1 maps to.
* @param _canAdjustSupply - whether the noteRegistry can make use of minting and burning
* @param _canConvert - whether the noteRegistry can transfer value from private to public
representation and vice versa
*/
function createNoteRegistry(
address _linkedTokenAddress,
uint256 _scalingFactor,
bool _canAdjustSupply,
bool _canConvert
) public {
uint8 assetType = getAssetTypeFromFlags(_canConvert, _canAdjustSupply);
uint24 factoryId = computeVersionFromComponents(defaultRegistryEpoch, defaultCryptoSystem, assetType);
createNoteRegistry(
_linkedTokenAddress,
_scalingFactor,
_canAdjustSupply,
_canConvert,
factoryId
);
}
/**
* @dev NoteRegistry creation method. Takes an id of the factory to use.
*
* @param _linkedTokenAddress - address of any erc20 linked token (can not be 0x0 if canConvert is true)
* @param _scalingFactor - defines the number of tokens that an AZTEC note value of 1 maps to.
* @param _canAdjustSupply - whether the noteRegistry can make use of minting and burning
* @param _canConvert - whether the noteRegistry can transfer value from private to public
representation and vice versa
* @param _factoryId - uint24 which contains 3 uint8s representing (epoch, cryptoSystem, assetType)
*/
function createNoteRegistry(
address _linkedTokenAddress,
uint256 _scalingFactor,
bool _canAdjustSupply,
bool _canConvert,
uint24 _factoryId
) public {
require(address(registries[msg.sender].behaviour) == address(0x0),
"address already has a linked note registry");
if (_canConvert) {
require(_linkedTokenAddress != address(0x0), "expected the linked token address to exist");
}
(,, uint8 assetType) = _factoryId.getVersionComponents();
// assetType is 0b00 where the bits represent (canAdjust, canConvert),
// so assetType can be one of 1, 2, 3 where
// 0 == no convert/no adjust (invalid)
// 1 == can convert/no adjust
// 2 == no convert/can adjust
// 3 == can convert/can adjust
uint8 flagAssetType = getAssetTypeFromFlags(_canConvert, _canAdjustSupply);
require (flagAssetType != uint8(0), "can not create asset with convert and adjust flags set to false");
require (flagAssetType == assetType, "expected note registry to match flags");
address factory = getFactoryAddress(_factoryId);
address behaviourAddress = NoteRegistryFactory(factory).deployNewBehaviourInstance();
bytes memory behaviourInitialisation = abi.encodeWithSignature(
"initialise(address,uint256,bool,bool)",
address(this),
_scalingFactor,
_canAdjustSupply,
_canConvert
);
address proxy = address(new AdminUpgradeabilityProxy(
behaviourAddress,
factory,
behaviourInitialisation
));
registries[msg.sender] = NoteRegistry({
behaviour: NoteRegistryBehaviour(proxy),
linkedToken: IERC20Mintable(_linkedTokenAddress),
latestFactory: _factoryId,
totalSupply: 0,
totalSupplemented: 0
});
emit CreateNoteRegistry(
msg.sender,
proxy,
_scalingFactor,
_linkedTokenAddress,
_canAdjustSupply,
_canConvert
);
}
/**
* @dev Method to upgrade the registry linked with the msg.sender to a new factory, based on _factoryId.
* The submitted _factoryId must be of epoch equal or greater than previous _factoryId, and of the same assetType.
*
* @param _factoryId - uint24 which contains 3 uint8s representing (epoch, cryptoSystem, assetType)
*/
function upgradeNoteRegistry(
uint24 _factoryId
) public {
NoteRegistry storage registry = registries[msg.sender];
require(address(registry.behaviour) != address(0x0), "note registry for sender doesn't exist");
(uint8 epoch,, uint8 assetType) = _factoryId.getVersionComponents();
uint24 oldFactoryId = registry.latestFactory;
(uint8 oldEpoch,, uint8 oldAssetType) = oldFactoryId.getVersionComponents();
require(epoch >= oldEpoch, "expected new registry to be of epoch equal or greater than existing registry");
require(assetType == oldAssetType, "expected assetType to be the same for old and new registry");
address factory = getFactoryAddress(_factoryId);
address newBehaviour = NoteRegistryFactory(factory).deployNewBehaviourInstance();
address oldFactory = getFactoryAddress(oldFactoryId);
registry.latestFactory = _factoryId;
NoteRegistryFactory(oldFactory).handoverBehaviour(address(registry.behaviour), newBehaviour, factory);
emit UpgradeNoteRegistry(
msg.sender,
address(registry.behaviour),
newBehaviour
);
}
/**
* @dev Internal method dealing with permissioning and transfer of public tokens.
*
* @param _publicOwner - the non-ACE party involved in this transaction. Either current or desired
* owner of public tokens
* @param _transferValue - the total public token value to transfer. Seperate value to abstract
* away scaling factors in first version of AZTEC
* @param _publicValue - the kPublic value to be used in zero-knowledge proofs
* @param _proofHash - usef for permissioning, hash of the proof that this spend is enacting
*
*/
function transferPublicTokens(
address _publicOwner,
uint256 _transferValue,
int256 _publicValue,
bytes32 _proofHash
)
internal
{
NoteRegistry storage registry = registries[msg.sender];
// if < 0, depositing
// else withdrawing
if (_publicValue < 0) {
uint256 approvalForAddressForHash = registry.publicApprovals[_publicOwner][_proofHash];
registry.totalSupply = registry.totalSupply.add(uint256(-_publicValue));
require(
approvalForAddressForHash >= uint256(-_publicValue),
"public owner has not validated a transfer of tokens"
);
registry.publicApprovals[_publicOwner][_proofHash] = approvalForAddressForHash.sub(uint256(-_publicValue));
registry.linkedToken.transferFrom(
_publicOwner,
address(this),
_transferValue);
} else {
registry.totalSupply = registry.totalSupply.sub(uint256(_publicValue));
registry.linkedToken.transfer(
_publicOwner,
_transferValue
);
}
}
/**
* @dev Update the state of the note registry according to transfer instructions issued by a
* zero-knowledge proof. This method will verify that the relevant proof has been validated,
* make sure the same proof has can't be re-used, and it then delegates to the relevant noteRegistry.
*
* @param _proof - unique identifier for a proof
* @param _proofOutput - transfer instructions issued by a zero-knowledge proof
* @param _proofSender - address of the entity sending the proof
*/
function updateNoteRegistry(
uint24 _proof,
bytes memory _proofOutput,
address _proofSender
) public {
NoteRegistry memory registry = registries[msg.sender];
require(address(registry.behaviour) != address(0x0), "note registry does not exist");
bytes32 proofHash = keccak256(_proofOutput);
bytes32 validatedProofHash = keccak256(abi.encode(proofHash, _proof, msg.sender));
require(
validateProofByHash(_proof, proofHash, _proofSender) == true,
"ACE has not validated a matching proof"
);
// clear record of valid proof - stops re-entrancy attacks and saves some gas
validatedProofs[validatedProofHash] = false;
(
address publicOwner,
uint256 transferValue,
int256 publicValue
) = registry.behaviour.updateNoteRegistry(_proof, _proofOutput);
if (publicValue != 0) {
transferPublicTokens(publicOwner, transferValue, publicValue, proofHash);
}
}
/**
* @dev Adds a public approval record to the noteRegistry, for use by ACE when it needs to transfer
public tokens it holds to an external address. It needs to be associated with the hash of a proof.
*/
function publicApprove(address _registryOwner, bytes32 _proofHash, uint256 _value) public {
NoteRegistry storage registry = registries[_registryOwner];
require(address(registry.behaviour) != address(0x0), "note registry does not exist");
registry.publicApprovals[msg.sender][_proofHash] = _value;
}
/**
* @dev Returns the registry for a given address.
*
* @param _registryOwner - address of the registry owner in question
*
* @return linkedTokenAddress - public ERC20 token that is linked to the NoteRegistry. This is used to
* transfer public value into and out of the system
* @return scalingFactor - defines how many ERC20 tokens are represented by one AZTEC note
* @return totalSupply - represents the total current supply of public tokens associated with a particular registry
* @return confidentialTotalMinted - keccak256 hash of the note representing the total minted supply
* @return confidentialTotalBurned - keccak256 hash of the note representing the total burned supply
* @return canConvert - flag set by the owner to decide whether the registry has public to private, and
* vice versa, conversion privilege
* @return canAdjustSupply - determines whether the registry has minting and burning privileges
*/
function getRegistry(address _registryOwner) public view returns (
address linkedToken,
uint256 scalingFactor,
bytes32 confidentialTotalMinted,
bytes32 confidentialTotalBurned,
uint256 totalSupply,
uint256 totalSupplemented,
bool canConvert,
bool canAdjustSupply
) {
NoteRegistry memory registry = registries[_registryOwner];
(
scalingFactor,
confidentialTotalMinted,
confidentialTotalBurned,
canConvert,
canAdjustSupply
) = registry.behaviour.getRegistry();
linkedToken = address(registry.linkedToken);
totalSupply = registry.totalSupply;
totalSupplemented = registry.totalSupplemented;
}
/**
* @dev Returns the note for a given address and note hash.
*
* @param _registryOwner - address of the registry owner
* @param _noteHash - keccak256 hash of the note coordiantes (gamma and sigma)
*
* @return status - status of the note, details whether the note is in a note registry
* or has been destroyed
* @return createdOn - time the note was created
* @return destroyedOn - time the note was destroyed
* @return noteOwner - address of the note owner
*/
function getNote(address _registryOwner, bytes32 _noteHash) public view returns (
uint8 status,
uint40 createdOn,
uint40 destroyedOn,
address noteOwner
) {
NoteRegistry memory registry = registries[_registryOwner];
return registry.behaviour.getNote(_noteHash);
}
/**
* @dev Internal utility method which converts two booleans into a uint8 where the first boolean
* represents (1 == true, 0 == false) the bit in position 1, and the second boolean the bit in position 2.
* The output is 1 for an asset which can convert between public and private, 2 for one with no conversion
* but with the ability to mint and/or burn, and 3 for a mixed asset which can convert and mint/burn
*
*/
function getAssetTypeFromFlags(bool _canConvert, bool _canAdjust) internal pure returns (uint8 assetType) {
uint8 convert = _canConvert ? 1 : 0;
uint8 adjust = _canAdjust ? 2 : 0;
assetType = convert + adjust;
}
/**
* @dev Internal utility method which converts three uint8s into a uint24
*
*/
function computeVersionFromComponents(
uint8 _first,
uint8 _second,
uint8 _third
) internal pure returns (uint24 version) {
assembly {
version := or(mul(_first, 0x10000), or(mul(_second, 0x100), _third))
}
}
/**
* @dev used for slow release, useless afterwards.
*/
function makeAssetAvailable(address _registryOwner) public onlyOwner {
NoteRegistry memory registry = registries[_registryOwner];
registry.behaviour.makeAvailable();
}
}
// File: contracts/libs/NoteUtils.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title NoteUtils
* @author AZTEC
* @dev NoteUtils is a utility library that extracts user-readable information from AZTEC proof outputs.
* Specifically, `bytes proofOutput` objects can be extracted from `bytes proofOutputs`,
* `bytes proofOutput` and `bytes note` can be extracted into their constituent components,
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
library NoteUtils {
/**
* @dev Get the number of entries in an AZTEC-ABI array (bytes proofOutputs, bytes inputNotes, bytes outputNotes)
* All 3 are rolled into a single function to eliminate 'wet' code - the implementations are identical
* @param _proofOutputsOrNotes `proofOutputs`, `inputNotes` or `outputNotes`
* @return number of entries in the pseudo dynamic array
*/
function getLength(bytes memory _proofOutputsOrNotes) internal pure returns (
uint len
) {
assembly {
// first word = the raw byte length
// second word = the actual number of entries (hence the 0x20 offset)
len := mload(add(_proofOutputsOrNotes, 0x20))
}
}
/**
* @dev Get a bytes object out of a dynamic AZTEC-ABI array
* @param _proofOutputsOrNotes `proofOutputs`, `inputNotes` or `outputNotes`
* @param _i the desired entry
* @return number of entries in the pseudo dynamic array
*/
function get(bytes memory _proofOutputsOrNotes, uint _i) internal pure returns (
bytes memory out
) {
bool valid;
assembly {
// check that i < the number of entries
valid := lt(
_i,
mload(add(_proofOutputsOrNotes, 0x20))
)
// memory map of the array is as follows:
// 0x00 - 0x20 : byte length of array
// 0x20 - 0x40 : n, the number of entries
// 0x40 - 0x40 + (0x20 * i) : relative memory offset to start of i'th entry (i <= n)
// Step 1: compute location of relative memory offset: _proofOutputsOrNotes + 0x40 + (0x20 * i)
// Step 2: loaded relative offset and add to _proofOutputsOrNotes to get absolute memory location
out := add(
mload(
add(
add(_proofOutputsOrNotes, 0x40),
mul(_i, 0x20)
)
),
_proofOutputsOrNotes
)
}
require(valid, "AZTEC array index is out of bounds");
}
/**
* @dev Extract constituent elements of a `bytes _proofOutput` object
* @param _proofOutput an AZTEC proof output
* @return inputNotes, AZTEC-ABI dynamic array of input AZTEC notes
* @return outputNotes, AZTEC-ABI dynamic array of output AZTEC notes
* @return publicOwner, the Ethereum address of the owner of any public tokens involved in the proof
* @return publicValue, the amount of public tokens involved in the proof
* if (publicValue > 0), this represents a transfer of tokens from ACE to publicOwner
* if (publicValue < 0), this represents a transfer of tokens from publicOwner to ACE
*/
function extractProofOutput(bytes memory _proofOutput) internal pure returns (
bytes memory inputNotes,
bytes memory outputNotes,
address publicOwner,
int256 publicValue
) {
assembly {
// memory map of a proofOutput:
// 0x00 - 0x20 : byte length of proofOutput
// 0x20 - 0x40 : relative offset to inputNotes
// 0x40 - 0x60 : relative offset to outputNotes
// 0x60 - 0x80 : publicOwner
// 0x80 - 0xa0 : publicValue
// 0xa0 - 0xc0 : challenge
inputNotes := add(_proofOutput, mload(add(_proofOutput, 0x20)))
outputNotes := add(_proofOutput, mload(add(_proofOutput, 0x40)))
publicOwner := and(
mload(add(_proofOutput, 0x60)),
0xffffffffffffffffffffffffffffffffffffffff
)
publicValue := mload(add(_proofOutput, 0x80))
}
}
/**
* @dev Extract the challenge from a bytes proofOutput variable
* @param _proofOutput bytes proofOutput, outputted from a proof validation smart contract
* @return bytes32 challenge - cryptographic variable that is part of the sigma protocol
*/
function extractChallenge(bytes memory _proofOutput) internal pure returns (
bytes32 challenge
) {
assembly {
challenge := mload(add(_proofOutput, 0xa0))
}
}
/**
* @dev Extract constituent elements of an AZTEC note
* @param _note an AZTEC note
* @return owner, Ethereum address of note owner
* @return noteHash, the hash of the note's public key
* @return metadata, note-specific metadata (contains public key and any extra data needed by note owner)
*/
function extractNote(bytes memory _note) internal pure returns (
address owner,
bytes32 noteHash,
bytes memory metadata
) {
assembly {
// memory map of a note:
// 0x00 - 0x20 : byte length of note
// 0x20 - 0x40 : note type
// 0x40 - 0x60 : owner
// 0x60 - 0x80 : noteHash
// 0x80 - 0xa0 : start of metadata byte array
owner := and(
mload(add(_note, 0x40)),
0xffffffffffffffffffffffffffffffffffffffff
)
noteHash := mload(add(_note, 0x60))
metadata := add(_note, 0x80)
}
}
/**
* @dev Get the note type
* @param _note an AZTEC note
* @return noteType
*/
function getNoteType(bytes memory _note) internal pure returns (
uint256 noteType
) {
assembly {
noteType := mload(add(_note, 0x20))
}
}
}
// File: contracts/libs/ProofUtils.sol
pragma solidity >= 0.5.0 <0.6.0;
/**
* @title ProofUtils
* @author AZTEC
* @dev Library of proof utility functions
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
library ProofUtils {
/**
* @dev We compress three uint8 numbers into only one uint24 to save gas.
* Reverts if the category is not one of [1, 2, 3, 4].
* @param proof The compressed uint24 number.
* @return A tuple (uint8, uint8, uint8) representing the epoch, category and proofId.
*/
function getProofComponents(uint24 proof) internal pure returns (uint8 epoch, uint8 category, uint8 id) {
assembly {
id := and(proof, 0xff)
category := and(div(proof, 0x100), 0xff)
epoch := and(div(proof, 0x10000), 0xff)
}
return (epoch, category, id);
}
}
// File: contracts/libs/SafeMath8.sol
pragma solidity >=0.5.0 <= 0.6.0;
/**
* @title SafeMath8
* @author AZTEC
* @dev Library of SafeMath arithmetic operations
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
library SafeMath8 {
/**
* @dev SafeMath multiplication
* @param a - uint8 multiplier
* @param b - uint8 multiplicand
* @return uint8 result of multiplying a and b
*/
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint256 c = uint256(a) * uint256(b);
require(c < 256, "uint8 mul triggered integer overflow");
return uint8(c);
}
/**
* @dev SafeMath division
* @param a - uint8 dividend
* @param b - uint8 divisor
* @return uint8 result of dividing a by b
*/
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// assert(a == b * c + a % b); // There is no case in which this doesnβt hold
return a / b;
}
/**
* @dev SafeMath subtraction
* @param a - uint8 minuend
* @param b - uint8 subtrahend
* @return uint8 result of subtracting b from a
*/
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
require(b <= a, "uint8 sub triggered integer underflow");
return a - b;
}
/**
* @dev SafeMath addition
* @param a - uint8 addend
* @param b - uint8 addend
* @return uint8 result of adding a and b
*/
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
require(c >= a, "uint8 add triggered integer overflow");
return c;
}
}
// File: contracts/ACE/ACE.sol
pragma solidity >=0.5.0 <0.6.0;
// TODO: v-- harmonize
/**
* @title The AZTEC Cryptography Engine
* @author AZTEC
* @dev ACE validates the AZTEC protocol's family of zero-knowledge proofs, which enables
* digital asset builders to construct fungible confidential digital assets according to the AZTEC token standard.
*
* Copyright 2020 Spilsbury Holdings Ltd
*
* Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
contract ACE is IAZTEC, Ownable, NoteRegistryManager {
using NoteUtils for bytes;
using ProofUtils for uint24;
using SafeMath for uint256;
using SafeMath8 for uint8;
event SetCommonReferenceString(bytes32[6] _commonReferenceString);
event SetProof(
uint8 indexed epoch,
uint8 indexed category,
uint8 indexed id,
address validatorAddress
);
event IncrementLatestEpoch(uint8 newLatestEpoch);
// The commonReferenceString contains one G1 group element and one G2 group element,
// that are created via the AZTEC protocol's trusted setup. All zero-knowledge proofs supported
// by ACE use the same common reference string.
bytes32[6] private commonReferenceString;
// `validators`contains the addresses of the contracts that validate specific proof types
address[0x100][0x100][0x10000] public validators;
// a list of invalidated proof ids, used to blacklist proofs in the case of a vulnerability being discovered
bool[0x100][0x100][0x10000] public disabledValidators;
// latest proof epoch accepted by this contract
uint8 public latestEpoch = 1;
/**
* @dev contract constructor. Sets the owner of ACE
**/
constructor() public Ownable() {}
/**
* @dev Mint AZTEC notes
*
* @param _proof the AZTEC proof object
* @param _proofData the mint proof construction data
* @param _proofSender the Ethereum address of the original transaction sender. It is explicitly assumed that
* an asset using ACE supplies this field correctly - if they don't their asset is vulnerable to front-running
* Unnamed param is the AZTEC zero-knowledge proof data
* @return two `bytes` objects. The first contains the new confidentialTotalSupply note and the second contains the
* notes that were created. Returned so that a zkAsset can emit the appropriate events
*/
function mint(
uint24 _proof,
bytes calldata _proofData,
address _proofSender
) external returns (bytes memory) {
NoteRegistry memory registry = registries[msg.sender];
require(address(registry.behaviour) != address(0x0), "note registry does not exist for the given address");
// Check that it's a mintable proof
(, uint8 category, ) = _proof.getProofComponents();
require(category == uint8(ProofCategory.MINT), "this is not a mint proof");
bytes memory _proofOutputs = this.validateProof(_proof, _proofSender, _proofData);
require(_proofOutputs.getLength() > 0, "call to validateProof failed");
registry.behaviour.mint(_proofOutputs);
return(_proofOutputs);
}
/**
* @dev Burn AZTEC notes
*
* @param _proof the AZTEC proof object
* @param _proofData the burn proof construction data
* @param _proofSender the Ethereum address of the original transaction sender. It is explicitly assumed that
* an asset using ACE supplies this field correctly - if they don't their asset is vulnerable to front-running
* Unnamed param is the AZTEC zero-knowledge proof data
* @return two `bytes` objects. The first contains the new confidentialTotalSupply note and the second contains the
* notes that were created. Returned so that a zkAsset can emit the appropriate events
*/
function burn(
uint24 _proof,
bytes calldata _proofData,
address _proofSender
) external returns (bytes memory) {
NoteRegistry memory registry = registries[msg.sender];
require(address(registry.behaviour) != address(0x0), "note registry does not exist for the given address");
// Check that it's a burnable proof
(, uint8 category, ) = _proof.getProofComponents();
require(category == uint8(ProofCategory.BURN), "this is not a burn proof");
bytes memory _proofOutputs = this.validateProof(_proof, _proofSender, _proofData);
require(_proofOutputs.getLength() > 0, "call to validateProof failed");
registry.behaviour.burn(_proofOutputs);
return _proofOutputs;
}
/**
* @dev Validate an AZTEC zero-knowledge proof. ACE will issue a validation transaction to the smart contract
* linked to `_proof`. The validator smart contract will have the following interface:
*
* function validate(
* bytes _proofData,
* address _sender,
* bytes32[6] _commonReferenceString
* ) public returns (bytes)
*
* @param _proof the AZTEC proof object
* @param _sender the Ethereum address of the original transaction sender. It is explicitly assumed that
* an asset using ACE supplies this field correctly - if they don't their asset is vulnerable to front-running
* Unnamed param is the AZTEC zero-knowledge proof data
* @return a `bytes proofOutputs` variable formatted according to the Cryptography Engine standard
*/
function validateProof(uint24 _proof, address _sender, bytes calldata) external returns (bytes memory) {
require(_proof != 0, "expected the proof to be valid");
// validate that the provided _proof object maps to a corresponding validator and also that
// the validator is not disabled
address validatorAddress = getValidatorAddress(_proof);
bytes memory proofOutputs;
assembly {
// the first evm word of the 3rd function param is the abi encoded location of proof data
let proofDataLocation := add(0x04, calldataload(0x44))
// manually construct validator calldata map
let memPtr := mload(0x40)
mstore(add(memPtr, 0x04), 0x100) // location in calldata of the start of `bytes _proofData` (0x100)
mstore(add(memPtr, 0x24), _sender)
mstore(add(memPtr, 0x44), sload(commonReferenceString_slot))
mstore(add(memPtr, 0x64), sload(add(0x01, commonReferenceString_slot)))
mstore(add(memPtr, 0x84), sload(add(0x02, commonReferenceString_slot)))
mstore(add(memPtr, 0xa4), sload(add(0x03, commonReferenceString_slot)))
mstore(add(memPtr, 0xc4), sload(add(0x04, commonReferenceString_slot)))
mstore(add(memPtr, 0xe4), sload(add(0x05, commonReferenceString_slot)))
// 0x104 because there's an address, the length 6 and the static array items
let destination := add(memPtr, 0x104)
// note that we offset by 0x20 because the first word is the length of the dynamic bytes array
let proofDataSize := add(calldataload(proofDataLocation), 0x20)
// copy the calldata into memory so we can call the validator contract
calldatacopy(destination, proofDataLocation, proofDataSize)
// call our validator smart contract, and validate the call succeeded
let callSize := add(proofDataSize, 0x104)
switch staticcall(gas, validatorAddress, memPtr, callSize, 0x00, 0x00)
case 0 {
mstore(0x00, 400) revert(0x00, 0x20) // call failed because proof is invalid
}
// copy returndata to memory
returndatacopy(memPtr, 0x00, returndatasize)
// store the proof outputs in memory
mstore(0x40, add(memPtr, returndatasize))
// the first evm word in the memory pointer is the abi encoded location of the actual returned data
proofOutputs := add(memPtr, mload(memPtr))
}
// if this proof satisfies a balancing relationship, we need to record the proof hash
if (((_proof >> 8) & 0xff) == uint8(ProofCategory.BALANCED)) {
uint256 length = proofOutputs.getLength();
for (uint256 i = 0; i < length; i += 1) {
bytes32 proofHash = keccak256(proofOutputs.get(i));
bytes32 validatedProofHash = keccak256(abi.encode(proofHash, _proof, msg.sender));
validatedProofs[validatedProofHash] = true;
}
}
return proofOutputs;
}
/**
* @dev Clear storage variables set when validating zero-knowledge proofs.
* The only address that can clear data from `validatedProofs` is the address that created the proof.
* Function is designed to utilize [EIP-1283](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1283.md)
* to reduce gas costs. It is highly likely that any storage variables set by `validateProof`
* are only required for the duration of a single transaction.
* E.g. a decentralized exchange validating a swap proof and sending transfer instructions to
* two confidential assets.
* This method allows the calling smart contract to recover most of the gas spent by setting `validatedProofs`
* @param _proof the AZTEC proof object
* @param _proofHashes dynamic array of proof hashes
*/
function clearProofByHashes(uint24 _proof, bytes32[] calldata _proofHashes) external {
uint256 length = _proofHashes.length;
for (uint256 i = 0; i < length; i += 1) {
bytes32 proofHash = _proofHashes[i];
require(proofHash != bytes32(0x0), "expected no empty proof hash");
bytes32 validatedProofHash = keccak256(abi.encode(proofHash, _proof, msg.sender));
require(validatedProofs[validatedProofHash] == true, "can only clear previously validated proofs");
validatedProofs[validatedProofHash] = false;
}
}
/**
* @dev Set the common reference string.
* If the trusted setup is re-run, we will need to be able to change the crs
* @param _commonReferenceString the new commonReferenceString
*/
function setCommonReferenceString(bytes32[6] memory _commonReferenceString) public {
require(isOwner(), "only the owner can set the common reference string");
commonReferenceString = _commonReferenceString;
emit SetCommonReferenceString(_commonReferenceString);
}
/**
* @dev Forever invalidate the given proof.
* @param _proof the AZTEC proof object
*/
function invalidateProof(uint24 _proof) public {
require(isOwner(), "only the owner can invalidate a proof");
(uint8 epoch, uint8 category, uint8 id) = _proof.getProofComponents();
require(validators[epoch][category][id] != address(0x0), "can only invalidate proofs that exist");
disabledValidators[epoch][category][id] = true;
}
/**
* @dev Validate a previously validated AZTEC proof via its hash
* This enables confidential assets to receive transfer instructions from a dApp that
* has already validated an AZTEC proof that satisfies a balancing relationship.
* @param _proof the AZTEC proof object
* @param _proofHash the hash of the `proofOutput` received by the asset
* @param _sender the Ethereum address of the contract issuing the transfer instruction
* @return a boolean that signifies whether the corresponding AZTEC proof has been validated
*/
function validateProofByHash(
uint24 _proof,
bytes32 _proofHash,
address _sender
) public view returns (bool) {
// We need create a unique encoding of _proof, _proofHash and _sender,
// and use as a key to access validatedProofs
// We do this by computing bytes32 validatedProofHash = keccak256(ABI.encode(_proof, _proofHash, _sender))
// We also need to access disabledValidators[_proof.epoch][_proof.category][_proof.id]
// This bit is implemented in Yul, as 3-dimensional array access chews through
// a lot of gas in Solidity, as does ABI.encode
bytes32 validatedProofHash;
bool isValidatorDisabled;
assembly {
// inside _proof, we have 3 packed variables : [epoch, category, id]
// each is a uint8.
// We need to compute the storage key for `disabledValidators[epoch][category][id]`
// Type of array is bool[0x100][0x100][0x100]
// Solidity will only squish 32 boolean variables into a single storage slot, not 256
// => result of disabledValidators[epoch][category] is stored in 0x08 storage slots
// => result of disabledValidators[epoch] is stored in 0x08 * 0x100 = 0x800 storage slots
// To compute the storage slot disabledValidators[epoch][category][id], we do the following:
// 1. get the disabledValidators slot
// 2. add (epoch * 0x800) to the slot (or epoch << 11)
// 3. add (category * 0x08) to the slot (or category << 3)
// 4. add (id / 0x20) to the slot (or id >> 5)
// Once the storage slot has been loaded, we need to isolate the byte that contains our boolean
// This will be equal to id % 0x20, which is also id & 0x1f
// Putting this all together. The storage slot offset from '_proof' is...
// epoch: ((_proof & 0xff0000) >> 16) << 11 = ((_proof & 0xff0000) >> 5)
// category: ((_proof & 0xff00) >> 8) << 3 = ((_proof & 0xff00) >> 5)
// id: (_proof & 0xff) >> 5
// i.e. the storage slot offset = _proof >> 5
// the byte index of the storage word that we require, is equal to (_proof & 0x1f)
// to convert to a bit index, we multiply by 8
// i.e. bit index = shl(3, and(_proof & 0x1f))
// => result = shr(shl(3, and(_proof & 0x1f), value))
isValidatorDisabled :=
shr(
shl(
0x03,
and(_proof, 0x1f)
),
sload(add(shr(5, _proof), disabledValidators_slot))
)
// Next, compute validatedProofHash = keccak256(abi.encode(_proofHash, _proof, _sender))
// cache free memory pointer - we will overwrite it when computing hash (cheaper than using free memory)
let memPtr := mload(0x40)
mstore(0x00, _proofHash)
mstore(0x20, _proof)
mstore(0x40, _sender)
validatedProofHash := keccak256(0x00, 0x60)
mstore(0x40, memPtr) // restore the free memory pointer
}
require(isValidatorDisabled == false, "proof id has been invalidated");
return validatedProofs[validatedProofHash];
}
/**
* @dev Adds or modifies a proof into the Cryptography Engine.
* This method links a given `_proof` to a smart contract validator.
* @param _proof the AZTEC proof object
* @param _validatorAddress the address of the smart contract validator
*/
function setProof(
uint24 _proof,
address _validatorAddress
) public {
require(isOwner(), "only the owner can set a proof");
require(_validatorAddress != address(0x0), "expected the validator address to exist");
(uint8 epoch, uint8 category, uint8 id) = _proof.getProofComponents();
require(epoch <= latestEpoch, "the proof epoch cannot be bigger than the latest epoch");
require(validators[epoch][category][id] == address(0x0), "existing proofs cannot be modified");
validators[epoch][category][id] = _validatorAddress;
emit SetProof(epoch, category, id, _validatorAddress);
}
/**
* @dev Increments the `latestEpoch` storage variable.
*/
function incrementLatestEpoch() public {
require(isOwner(), "only the owner can update the latest epoch");
latestEpoch = latestEpoch.add(1);
emit IncrementLatestEpoch(latestEpoch);
}
/**
* @dev Returns the common reference string.
* We use a custom getter for `commonReferenceString` - the default getter created by making the storage
* variable public indexes individual elements of the array, and we want to return the whole array
*/
function getCommonReferenceString() public view returns (bytes32[6] memory) {
return commonReferenceString;
}
/**
* @dev Get the address of the relevant validator contract
*
* @param _proof unique identifier of a particular proof
* @return validatorAddress - the address of the validator contract
*/
function getValidatorAddress(uint24 _proof) public view returns (address validatorAddress) {
bool isValidatorDisabled;
bool queryInvalid;
assembly {
// To compute the storage key for validatorAddress[epoch][category][id], we do the following:
// 1. get the validatorAddress slot
// 2. add (epoch * 0x10000) to the slot
// 3. add (category * 0x100) to the slot
// 4. add (id) to the slot
// i.e. the range of storage pointers allocated to validatorAddress ranges from
// validatorAddress_slot to (0xffff * 0x10000 + 0xff * 0x100 + 0xff = validatorAddress_slot 0xffffffff)
// Conveniently, the multiplications we have to perform on epoch, category and id correspond
// to their byte positions in _proof.
// i.e. (epoch * 0x10000) = and(_proof, 0xff0000)
// and (category * 0x100) = and(_proof, 0xff00)
// and (id) = and(_proof, 0xff)
// Putting this all together. The storage slot offset from '_proof' is...
// (_proof & 0xffff0000) + (_proof & 0xff00) + (_proof & 0xff)
// i.e. the storage slot offset IS the value of _proof
validatorAddress := sload(add(_proof, validators_slot))
isValidatorDisabled :=
shr(
shl(0x03, and(_proof, 0x1f)),
sload(add(shr(5, _proof), disabledValidators_slot))
)
queryInvalid := or(iszero(validatorAddress), isValidatorDisabled)
}
// wrap both require checks in a single if test. This means the happy path only has 1 conditional jump
if (queryInvalid) {
require(validatorAddress != address(0x0), "expected the validator address to exist");
require(isValidatorDisabled == false, "expected the validator address to not be disabled");
}
}
}
| Set the common reference string. If the trusted setup is re-run, we will need to be able to change the crs _commonReferenceString the new commonReferenceString/ | function setCommonReferenceString(bytes32[6] memory _commonReferenceString) public {
require(isOwner(), "only the owner can set the common reference string");
commonReferenceString = _commonReferenceString;
emit SetCommonReferenceString(_commonReferenceString);
}
| 6,450,243 |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {IVotingPowerStrategy} from '../../interfaces/governance/IVotingPowerStrategy.sol';
import {IKyberGovernance} from '../../interfaces/governance/IKyberGovernance.sol';
import {IKyberStaking} from '../../interfaces/staking/IKyberStaking.sol';
import {EpochUtils} from '../../misc/EpochUtils.sol';
/**
* @title Voting Power Strategy contract based on epoch mechanism
* @dev Smart contract containing logic to measure users' relative power to vote.
**/
contract EpochVotingPowerStrategy is IVotingPowerStrategy, EpochUtils {
using SafeMath for uint256;
uint256 public constant MAX_PROPOSAL_PER_EPOCH = 10;
IKyberStaking public immutable staking;
IKyberGovernance public immutable governance;
mapping(uint256 => uint256[]) internal epochProposals;
/**
* @dev Constructor, register tokens used for Voting and Proposition Powers.
* @param _governance The address of governance contract.
* @param _staking The address of the knc staking contract.
**/
constructor(IKyberGovernance _governance, IKyberStaking _staking)
EpochUtils(_staking.epochPeriodInSeconds(), _staking.firstEpochStartTime())
{
staking = _staking;
governance = _governance;
}
modifier onlyStaking() {
require(msg.sender == address(staking), 'only staking');
_;
}
modifier onlyGovernance() {
require(msg.sender == address(governance), 'only governance');
_;
}
/**
* @dev stores proposalIds per epoch mapping, so when user withdraws,
* voting power strategy is aware of which proposals are affected
*/
function handleProposalCreation(
uint256 proposalId,
uint256 startTime,
uint256 /*endTime*/
) external override onlyGovernance {
uint256 epoch = getEpochNumber(startTime);
epochProposals[epoch].push(proposalId);
}
/**
* @dev remove proposalId from proposalIds per epoch mapping, so when user withdraws,
* voting power strategy is aware of which proposals are affected
*/
function handleProposalCancellation(uint256 proposalId) external override onlyGovernance {
IKyberGovernance.ProposalWithoutVote memory proposal = governance.getProposalById(proposalId);
uint256 epoch = getEpochNumber(proposal.startTime);
uint256[] storage proposalIds = epochProposals[epoch];
for (uint256 i = 0; i < proposalIds.length; i++) {
if (proposalIds[i] == proposalId) {
// remove this proposalId out of list
proposalIds[i] = proposalIds[proposalIds.length - 1];
proposalIds.pop();
break;
}
}
}
/**
* @dev assume that governance check start and end time
* @dev call to init data if needed, and return voter's voting power
* @dev proposalId, choice: unused param for future usage
*/
function handleVote(
address voter,
uint256, /*proposalId*/
uint256 /*choice*/
) external override onlyGovernance returns (uint256 votingPower) {
(uint256 stake, uint256 dStake, address representative) = staking
.initAndReturnStakerDataForCurrentEpoch(voter);
return representative == voter ? stake.add(dStake) : dStake;
}
/**
* @dev handle user withdraw from staking contract
* @dev notice for governance that voting power for proposalIds in current epoch is changed
*/
function handleWithdrawal(
address user,
uint256 /*reduceAmount*/
) external override onlyStaking {
uint256 currentEpoch = getCurrentEpochNumber();
(uint256 stake, uint256 dStake, address representative) = staking.getStakerData(
user,
currentEpoch
);
uint256 votingPower = representative == user ? stake.add(dStake) : dStake;
governance.handleVotingPowerChanged(user, votingPower, epochProposals[currentEpoch]);
}
/**
* @dev call to get voter's voting power given timestamp
* @dev only for reading purpose. when submitVote, should call handleVote instead
*/
function getVotingPower(address voter, uint256 timestamp)
external
override
view
returns (uint256 votingPower)
{
uint256 currentEpoch = getEpochNumber(timestamp);
(uint256 stake, uint256 dStake, address representative) = staking.getStakerData(
voter,
currentEpoch
);
votingPower = representative == voter ? stake.add(dStake) : dStake;
}
/**
* @dev validate that a proposal is suitable for epoch mechanism
*/
function validateProposalCreation(uint256 startTime, uint256 endTime)
external
override
view
returns (bool)
{
/// start in the past
if (startTime < block.timestamp) {
return false;
}
uint256 startEpoch = getEpochNumber(startTime);
/// proposal must start and end within an epoch
if (startEpoch != getEpochNumber(endTime)) {
return false;
}
/// proposal must be current or next epoch
if (startEpoch > getCurrentEpochNumber().add(1)) {
return false;
}
/// too many proposals
if (epochProposals[startEpoch].length >= MAX_PROPOSAL_PER_EPOCH) {
return false;
}
return true;
}
function getMaxVotingPower() external override view returns (uint256) {
return staking.kncToken().totalSupply();
}
function getListProposalIds(uint256 epoch) external view returns (uint256[] memory proposalIds) {
return epochProposals[epoch];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IWithdrawHandler} from '../staking/IWithdrawHandler.sol';
interface IVotingPowerStrategy is IWithdrawHandler {
/**
* @dev call by governance when create a proposal
*/
function handleProposalCreation(
uint256 proposalId,
uint256 startTime,
uint256 endTime
) external;
/**
* @dev call by governance when cancel a proposal
*/
function handleProposalCancellation(uint256 proposalId) external;
/**
* @dev call by governance when submitting a vote
* @param choice: unused param for future usage
* @return votingPower of voter
*/
function handleVote(
address voter,
uint256 proposalId,
uint256 choice
) external returns (uint256 votingPower);
/**
* @dev get voter's voting power given timestamp
* @dev for reading purposes and validating voting power for creating/canceling proposal in the furture
* @dev when submitVote, should call 'handleVote' instead
*/
function getVotingPower(address voter, uint256 timestamp)
external
view
returns (uint256 votingPower);
/**
* @dev validate that startTime and endTime are suitable for calculating voting power
* @dev with current version, startTime and endTime must be in the sameEpcoh
*/
function validateProposalCreation(uint256 startTime, uint256 endTime)
external
view
returns (bool);
/**
* @dev getMaxVotingPower at current time
* @dev call by governance when creating a proposal
*/
function getMaxVotingPower() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IExecutorWithTimelock} from './IExecutorWithTimelock.sol';
import {IVotingPowerStrategy} from './IVotingPowerStrategy.sol';
interface IKyberGovernance {
enum ProposalState {
Pending,
Canceled,
Active,
Failed,
Succeeded,
Queued,
Expired,
Executed,
Finalized
}
enum ProposalType {Generic, Binary}
/// For Binary proposal, optionBitMask is 0/1/2
/// For Generic proposal, optionBitMask is bitmask of voted options
struct Vote {
uint32 optionBitMask;
uint224 votingPower;
}
struct ProposalWithoutVote {
uint256 id;
ProposalType proposalType;
address creator;
IExecutorWithTimelock executor;
IVotingPowerStrategy strategy;
address[] targets;
uint256[] weiValues;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
string[] options;
uint256[] voteCounts;
uint256 totalVotes;
uint256 maxVotingPower;
uint256 startTime;
uint256 endTime;
uint256 executionTime;
string link;
bool executed;
bool canceled;
}
struct Proposal {
ProposalWithoutVote proposalData;
mapping(address => Vote) votes;
}
struct BinaryProposalParams {
address[] targets;
uint256[] weiValues;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
}
/**
* @dev emitted when a new binary proposal is created
* @param proposalId id of the binary proposal
* @param creator address of the creator
* @param executor ExecutorWithTimelock contract that will execute the proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param targets list of contracts called by proposal's associated transactions
* @param weiValues 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 startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param link URL link of the proposal
* @param maxVotingPower max voting power for this proposal
**/
event BinaryProposalCreated(
uint256 proposalId,
address indexed creator,
IExecutorWithTimelock indexed executor,
IVotingPowerStrategy indexed strategy,
address[] targets,
uint256[] weiValues,
string[] signatures,
bytes[] calldatas,
bool[] withDelegatecalls,
uint256 startTime,
uint256 endTime,
string link,
uint256 maxVotingPower
);
/**
* @dev emitted when a new generic proposal is created
* @param proposalId id of the generic proposal
* @param creator address of the creator
* @param executor ExecutorWithTimelock contract that will execute the proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param options list of proposal vote options
* @param startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param link URL link of the proposal
* @param maxVotingPower max voting power for this proposal
**/
event GenericProposalCreated(
uint256 proposalId,
address indexed creator,
IExecutorWithTimelock indexed executor,
IVotingPowerStrategy indexed strategy,
string[] options,
uint256 startTime,
uint256 endTime,
string link,
uint256 maxVotingPower
);
/**
* @dev emitted when a proposal is canceled
* @param proposalId id of the proposal
**/
event ProposalCanceled(uint256 proposalId);
/**
* @dev emitted when a proposal is queued
* @param proposalId 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 indexed proposalId,
uint256 executionTime,
address indexed initiatorQueueing
);
/**
* @dev emitted when a proposal is executed
* @param proposalId id of the proposal
* @param initiatorExecution address of the initiator of the execution transaction
**/
event ProposalExecuted(uint256 proposalId, address indexed initiatorExecution);
/**
* @dev emitted when a vote is registered
* @param proposalId id of the proposal
* @param voter address of the voter
* @param voteOptions vote options selected by voter
* @param votingPower Power of the voter/vote
**/
event VoteEmitted(
uint256 indexed proposalId,
address indexed voter,
uint32 indexed voteOptions,
uint224 votingPower
);
/**
* @dev emitted when a vote is registered
* @param proposalId id of the proposal
* @param voter address of the voter
* @param voteOptions vote options selected by voter
* @param oldVotingPower Old power of the voter/vote
* @param newVotingPower New power of the voter/vote
**/
event VotingPowerChanged(
uint256 indexed proposalId,
address indexed voter,
uint32 indexed voteOptions,
uint224 oldVotingPower,
uint224 newVotingPower
);
event DaoOperatorTransferred(address indexed newDaoOperator);
event ExecutorAuthorized(address indexed executor);
event ExecutorUnauthorized(address indexed executor);
event VotingPowerStrategyAuthorized(address indexed strategy);
event VotingPowerStrategyUnauthorized(address indexed strategy);
/**
* @dev Function is triggered when users withdraw from staking and change voting power
*/
function handleVotingPowerChanged(
address staker,
uint256 newVotingPower,
uint256[] calldata proposalIds
) external;
/**
* @dev Creates a Binary Proposal (needs to be validated by the Proposal Validator)
* @param executor The ExecutorWithTimelock contract that will execute the proposal
* @param strategy voting power strategy of the proposal
* @param executionParams data for execution, includes
* targets list of contracts called by proposal's associated transactions
* weiValues list of value in wei for each proposal's associated transaction
* signatures list of function signatures (can be empty)
* to be used when created the callData
* calldatas list of calldatas: if associated signature empty,
* calldata ready, else calldata is arguments
* withDelegatecalls boolean, true = transaction delegatecalls the taget,
* else calls the target
* @param startTime start timestamp to allow vote
* @param endTime end timestamp of the proposal
* @param link link to the proposal description
**/
function createBinaryProposal(
IExecutorWithTimelock executor,
IVotingPowerStrategy strategy,
BinaryProposalParams memory executionParams,
uint256 startTime,
uint256 endTime,
string memory link
) external returns (uint256 proposalId);
/**
* @dev Creates a Generic Proposal
* @param executor ExecutorWithTimelock contract that will execute the proposal
* @param strategy votingPowerStrategy contract to calculate voting power
* @param options list of proposal vote options
* @param startTime timestamp when vote starts
* @param endTime timestamp when vote ends
* @param link URL link of the proposal
**/
function createGenericProposal(
IExecutorWithTimelock executor,
IVotingPowerStrategy strategy,
string[] memory options,
uint256 startTime,
uint256 endTime,
string memory link
) external returns (uint256 proposalId);
/**
* @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 optionBitMask vote option(s) selected
**/
function submitVote(uint256 proposalId, uint256 optionBitMask) external;
/**
* @dev Function to register the vote of user that has voted offchain via signature
* @param proposalId id of the proposal
* @param choice the bit mask of voted options
* @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,
uint256 choice,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Add new addresses to the list of authorized executors
* @param executors list of new addresses to be authorized executors
**/
function authorizeExecutors(address[] calldata 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[] calldata executors) external;
/**
* @dev Add new addresses to the list of authorized strategies
* @param strategies list of new addresses to be authorized strategies
**/
function authorizeVotingPowerStrategies(address[] calldata strategies) external;
/**
* @dev Remove addresses to the list of authorized strategies
* @param strategies list of addresses to be removed as authorized strategies
**/
function unauthorizeVotingPowerStrategies(address[] calldata strategies) external;
/**
* @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 Returns whether an address is an authorized strategy
* @param strategy address to evaluate as authorized strategy
* @return true if authorized
**/
function isVotingPowerStrategyAuthorized(address strategy) external view returns (bool);
/**
* @dev Getter the address of the guardian, that can mainly cancel proposals
* @return The address of the guardian
**/
function getDaoOperator() 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 ProposalWithoutVote memory object
**/
function getProposalById(uint256 proposalId) external view returns (ProposalWithoutVote memory);
/**
* @dev Getter of the vote data of a proposal by id
* including totalVotes, voteCounts and options
* @param proposalId id of the proposal
* @return (totalVotes, voteCounts, options)
**/
function getProposalVoteDataById(uint256 proposalId)
external
view
returns (
uint256,
uint256[] memory,
string[] memory
);
/**
* @dev Getter of the Vote of a voter about a proposal
* Note: Vote is a struct: ({uint32 bitOptionMask, uint224 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.7.6;
pragma abicoder v2;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IEpochUtils} from './IEpochUtils.sol';
interface IKyberStaking is IEpochUtils {
event Delegated(
address indexed staker,
address indexed representative,
uint256 indexed epoch,
bool isDelegated
);
event Deposited(uint256 curEpoch, address indexed staker, uint256 amount);
event Withdraw(uint256 indexed curEpoch, address indexed staker, uint256 amount);
function initAndReturnStakerDataForCurrentEpoch(address staker)
external
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
function deposit(uint256 amount) external;
function delegate(address dAddr) external;
function withdraw(uint256 amount) external;
/**
* @notice return combine data (stake, delegatedStake, representative) of a staker
* @dev allow to get staker data up to current epoch + 1
*/
function getStakerData(address staker, uint256 epoch)
external
view
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
function getLatestStakerData(address staker)
external
view
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
/**
* @notice return raw data of a staker for an epoch
* WARN: should be used only for initialized data
* if data has not been initialized, it will return all 0
* pool master shouldn't use this function to compute/distribute rewards of pool members
*/
function getStakerRawData(address staker, uint256 epoch)
external
view
returns (
uint256 stake,
uint256 delegatedStake,
address representative
);
function kncToken() external view returns (IERC20);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import '@openzeppelin/contracts/math/SafeMath.sol';
import '../interfaces/staking/IEpochUtils.sol';
contract EpochUtils is IEpochUtils {
using SafeMath for uint256;
uint256 public immutable override epochPeriodInSeconds;
uint256 public immutable override firstEpochStartTime;
constructor(uint256 _epochPeriod, uint256 _startTime) {
require(_epochPeriod > 0, 'ctor: epoch period is 0');
epochPeriodInSeconds = _epochPeriod;
firstEpochStartTime = _startTime;
}
function getCurrentEpochNumber() public override view returns (uint256) {
return getEpochNumber(block.timestamp);
}
function getEpochNumber(uint256 currentTime) public override view returns (uint256) {
if (currentTime < firstEpochStartTime || epochPeriodInSeconds == 0) {
return 0;
}
// ((currentTime - firstEpochStartTime) / epochPeriodInSeconds) + 1;
return ((currentTime.sub(firstEpochStartTime)).div(epochPeriodInSeconds)).add(1);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
/**
* @title Interface for callbacks hooks when user withdraws from staking contract
*/
interface IWithdrawHandler {
function handleWithdrawal(address staker, uint256 reduceAmount) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IKyberGovernance} from './IKyberGovernance.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 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);
/**
* @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(IKyberGovernance 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.6;
interface IEpochUtils {
function epochPeriodInSeconds() external view returns (uint256);
function firstEpochStartTime() external view returns (uint256);
function getCurrentEpochNumber() external view returns (uint256);
function getEpochNumber(uint256 timestamp) external view returns (uint256);
}
| assume that governance check start and end time call to init data if needed, and return voter's voting power proposalId, choice: unused param for future usage/ | function handleVote(
address voter,
uint256, /*proposalId*/
uint256 /*choice*/
) external override onlyGovernance returns (uint256 votingPower) {
(uint256 stake, uint256 dStake, address representative) = staking
.initAndReturnStakerDataForCurrentEpoch(voter);
return representative == voter ? stake.add(dStake) : dStake;
}
| 1,596,857 |
pragma solidity 0.6.12;
//
/**
* @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;
}
}
//
/*
* ABDK Math 64.64 Smart Contract Library. Copyright Β© 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/**
* @dev Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
* @dev Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << 127 - msb;
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= 63 - (x >> 64);
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= xe;
else x <<= -xe;
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= re;
else if (re < 0) result >>= -re;
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
//
interface INest_3_OfferPrice {
function transfer(address to, uint value) external returns (bool);
/**
* @dev Update and check the latest price
* @param tokenAddress Token address
* @return ethAmount ETH amount
* @return erc20Amount Erc20 amount
* @return blockNum Price block
*/
function updateAndCheckPriceNow(address tokenAddress) external payable returns(uint256 ethAmount, uint256 erc20Amount, uint256 blockNum);
/**
* @dev Update and check the effective price list
* @param tokenAddress Token address
* @param num Number of prices to check
* @return uint256[] price list
*/
function updateAndCheckPriceList(address tokenAddress, uint256 num) external payable returns (uint256[] memory);
// Activate the price checking function
function activation() external;
// Check the minimum ETH cost of obtaining the price
function checkPriceCostLeast(address tokenAddress) external view returns(uint256);
// Check the maximum ETH cost of obtaining the price
function checkPriceCostMost(address tokenAddress) external view returns(uint256);
// Check the cost of a single price data
function checkPriceCostSingle(address tokenAddress) external view returns(uint256);
// Check whether the price-checking functions can be called
function checkUseNestPrice(address target) external view returns (bool);
// Check whether the address is in the blocklist
function checkBlocklist(address add) external view returns(bool);
// Check the amount of NEST to destroy to call prices
function checkDestructionAmount() external view returns(uint256);
// Check the waiting time to start calling prices
function checkEffectTime() external view returns (uint256);
}
//
interface ICoFiXKTable {
function setK0(uint256 tIdx, uint256 sigmaIdx, int128 k0) external;
function setK0InBatch(uint256[] memory tIdxs, uint256[] memory sigmaIdxs, int128[] memory k0s) external;
function getK0(uint256 tIdx, uint256 sigmaIdx) external view returns (int128);
}
//
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
//
interface ICoFiXController {
event NewK(address token, int128 K, int128 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 tIdx, uint256 sigmaIdx, int128 K0);
event NewGovernance(address _new);
event NewOracle(address _priceOracle);
event NewKTable(address _kTable);
event NewTimespan(uint256 _timeSpan);
event NewKRefreshInterval(uint256 _interval);
event NewKLimit(int128 maxK0);
event NewGamma(int128 _gamma);
event NewTheta(address token, uint32 theta);
function addCaller(address caller) external;
function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta);
}
//
interface INest_3_VoteFactory {
// ζ₯θ―’ε°ε
function checkAddress(string calldata name) external view returns (address contractAddress);
// _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.checkAddress("nest.v3.offerPrice")));
}
//
interface ICoFiXERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
// function name() external pure returns (string memory);
// function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
//
interface ICoFiXPair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1);
function mint(address to) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address outToken, address to) external payable returns (uint amountOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
}
//
// Controller contract to call NEST Oracle for prices, managed by governance
// Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract
contract CoFiXController is ICoFiXController {
using SafeMath for uint256;
enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX
uint256 constant public AONE = 1 ether;
uint256 constant public K_BASE = 1E8;
uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy
uint256 constant internal TIMESTAMP_MODULUS = 2**32;
int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point
int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16)
uint256 constant internal K_EXPECTED_VALUE = 0.0025*1E8;
// impact cost params
uint256 constant internal C_BUYIN_ALPHA = 25700000000000; // Ξ±=2.570e-05*1e18
uint256 constant internal C_BUYIN_BETA = 854200000000; // Ξ²=8.542e-07*1e18
uint256 constant internal C_SELLOUT_ALPHA = 117100000000000; // Ξ±=-1.171e-04*1e18
uint256 constant internal C_SELLOUT_BETA = 838600000000; // Ξ²=8.386e-07*1e18
mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta
mapping(address => bool) public callerAllowed;
INest_3_VoteFactory public immutable voteFactory;
// managed by governance
address public governance;
address public immutable nestToken;
address public immutable factory;
address public kTable;
uint256 public timespan = 14;
uint256 public kRefreshInterval = 5 minutes;
uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle
int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16)
int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16)
modifier onlyGovernance() {
require(msg.sender == governance, "CoFiXCtrl: !governance");
_;
}
constructor(address _voteFactory, address _nest, address _factory, address _kTable) public {
governance = msg.sender;
voteFactory = INest_3_VoteFactory(address(_voteFactory));
nestToken = _nest;
factory = _factory;
kTable = _kTable;
}
receive() external payable {}
/* setters for protocol governance */
function setGovernance(address _new) external onlyGovernance {
governance = _new;
emit NewGovernance(_new);
}
function setKTable(address _kTable) external onlyGovernance {
kTable = _kTable;
emit NewKTable(_kTable);
}
function setTimespan(uint256 _timeSpan) external onlyGovernance {
timespan = _timeSpan;
emit NewTimespan(_timeSpan);
}
function setKRefreshInterval(uint256 _interval) external onlyGovernance {
kRefreshInterval = _interval;
emit NewKRefreshInterval(_interval);
}
function setOracleDestructionAmount(uint256 _amount) external onlyGovernance {
DESTRUCTION_AMOUNT = _amount;
}
function setKLimit(int128 maxK0) external onlyGovernance {
MAX_K0 = maxK0;
emit NewKLimit(maxK0);
}
function setGamma(int128 _gamma) external onlyGovernance {
GAMMA = _gamma;
emit NewGamma(_gamma);
}
function setTheta(address token, uint32 theta) external onlyGovernance {
KInfoMap[token][2] = theta;
emit NewTheta(token, theta);
}
// Activate on NEST Oracle, should not be called twice for the same nest oracle
function activate() external onlyGovernance {
// address token, address from, address to, uint value
TransferHelper.safeTransferFrom(nestToken, msg.sender, address(this), DESTRUCTION_AMOUNT);
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
// address token, address to, uint value
TransferHelper.safeApprove(nestToken, oracle, DESTRUCTION_AMOUNT);
INest_3_OfferPrice(oracle).activation(); // nest.transferFrom will be called
TransferHelper.safeApprove(nestToken, oracle, 0); // ensure safety
}
function addCaller(address caller) external override {
require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov");
callerAllowed[caller] = true;
}
// Calc variance of price and K in CoFiX is very expensive
// We use expected value of K based on statistical calculations here to save gas
// In the near future, NEST could provide the variance of price directly. We will adopt it then.
// We can make use of `data` bytes in the future
function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) {
require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
(_ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token);
CoFiX_OP cop = CoFiX_OP(op);
uint256 impactCost;
if (cop == CoFiX_OP.SWAP_WITH_EXACT) {
impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.SWAP_FOR_EXACT) {
impactCost = calcImpactCostFor_SWAP_FOR_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.BURN) {
impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount);
}
return (K_EXPECTED_VALUE.add(impactCost), _ethAmount, _erc20Amount, _blockNum, KInfoMap[token][2]);
}
function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) {
// bytes memory data = abi.encode(msg.sender, outToken, to, liquidity);
(, address outToken, , uint256 liquidity) = abi.decode(data, (address, address, address, uint256));
// calc real vol by liquidity * np
uint256 navps = ICoFiXPair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair
uint256 vol = liquidity.mul(navps).div(NAVPS_BASE);
if (outToken != token) {
// buy in ETH, outToken is ETH
return impactCostForBuyInETH(vol);
}
// sell out liquidity, outToken is token, take this as sell out ETH and get token
return impactCostForSellOutETH(vol);
}
function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountIn is token
// convert to amountIn in ETH
uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount);
return impactCostForBuyInETH(vol);
}
// sell out ETH, amountIn is ETH
return impactCostForSellOutETH(amountIn);
}
function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountOutExact is ETH
return impactCostForBuyInETH(amountOutExact);
}
// sell out ETH, amountIn is ETH, amountOutExact is token
// convert to amountOutExact in ETH
uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount);
return impactCostForSellOutETH(vol);
}
// impact cost
// - C = 0, if VOL < 500
// - C = Ξ± + Ξ² * VOL, if VOL >= 500
// Ξ±=2.570e-05οΌΞ²=8.542e-07
function impactCostForBuyInETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18);
return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10); // combine mul div
}
// Ξ±=-1.171e-04οΌΞ²=8.386e-07
function impactCostForSellOutETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18);
return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10); // combine mul div
}
// // We can make use of `data` bytes in the future
// function queryOracle(address token, bytes memory /*data*/) external override payable returns (uint256 _k, uint256, uint256, uint256, uint256) {
// require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
// uint256 _now = block.timestamp % TIMESTAMP_MODULUS; // 2106
// {
// uint256 _lastUpdate = KInfoMap[token][1];
// if (_now >= _lastUpdate && _now.sub(_lastUpdate) <= kRefreshInterval) { // lastUpdate (2105) | 2106 | now (1)
// return getLatestPrice(token);
// }
// }
// uint256 _balanceBefore = address(this).balance;
// // int128 K0; // K0AndK[0]
// // int128 K; // K0AndK[1]
// int128[2] memory K0AndK;
// // OraclePrice memory _op;
// uint256[7] memory _op;
// int128 _variance;
// // (_variance, _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum) = calcVariance(token);
// (_variance, _op[0], _op[1], _op[2], _op[3]) = calcVariance(token);
// {
// // int128 _volatility = ABDKMath64x64.sqrt(_variance);
// // int128 _sigma = ABDKMath64x64.div(_volatility, ABDKMath64x64.sqrt(ABDKMath64x64.fromUInt(timespan)));
// int128 _sigma = ABDKMath64x64.sqrt(ABDKMath64x64.div(_variance, ABDKMath64x64.fromUInt(timespan))); // combined into one sqrt
// // tIdx is _op[4]
// // sigmaIdx is _op[5]
// _op[4] = (_op[0].add(5)).div(10); // rounding to the nearest
// _op[5] = ABDKMath64x64.toUInt(
// ABDKMath64x64.add(
// ABDKMath64x64.div(_sigma, SIGMA_STEP), // _sigma / 0.0001, e.g. (0.00098/0.0001)=9.799 => 9
// ZERO_POINT_FIVE // e.g. (0.00098/0.0001)+0.5=10.299 => 10
// )
// );
// if (_op[5] > 0) {
// _op[5] = _op[5].sub(1);
// }
// // getK0(uint256 tIdx, uint256 sigmaIdx)
// // K0 is K0AndK[0]
// K0AndK[0] = ICoFiXKTable(kTable).getK0(
// _op[4],
// _op[5]
// );
// // K = gamma * K0
// K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]);
// emit NewK(token, K0AndK[1], _sigma, _op[0], _op[1], _op[2], _op[3], _op[4], _op[5], K0AndK[0]);
// }
// require(K0AndK[0] <= MAX_K0, "CoFiXCtrl: K0");
// {
// // we could decode data in the future to pay the fee change and mining award token directly to reduce call cost
// // TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance)));
// uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
// if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
// _k = ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE)));
// _op[6] = KInfoMap[token][2]; // theta
// KInfoMap[token][0] = uint32(_k); // k < MAX_K << uint32(-1)
// KInfoMap[token][1] = uint32(_now); // 2106
// return (_k, _op[1], _op[2], _op[3], _op[6]);
// }
// }
// function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
// k = KInfoMap[token][0];
// updatedAt = KInfoMap[token][1];
// theta = KInfoMap[token][2];
// }
function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
k = uint32(K_EXPECTED_VALUE);
updatedAt = uint32(block.timestamp);
theta = KInfoMap[token][2];
}
function getLatestPrice(address token) internal returns (uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) {
uint256 _balanceBefore = address(this).balance;
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 1);
require(_rawPriceList.length == 3, "CoFiXCtrl: bad price len");
// validate T
uint256 _T = block.number.sub(_rawPriceList[2]).mul(timespan);
require(_T < 900, "CoFiXCtrl: oralce price outdated");
uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
return (_rawPriceList[0], _rawPriceList[1], _rawPriceList[2]);
// return (K_EXPECTED_VALUE, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2], KInfoMap[token][2]);
}
// calc Variance, a.k.a. sigma squared
function calcVariance(address token) internal returns (
int128 _variance,
uint256 _T,
uint256 _ethAmount,
uint256 _erc20Amount,
uint256 _blockNum
) // keep these variables to make return values more clear
{
address oracle = voteFactory.checkAddress("nest.v3.offerPrice");
// query raw price list from nest oracle (newest to oldest)
uint256[] memory _rawPriceList = INest_3_OfferPrice(oracle).updateAndCheckPriceList{value: msg.value}(token, 50);
require(_rawPriceList.length == 150, "CoFiXCtrl: bad price len");
// calc P a.k.a. price from the raw price data (ethAmount, erc20Amount, blockNum)
uint256[] memory _prices = new uint256[](50);
for (uint256 i = 0; i < 50; i++) {
// 0..50 (newest to oldest), so _prices[0] is p49 (latest price), _prices[49] is p0 (base price)
_prices[i] = calcPrice(_rawPriceList[i*3], _rawPriceList[i*3+1]);
}
// calc x a.k.a. standardized sequence of differences (newest to oldest)
int128[] memory _stdSeq = new int128[](49);
for (uint256 i = 0; i < 49; i++) {
_stdSeq[i] = calcStdSeq(_prices[i], _prices[i+1], _prices[49], _rawPriceList[i*3+2], _rawPriceList[(i+1)*3+2]);
}
// Option 1: calc variance of x
// Option 2: calc mean value first and then calc variance
// Use option 1 for gas saving
int128 _sumSq; // sum of squares of x
int128 _sum; // sum of x
for (uint256 i = 0; i < 49; i++) {
_sumSq = ABDKMath64x64.add(ABDKMath64x64.pow(_stdSeq[i], 2), _sumSq);
_sum = ABDKMath64x64.add(_stdSeq[i], _sum);
}
_variance = ABDKMath64x64.sub(
ABDKMath64x64.div(
_sumSq,
ABDKMath64x64.fromUInt(49)
),
ABDKMath64x64.div(
ABDKMath64x64.pow(_sum, 2),
ABDKMath64x64.fromUInt(49*49)
)
);
_T = block.number.sub(_rawPriceList[2]).mul(timespan);
return (_variance, _T, _rawPriceList[0], _rawPriceList[1], _rawPriceList[2]);
}
function calcPrice(uint256 _ethAmount, uint256 _erc20Amount) internal pure returns (uint256) {
return AONE.mul(_erc20Amount).div(_ethAmount);
}
// diff ratio could be negative
// p2: P_{i}
// p1: P_{i-1}
// p0: P_{0}
function calcDiffRatio(uint256 p2, uint256 p1, uint256 p0) internal pure returns (int128) {
int128 _p2 = ABDKMath64x64.fromUInt(p2);
int128 _p1 = ABDKMath64x64.fromUInt(p1);
int128 _p0 = ABDKMath64x64.fromUInt(p0);
return ABDKMath64x64.div(ABDKMath64x64.sub(_p2, _p1), _p0);
}
// p2: P_{i}
// p1: P_{i-1}
// p0: P_{0}
// bn2: blocknum_{i}
// bn1: blocknum_{i-1}
function calcStdSeq(uint256 p2, uint256 p1, uint256 p0, uint256 bn2, uint256 bn1) internal pure returns (int128) {
return ABDKMath64x64.div(
calcDiffRatio(p2, p1, p0),
ABDKMath64x64.sqrt(
ABDKMath64x64.fromUInt(bn2.sub(bn1)) // c must be larger than d
)
);
}
} | buy in ETH, outToken is ETH, amountIn is token convert to amountIn in ETH | function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256));
if (outToken != token) {
uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount);
return impactCostForBuyInETH(vol);
}
}
| 14,965,902 |
pragma solidity 0.5.10;
contract Context {
constructor () internal { }
function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this;
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(a, b, "SafeMath: subtraction overflow");
}
function SUB97(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 MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV358(a, b, "SafeMath: division by zero");
}
function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD464(a, b, "SafeMath: modulo by zero");
}
function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER927(_MSGSENDER793(), recipient, amount);
return true;
}
function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, amount);
return true;
}
function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER927(sender, recipient, amount);
_APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue));
return true;
}
function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD803(amount);
emit TRANSFER432(sender, recipient, amount);
}
function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD803(amount);
_balances[account] = _balances[account].ADD803(amount);
emit TRANSFER432(address(0), account, amount);
}
function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB97(amount);
emit TRANSFER432(account, address(0), amount);
}
function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
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 APPROVAL431(owner, spender, amount);
}
function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN826(account, amount);
_APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance"));
}
}
library BytesLib {
function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
bytes memory tempBytes;
assembly {
tempBytes := mload(0x40)
let length := mload(_preBytes)
mstore(tempBytes, length)
let mc := add(tempBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
mc := end
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31)
))
}
return tempBytes;
}
function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING
assembly {
let fslot := sload(_preBytes_slot)
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
sstore(
_preBytes_slot,
add(
fslot,
add(
mul(
div(
mload(add(_postBytes, 0x20)),
exp(0x100, sub(32, mlength))
),
exp(0x100, sub(32, newlength))
),
mul(mlength, 2)
)
)
)
}
case 1 {
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + _length), "Slice out of bounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
tempBytes := mload(0x40)
let lengthmod := and(_length, 31)
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
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)
mstore(0x40, and(add(mc, 31), not(31)))
}
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 20), "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 32), "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let length := mload(_preBytes)
switch eq(length, mload(_postBytes))
case 1 {
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
if iszero(eq(mload(mc), mload(cc))) {
success := 0
cb := 0
}
}
}
default {
success := 0
}
}
return success;
}
function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let fslot := sload(_preBytes_slot)
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
switch eq(slength, mlength)
case 1 {
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
success := 0
}
}
default {
let cb := 1
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
success := 0
cb := 0
}
}
}
}
}
default {
success := 0
}
}
return success;
}
function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING
bytes memory tempEmptyStringTest = bytes(_source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
}
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING
uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING
uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING
function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING
if (uint8(_flag[0]) == 0xff) {
return 8;
}
if (uint8(_flag[0]) == 0xfe) {
return 4;
}
if (uint8(_flag[0]) == 0xfd) {
return 2;
}
return 0;
}
function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
bytes memory _newValue = new bytes(_b.length);
for (uint i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 _number;
for (uint i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _start = _b.length.SUB97(_num);
return _b.SLICE479(_start, _num);
}
function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571();
}
function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i ++) {
_remaining = _vin.SLICE479(_offset, _vin.length - _offset);
_len = DETERMINEINPUTLENGTH677(_remaining);
_offset = _offset + _len;
}
_remaining = _vin.SLICE479(_offset, _vin.length - _offset);
_len = DETERMINEINPUTLENGTH677(_remaining);
return _vin.SLICE479(_offset, _len);
}
function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING
return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00");
}
function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4);
}
function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input);
bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence);
return uint32(BYTESTOUINT790(_beSequence));
}
function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen);
}
function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING
bytes memory _varIntTag = _input.SLICE479(36, 1);
uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag);
uint256 _len;
if (_varIntDataLen == 0) {
_len = uint8(_varIntTag[0]);
} else {
_len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen)));
}
return (_varIntDataLen, _len);
}
function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(37, 4);
}
function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input);
bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence);
return uint32(BYTESTOUINT790(_inputeSequence));
}
function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(0, 36);
}
function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return _input.SLICE479(0, 32).TOBYTES32571();
}
function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input));
bytes memory _beId = REVERSEENDIANNESS18(_leId);
return _beId.TOBYTES32571();
}
function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(32, 4);
}
function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leIndex = EXTRACTTXINDEXLE408(_input);
bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex);
return uint32(BYTESTOUINT790(_beIndex));
}
function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint8 _len = uint8(_output.SLICE479(8, 1)[0]);
require(_len < 0xfd, "Multi-byte VarInts not supported");
return _len + 8 + 1;
}
function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i ++) {
_remaining = _vout.SLICE479(_offset, _vout.length - _offset);
_len = DETERMINEOUTPUTLENGTH588(_remaining);
_offset = _offset + _len;
}
_remaining = _vout.SLICE479(_offset, _vout.length - _offset);
_len = DETERMINEOUTPUTLENGTH588(_remaining);
return _vout.SLICE479(_offset, _len);
}
function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _output.SLICE479(8, 1);
}
function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _output.SLICE479(0, 8);
}
function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING
bytes memory _leValue = EXTRACTVALUELE862(_output);
bytes memory _beValue = REVERSEENDIANNESS18(_leValue);
return uint64(BYTESTOUINT790(_beValue));
}
function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) {
return hex"";
}
bytes memory _dataLen = _output.SLICE479(10, 1);
return _output.SLICE479(11, BYTESTOUINT790(_dataLen));
}
function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
if (uint8(_output.SLICE479(9, 1)[0]) == 0) {
uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2;
if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) {
return hex"";
}
return _output.SLICE479(11, _len);
} else {
bytes32 _tag = keccak256(_output.SLICE479(8, 3));
if (_tag == keccak256(hex"1976a9")) {
if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 ||
keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) {
return hex"";
}
return _output.SLICE479(12, 20);
} else if (_tag == keccak256(hex"17a914")) {
if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) {
return hex"";
}
return _output.SLICE479(11, 20);
}
}
return hex"";
}
function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING
uint256 _offset = 1;
uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]);
if (_nIns >= 0xfd || _nIns == 0) {
return false;
}
for (uint8 i = 0; i < _nIns; i++) {
_offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset));
if (_offset > _vin.length) {
return false;
}
}
return _offset == _vin.length;
}
function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING
uint256 _offset = 1;
uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]);
if (_nOuts >= 0xfd || _nOuts == 0) {
return false;
}
for (uint8 i = 0; i < _nOuts; i++) {
_offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset));
if (_offset > _vout.length) {
return false;
}
}
return _offset == _vout.length;
}
function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(36, 32);
}
function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header));
}
function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING
bytes memory _m = _header.SLICE479(72, 3);
uint8 _e = uint8(_header[75]);
uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m));
uint _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return diff1_target719.DIV358(_target);
}
function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(4, 32);
}
function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header));
}
function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(68, 4);
}
function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING
return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header))));
}
function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header));
}
function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return HASH256986(abi.encodePacked(_a, _b));
}
function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (_proof.length % 32 != 0) {
return false;
}
if (_proof.length == 32) {
return true;
}
if (_proof.length == 64) {
return false;
}
uint _idx = _index;
bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571();
bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571();
for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) {
if (_idx % 2 == 1) {
_current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current));
} else {
_current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32));
}
_idx = _idx >> 1;
}
return _current == _root;
}
function RETARGETALGORITHM78( //inject NONSTANDARD NAMING
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) internal pure returns (uint256) {
uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp);
if (_elapsedTime < retarget_period820.DIV358(4)) {
_elapsedTime = retarget_period820.DIV358(4);
}
if (_elapsedTime > retarget_period820.MUL111(4)) {
_elapsedTime = retarget_period820.MUL111(4);
}
uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime);
return _adjusted.DIV358(retarget_period820).MUL111(65536);
}
}
interface FundsInterface {
function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING
function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING
function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING
}
interface SalesInterface {
function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING
function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING
}
interface CollateralInterface {
function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING
function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING
function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING
function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING
}
contract DSMath {
function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x + y) >= x);
}
function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x - y) <= x);
}
function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require(y == 0 || (z = x * y) / y == x);
}
function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING
require(b > 0);
c = a / b;
}
function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
return x <= y ? x : y;
}
function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
return x >= y ? x : y;
}
function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING
return x <= y ? x : y;
}
function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING
return x >= y ? x : y;
}
uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING
uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING
uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING
function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), col735 / 2) / col735;
}
function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), wad510 / 2) / wad510;
}
function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), ray271 / 2) / ray271;
}
function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, col735), y / 2) / y;
}
function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, wad510), y / 2) / y;
}
function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, ray271), y / 2) / y;
}
function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = n % 2 != 0 ? x : ray271;
for (n /= 2; n != 0; n /= 2) {
x = RMUL965(x, x);
if (n % 2 != 0) {
z = RMUL965(z, x);
}
}
}
}
contract Medianizer {
function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING
function READ913() external returns (bytes32); //inject NONSTANDARD NAMING
function POKE561() external; //inject NONSTANDARD NAMING
function POKE561(bytes32) external; //inject NONSTANDARD NAMING
function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING
}
contract Loans is DSMath {
FundsInterface funds;
Medianizer med;
SalesInterface sales;
CollateralInterface col;
uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING
uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING
uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING
uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING
uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING
uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING
uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING
mapping (bytes32 => Loan) public loans;
mapping (bytes32 => PubKeys) public pubKeys;
mapping (bytes32 => SecretHashes) public secretHashes;
mapping (bytes32 => Bools) public bools;
mapping (bytes32 => bytes32) public fundIndex;
mapping (bytes32 => uint256) public repayments;
mapping (address => bytes32[]) public borrowerLoans;
mapping (address => bytes32[]) public lenderLoans;
mapping (address => mapping(uint256 => bool)) public addressToTimestamp;
uint256 public loanIndex;
ERC20 public token;
uint256 public decimals;
address deployer;
struct Loan {
address borrower;
address lender;
address arbiter;
uint256 createdAt;
uint256 loanExpiration;
uint256 requestTimestamp;
uint256 closedTimestamp;
uint256 principal;
uint256 interest;
uint256 penalty;
uint256 fee;
uint256 liquidationRatio;
}
struct PubKeys {
bytes borrowerPubKey;
bytes lenderPubKey;
bytes arbiterPubKey;
}
struct SecretHashes {
bytes32 secretHashA1;
bytes32[3] secretHashAs;
bytes32 secretHashB1;
bytes32[3] secretHashBs;
bytes32 secretHashC1;
bytes32[3] secretHashCs;
bytes32 withdrawSecret;
bytes32 acceptSecret;
bool set;
}
struct Bools {
bool funded;
bool approved;
bool withdrawn;
bool sale;
bool paid;
bool off;
}
event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING
event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING
event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING
event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING
event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING
event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING
event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING
event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING
event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING
event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING
function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].borrower;
}
function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].lender;
}
function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].arbiter;
}
function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].createdAt, approve_exp_threshold840);
}
function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].loanExpiration, accept_exp_threshold947);
}
function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443);
}
function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699);
}
function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].principal;
}
function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].interest;
}
function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].fee;
}
function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].penalty;
}
function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return col.COLLATERAL382(loan);
}
function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.REFUNDABLECOLLATERAL879(loan);
}
function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.SEIZABLECOLLATERAL368(loan);
}
function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.TEMPORARYREFUNDABLECOLLATERAL760(loan);
}
function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.TEMPORARYSEIZABLECOLLATERAL228(loan);
}
function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return repayments[loan];
}
function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].liquidationRatio;
}
function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(PRINCIPAL566(loan), INTEREST523(loan));
}
function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(OWEDTOLENDER7(loan), FEE426(loan));
}
function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan));
}
function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(OWEDFORLOAN262(loan), REPAID307(loan));
}
function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].funded;
}
function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].approved;
}
function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].withdrawn;
}
function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].sale;
}
function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].paid;
}
function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].off;
}
function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING
return MUL111(x, (10 ** SUB97(18, decimals)));
}
function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING
return DIV358(x, (10 ** SUB97(18, decimals)));
}
function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING
return borrowerLoans[borrower_].length;
}
function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING
return lenderLoans[lender_].length;
}
function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
(bytes32 val, bool set) = med.PEEK685();
require(set, "Loans.minSeizableCollateral: Medianizer must be set");
uint256 price = uint(val);
return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735));
}
function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
(bytes32 val, bool set) = med.PEEK685();
require(set, "Loans.collateralValue: Medianizer must be set");
uint256 price = uint(val);
return CMUL87(price, COLLATERAL382(loan));
}
function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan));
}
function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317);
}
function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan);
}
constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public {
require(address(funds_) != address(0), "Funds address must be non-zero");
require(address(med_) != address(0), "Medianizer address must be non-zero");
require(address(token_) != address(0), "Token address must be non-zero");
deployer = msg.sender;
funds = funds_;
med = med_;
token = token_;
decimals = decimals_;
require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed");
}
function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this");
require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set");
require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero");
sales = sales_;
}
function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this");
require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set");
require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero");
col = col_;
}
function CREATE943( //inject NONSTANDARD NAMING
uint256 loanExpiration_,
address[3] calldata usrs_,
uint256[7] calldata vals_,
bytes32 fund
) external returns (bytes32 loan) {
if (fund != bytes32(0)) {
require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args");
}
require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed");
require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`");
require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero");
require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero");
require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero");
loanIndex = ADD803(loanIndex, 1);
loan = bytes32(loanIndex);
loans[loan].createdAt = now;
loans[loan].loanExpiration = loanExpiration_;
loans[loan].borrower = usrs_[0];
loans[loan].lender = usrs_[1];
loans[loan].arbiter = usrs_[2];
loans[loan].principal = vals_[0];
loans[loan].interest = vals_[1];
loans[loan].penalty = vals_[2];
loans[loan].fee = vals_[3];
uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan);
col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol);
loans[loan].liquidationRatio = vals_[5];
loans[loan].requestTimestamp = vals_[6];
fundIndex[loan] = fund;
secretHashes[loan].set = false;
borrowerLoans[usrs_[0]].push(bytes32(loanIndex));
lenderLoans[usrs_[1]].push(bytes32(loanIndex));
addressToTimestamp[usrs_[0]][vals_[6]] = true;
emit CREATE22(loan);
}
function SETSECRETHASHES742( //inject NONSTANDARD NAMING
bytes32 loan,
bytes32[4] calldata borrowerSecretHashes,
bytes32[4] calldata lenderSecretHashes,
bytes32[4] calldata arbiterSecretHashes,
bytes calldata borrowerPubKey_,
bytes calldata lenderPubKey_,
bytes calldata arbiterPubKey_
) external {
require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set");
require(
msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds),
"Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address"
);
secretHashes[loan].secretHashA1 = borrowerSecretHashes[0];
secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ];
secretHashes[loan].secretHashB1 = lenderSecretHashes[0];
secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ];
secretHashes[loan].secretHashC1 = arbiterSecretHashes[0];
secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ];
pubKeys[loan].borrowerPubKey = borrowerPubKey_;
pubKeys[loan].lenderPubKey = lenderPubKey_;
pubKeys[loan].arbiterPubKey = arbiterPubKey_;
secretHashes[loan].set = true;
}
function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING
require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set");
require(bools[loan].funded == false, "Loans.fund: Loan is already funded");
bools[loan].funded = true;
require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens");
emit FUNDLOAN50(loan);
}
function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING
require(bools[loan].funded == true, "Loans.approve: Loan must be funded");
require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan");
require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline");
bools[loan].approved = true;
emit APPROVE490(loan);
}
function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive");
require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded");
require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved");
require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn");
require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match");
bools[loan].withdrawn = true;
require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens");
secretHashes[loan].withdrawSecret = secretA1;
if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);}
emit WITHDRAW160(loan, secretA1);
}
function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.repay: Loan cannot be inactive");
require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation");
require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn");
require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired");
require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount");
require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens");
repayments[loan] = ADD803(amount, repayments[loan]);
if (REPAID307(loan) == OWEDFORLOAN262(loan)) {
bools[loan].paid = true;
if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);}
}
emit REPAY404(loan, amount);
}
function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.refund: Loan cannot be inactive");
require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation");
require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration");
require(bools[loan].paid == true, "Loans.refund: The loan must be repaid");
require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund");
bools[loan].off = true;
loans[loan].closedTimestamp = now;
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
funds.CALCGLOBALINTEREST773();
}
require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens");
emit REFUND289(loan);
}
function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING
ACCEPT922(loan, secret);
emit CANCEL833(loan, secret);
}
function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.cancel: Loan must not be inactive");
require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn");
require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached");
require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation");
CLOSE691(loan);
emit CANCEL833(loan, bytes32(0));
}
function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.accept: Loan must not be inactive");
require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid");
require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter");
require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past");
require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation");
require(
sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1,
"Loans.accept: Invalid secret"
);
secretHashes[loan].acceptSecret = secret;
CLOSE691(loan);
emit ACCEPT489(loan, secret);
}
function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING
bools[loan].off = true;
loans[loan].closedTimestamp = now;
if (bools[loan].withdrawn == false) {
if (fundIndex[loan] == bytes32(0)) {
require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender");
} else {
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
}
funds.DEPOSIT909(fundIndex[loan], loans[loan].principal);
}
}
else {
if (fundIndex[loan] == bytes32(0)) {
require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender");
} else {
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
}
funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan));
}
require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter");
}
}
function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive");
require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn");
require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party");
require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero");
if (sales.NEXT199(loan) == 0) {
if (now > loans[loan].loanExpiration) {
require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid");
} else {
require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio");
}
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
funds.CALCGLOBALINTEREST773();
}
} else {
require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached");
require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted");
require(
now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)),
"Loans.liquidate: Previous liquidation settlement expiration hasn't expired"
);
}
require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate");
require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed");
SecretHashes storage h = secretHashes[loan];
uint256 i = sales.NEXT199(loan);
sale_ = sales.CREATE943(
loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender,
h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash
);
if (bools[loan].sale == false) {
bools[loan].sale = true;
require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed");
}
if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);}
emit LIQUIDATE130(loan, secretHash, pubKeyHash);
}
}
interface CTokenInterface {
function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING
function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING
function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING
function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING
function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING
function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING
function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING
function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING
function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
interface CERC20Interface {
function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING
function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING
function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING
function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING
}
interface ERC20Interface {
function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
interface TrollerInterface {
function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING
function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING
function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING
function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING
}
contract Helpers is DSMath {
address public comptroller;
function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING
return comptroller;
}
function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING
TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117());
address[] memory markets = troller.GETASSETSIN764(address(this));
bool isEntered = false;
for (uint i = 0; i < markets.length; i++) {
if (markets[i] == cErc20) {
isEntered = true;
}
}
if (!isEntered) {
address[] memory toEnter = new address[](1);
toEnter[0] = cErc20;
troller.ENTERMARKETS395(toEnter);
}
}
function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING
ERC20Interface erc20Contract = ERC20Interface(erc20);
uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to);
if (srcAmt > tokenAllowance) {
erc20Contract.APPROVE357(to, 2**255);
}
}
}
contract ALCompound is Helpers {
function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING
ENTERMARKET780(cErc20);
ERC20Interface token = ERC20Interface(erc20);
uint toDeposit = token.BALANCEOF227(address(this));
if (toDeposit > tokenAmt) {
toDeposit = tokenAmt;
}
CERC20Interface cToken = CERC20Interface(cErc20);
SETAPPROVAL391(erc20, toDeposit, cErc20);
assert(cToken.MINT386(toDeposit) == 0);
}
function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken = CTokenInterface(cErc20);
SETAPPROVAL391(cErc20, 10**50, cErc20);
uint toBurn = cToken.BALANCEOF227(address(this));
uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666());
if (tokenToReturn > tokenAmt) {
tokenToReturn = tokenAmt;
}
require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong");
}
function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken = CTokenInterface(cErc20);
uint toBurn = cToken.BALANCEOF227(address(this));
if (toBurn > cTokenAmt) {
toBurn = cTokenAmt;
}
SETAPPROVAL391(cErc20, toBurn, cErc20);
require(cToken.REDEEM46(toBurn) == 0, "something went wrong");
}
}
contract Funds is DSMath, ALCompound {
Loans loans;
uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING
uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING
uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING
uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING
uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING
uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING
uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING
uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING
mapping (address => bytes32[]) public secretHashes;
mapping (address => uint256) public secretHashIndex;
mapping (address => bytes) public pubKeys;
mapping (bytes32 => Fund) public funds;
mapping (address => bytes32) public fundOwner;
mapping (bytes32 => Bools) public bools;
uint256 public fundIndex;
uint256 public lastGlobalInterestUpdated;
uint256 public tokenMarketLiquidity;
uint256 public cTokenMarketLiquidity;
uint256 public marketLiquidity;
uint256 public totalBorrow;
uint256 public globalInterestRateNumerator;
uint256 public lastUtilizationRatio;
uint256 public globalInterestRate;
uint256 public maxUtilizationDelta;
uint256 public utilizationInterestDivisor;
uint256 public maxInterestRateNumerator;
uint256 public minInterestRateNumerator;
uint256 public interestUpdateDelay;
uint256 public defaultArbiterFee;
ERC20 public token;
uint256 public decimals;
CTokenInterface public cToken;
bool compoundSet;
address deployer;
struct Fund {
address lender;
uint256 minLoanAmt;
uint256 maxLoanAmt;
uint256 minLoanDur;
uint256 maxLoanDur;
uint256 fundExpiry;
uint256 interest;
uint256 penalty;
uint256 fee;
uint256 liquidationRatio;
address arbiter;
uint256 balance;
uint256 cBalance;
}
struct Bools {
bool custom;
bool compoundEnabled;
}
event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING
event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING
event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING
event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING
event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING
event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING
event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING
constructor(
ERC20 token_,
uint256 decimals_
) public {
require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero");
require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero");
deployer = msg.sender;
token = token_;
decimals = decimals_;
utilizationInterestDivisor = 10531702972595856680093239305;
maxUtilizationDelta = 95310179948351216961192521;
globalInterestRateNumerator = 95310179948351216961192521;
maxInterestRateNumerator = 182321557320989604265864303;
minInterestRateNumerator = 24692612600038629323181834;
interestUpdateDelay = 86400;
defaultArbiterFee = 1000000000236936036262880196;
globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521));
}
function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this");
require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set");
require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero");
loans = loans_;
require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved");
}
function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending");
require(!compoundSet, "Funds.setCompound: Compound address has already been set");
require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero");
require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero");
cToken = cToken_;
comptroller = comptroller_;
compoundSet = true;
}
function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this");
require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero");
utilizationInterestDivisor = utilizationInterestDivisor_;
}
function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this");
require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero");
maxUtilizationDelta = maxUtilizationDelta_;
}
function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this");
require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero");
globalInterestRateNumerator = globalInterestRateNumerator_;
}
function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this");
require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero");
globalInterestRate = globalInterestRate_;
}
function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this");
require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero");
maxInterestRateNumerator = maxInterestRateNumerator_;
}
function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this");
require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero");
minInterestRateNumerator = minInterestRateNumerator_;
}
function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this");
require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero");
interestUpdateDelay = interestUpdateDelay_;
}
function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this");
require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%");
defaultArbiterFee = defaultArbiterFee_;
}
function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING
return funds[fund].lender;
}
function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].minLoanAmt;}
else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));}
}
function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].maxLoanAmt;}
else {return default_max_loan_amt507;}
}
function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].minLoanDur;}
else {return default_min_loan_dur981;}
}
function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
return funds[fund].maxLoanDur;
}
function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
return funds[fund].fundExpiry;
}
function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].interest;}
else {return globalInterestRate;}
}
function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].penalty;}
else {return default_liquidation_penalty756;}
}
function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].fee;}
else {return defaultArbiterFee;}
}
function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].liquidationRatio;}
else {return default_liquidation_ratio475;}
}
function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING
return funds[fund].arbiter;
}
function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].compoundEnabled) {
return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666());
} else {
return funds[fund].balance;
}
}
function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING
if (compoundSet) {
return cToken.EXCHANGERATECURRENT666();
} else {
return 0;
}
}
function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[fund].custom;
}
function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING
return secretHashes[addr_].length;
}
function CREATE943( //inject NONSTANDARD NAMING
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address");
require(
ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66,
"Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years"
);
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");}
fundIndex = ADD803(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false);
funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true);
funds[fund].arbiter = arbiter_;
bools[fund].custom = false;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {DEPOSIT909(fund, amount_);}
emit CREATE22(fund);
}
function CREATECUSTOM959( //inject NONSTANDARD NAMING
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 liquidationRatio_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address");
require(
ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66,
"Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years"
);
require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur");
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");}
fundIndex = ADD803(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false);
funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true);
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
funds[fund].arbiter = arbiter_;
bools[fund].custom = true;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {DEPOSIT909(fund, amount_);}
emit CREATE22(fund);
}
function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING
require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens");
if (bools[fund].compoundEnabled) {
MINTCTOKEN703(address(token), address(cToken), amount_);
uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666());
funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd);
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);}
} else {
funds[fund].balance = ADD803(funds[fund].balance, amount_);
if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();}
emit DEPOSIT856(fund, amount_);
}
function UPDATE438( //inject NONSTANDARD NAMING
bytes32 fund,
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_
) public {
require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund");
require(
ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66,
"Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years"
);
funds[fund].maxLoanDur = maxLoanDur_;
funds[fund].fundExpiry = fundExpiry_;
funds[fund].arbiter = arbiter_;
emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_);
}
function UPDATECUSTOM705( //inject NONSTANDARD NAMING
bytes32 fund,
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
uint256 liquidationRatio_,
address arbiter_
) external {
require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund");
require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur");
UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_);
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
}
function REQUEST711( //inject NONSTANDARD NAMING
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_,
bytes32[8] calldata secretHashes_,
bytes calldata pubKeyA_,
bytes calldata pubKeyB_
) external returns (bytes32 loanIndex) {
require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request");
require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance");
require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt");
require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt");
require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur");
require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry");
require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero");
require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero");
require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero");
require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero");
require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero");
loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_);
LOANUPDATEMARKETLIQUIDITY912(fund, amount_);
loans.FUND172(loanIndex);
emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
}
function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING
WITHDRAWTO298(fund, amount_, msg.sender);
}
function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING
require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens");
require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance");
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
REDEEMUNDERLYING614(address(cToken), amount_);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove);
require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = SUB97(funds[fund].balance, amount_);
require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();}
emit WITHDRAW160(fund, amount_, recipient_);
}
function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING
for (uint i = 0; i < secretHashes_.length; i++) {
secretHashes[msg.sender].push(secretHashes_[i]);
}
}
function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING
pubKeys[msg.sender] = pubKey_;
}
function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING
require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured");
require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled");
require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound");
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
MINTCTOKEN703(address(token), address(cToken), funds[fund].balance);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore);
tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance);
cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn);
bools[fund].compoundEnabled = true;
funds[fund].balance = 0;
funds[fund].cBalance = cTokenToReturn;
emit ENABLECOMPOUND170(fund);
}
function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING
require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled");
require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound");
uint256 balanceBefore = token.BALANCEOF227(address(this));
REDEEMCTOKEN224(address(cToken), funds[fund].cBalance);
uint256 balanceAfter = token.BALANCEOF227(address(this));
uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore);
tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn);
cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance);
bools[fund].compoundEnabled = false;
funds[fund].cBalance = 0;
funds[fund].balance = tokenToReturn;
emit DISABLECOMPOUND118(fund);
}
function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING
require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this");
totalBorrow = SUB97(totalBorrow, amount_);
}
function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING
marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725()));
if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) {
uint256 utilizationRatio;
if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));}
if (utilizationRatio > lastUtilizationRatio) {
uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio);
globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
} else {
uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio);
globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
}
globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521));
lastGlobalInterestUpdated = now;
lastUtilizationRatio = utilizationRatio;
}
}
function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_);
}
function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING
if (value == 0) {
if (addNow) {
return now + max_loan_length66;
}
return max_loan_length66;
}
return value;
}
function CREATELOAN338( //inject NONSTANDARD NAMING
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_
) private returns (bytes32 loanIndex) {
loanIndex = loans.CREATE943(
now + loanDur_,
[borrower_, LENDER92(fund), funds[fund].arbiter],
[
amount_,
CALCINTEREST818(amount_, INTEREST523(fund), loanDur_),
CALCINTEREST818(amount_, PENALTY434(fund), loanDur_),
CALCINTEREST818(amount_, FEE426(fund), loanDur_),
collateral_,
LIQUIDATIONRATIO684(fund),
requestTimestamp_
],
fund
);
}
function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING
bytes32 fund,
bytes32 loan,
bytes32[8] memory secretHashes_,
bytes memory pubKeyA_,
bytes memory pubKeyB_
) private {
loans.SETSECRETHASHES742(
loan,
[ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ],
[ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ],
GETSECRETHASHESFORLOAN447(ARBITER4(fund)),
pubKeyA_,
pubKeyB_,
pubKeys[ARBITER4(fund)]
);
}
function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
REDEEMUNDERLYING614(address(cToken), amount_);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove);
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = SUB97(funds[fund].balance, amount_);
if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {
totalBorrow = ADD803(totalBorrow, amount_);
CALCGLOBALINTEREST773();
}
}
function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING
secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4);
require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated");
return [
secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)]
];
}
} | inject NONSTANDARD NAMING | function REFUND497(bytes32 loan) external { | 1,784,199 |
pragma solidity ^0.4.24;
// File: contracts/upgradeability/ImplementationStorage.sol
/**
* @title ImplementationStorage
* @dev This contract stores proxy implementation address.
*/
contract ImplementationStorage {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "cvc.proxy.implementation", and is validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0xa490aab0d89837371982f93f57ffd20c47991f88066ef92475bc8233036969bb;
/**
* @dev Constructor
*/
constructor() public {
assert(IMPLEMENTATION_SLOT == keccak256("cvc.proxy.implementation"));
}
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function implementation() public view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
}
// 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: contracts/upgradeability/CvcProxy.sol
/**
* @title CvcProxy
* @dev Transparent proxy with upgradeability functions and authorization control.
*/
contract CvcProxy is ImplementationStorage {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address implementation);
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "cvc.proxy.admin", and is validated in the constructor.
*/
bytes32 private constant ADMIN_SLOT = 0x2bbac3e52eee27be250d682577104e2abe776c40160cd3167b24633933100433;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* It executes the function if called by admin. Otherwise, it will delegate the call to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == currentAdmin()) {
_;
} else {
delegate(implementation());
}
}
/**
* Contract constructor.
* It sets the `msg.sender` as the proxy admin.
*/
constructor() public {
assert(ADMIN_SLOT == keccak256("cvc.proxy.admin"));
setAdmin(msg.sender);
}
/**
* @dev Fallback function.
*/
function() external payable {
require(msg.sender != currentAdmin(), "Message sender is not contract admin");
delegate(implementation());
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param _newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address _newAdmin) external ifAdmin {
require(_newAdmin != address(0), "Cannot change contract admin to zero address");
emit AdminChanged(currentAdmin(), _newAdmin);
setAdmin(_newAdmin);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param _implementation the address of the new implementation to be set.
*/
function upgradeTo(address _implementation) external ifAdmin {
upgradeImplementation(_implementation);
}
/**
* @dev Allows the proxy owner to upgrade and call the new implementation
* to initialize whatever is needed through a low level call.
* @param _implementation the address of the new implementation to be set.
* @param _data the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload.
*/
function upgradeToAndCall(address _implementation, bytes _data) external payable ifAdmin {
upgradeImplementation(_implementation);
//solium-disable-next-line security/no-call-value
require(address(this).call.value(msg.value)(_data), "Upgrade error: initialization method call failed");
}
/**
* @dev Returns the Address of the proxy admin.
* @return address
*/
function admin() external view ifAdmin returns (address) {
return currentAdmin();
}
/**
* @dev Upgrades the implementation address.
* @param _newImplementation the address of the new implementation to be set
*/
function upgradeImplementation(address _newImplementation) private {
address currentImplementation = implementation();
require(currentImplementation != _newImplementation, "Upgrade error: proxy contract already uses specified implementation");
setImplementation(_newImplementation);
emit Upgraded(_newImplementation);
}
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param _implementation Address to delegate.
*/
function delegate(address _implementation) private {
assembly {
// Copy msg.data.
calldatacopy(0, 0, calldatasize)
// Call current implementation passing proxy calldata.
let result := delegatecall(gas, _implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
// Propagate result (delegatecall returns 0 on error).
switch result
case 0 {revert(0, returndatasize)}
default {return (0, returndatasize)}
}
}
/**
* @return The admin slot.
*/
function currentAdmin() private view returns (address proxyAdmin) {
bytes32 slot = ADMIN_SLOT;
assembly {
proxyAdmin := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param _newAdmin Address of the new proxy admin.
*/
function setAdmin(address _newAdmin) private {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, _newAdmin)
}
}
/**
* @dev Sets the implementation address of the proxy.
* @param _newImplementation Address of the new implementation.
*/
function setImplementation(address _newImplementation) private {
require(
AddressUtils.isContract(_newImplementation),
"Cannot set new implementation: no contract code at contract address"
);
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, _newImplementation)
}
}
}
// 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.
*/
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/upgradeability/CvcMigrator.sol
/**
* @title CvcMigrator
* @dev This is a system contract which provides transactional upgrade functionality.
* It allows the ability to add 'upgrade transactions' for multiple proxy contracts and execute all of them in single transaction.
*/
contract CvcMigrator is Ownable {
/**
* @dev The ProxyCreated event is emitted when new instance of CvcProxy contract is deployed.
* @param proxyAddress New proxy contract instance address.
*/
event ProxyCreated(address indexed proxyAddress);
struct Migration {
address proxy;
address implementation;
bytes data;
}
/// List of registered upgrades.
Migration[] public migrations;
/**
* @dev Store migration record for the next migration
* @param _proxy Proxy address
* @param _implementation Implementation address
* @param _data Pass-through to proxy's updateToAndCall
*/
function addUpgrade(address _proxy, address _implementation, bytes _data) external onlyOwner {
require(AddressUtils.isContract(_implementation), "Migrator error: no contract code at new implementation address");
require(CvcProxy(_proxy).implementation() != _implementation, "Migrator error: proxy contract already uses specified implementation");
migrations.push(Migration(_proxy, _implementation, _data));
}
/**
* @dev Applies stored upgrades to proxies. Flushes the list of migration records
*/
function migrate() external onlyOwner {
for (uint256 i = 0; i < migrations.length; i++) {
Migration storage migration = migrations[i];
if (migration.data.length > 0) {
CvcProxy(migration.proxy).upgradeToAndCall(migration.implementation, migration.data);
} else {
CvcProxy(migration.proxy).upgradeTo(migration.implementation);
}
}
delete migrations;
}
/**
* @dev Flushes the migration list without applying them. Can be used in case wrong migration added to the list.
*/
function reset() external onlyOwner {
delete migrations;
}
/**
* @dev Transfers ownership from the migrator to a new address
* @param _target Proxy address
* @param _newOwner New proxy owner address
*/
function changeProxyAdmin(address _target, address _newOwner) external onlyOwner {
CvcProxy(_target).changeAdmin(_newOwner);
}
/**
* @dev Proxy factory
* @return CvcProxy
*/
function createProxy() external onlyOwner returns (CvcProxy) {
CvcProxy proxy = new CvcProxy();
// We emit event here to retrieve contract address later in the tx receipt
emit ProxyCreated(address(proxy));
return proxy;
}
/**
* @dev Returns migration record by index. Will become obsolete as soon as migrations() will be usable via web3.js
* @param _index 0-based index
* @return address Proxy address
* @return address Implementation address
* @return bytes Pass-through to proxy's updateToAndCall
*/
function getMigration(uint256 _index) external view returns (address, address, bytes) {
return (migrations[_index].proxy, migrations[_index].implementation, migrations[_index].data);
}
/**
* @dev Returns current stored migration count
* @return uint256 Count
*/
function getMigrationCount() external view returns (uint256) {
return migrations.length;
}
} | Returns current stored migration count return uint256 Count/ | function getMigrationCount() external view returns (uint256) {
return migrations.length;
}
| 5,903,380 |
./full_match/1/0x2fC246149B4B8d7bcEF6188A10AF1791380227f1/sources/src/BaseWithStorage/ERC20Group.sol | mint more tokens of a specific subToken . to address receiving the tokens. id subToken id (also the index at which it was added). amount of token minted. | function mint(
address to,
uint256 id,
uint256 amount
) external {
require(_minters[msg.sender], "NOT_AUTHORIZED_MINTER");
(uint256 bin, uint256 index) = id.getTokenBinIndex();
mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to];
toPack[bin] = toPack[bin].updateTokenBalance(index, amount, ObjectLib32.Operations.ADD);
_packedSupplies[bin] = _packedSupplies[bin].updateTokenBalance(index, amount, ObjectLib32.Operations.ADD);
_erc20s[id].emitTransferEvent(address(0), to, amount);
}
| 8,434,504 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.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);
function decimals() external view returns (uint8);
/**
* @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: @openzeppelin/contracts/math/SafeMath.sol
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
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/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @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");
}
}
}
// 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: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.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.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _owner;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Treasury.sol
pragma solidity ^0.6.6;
// Treasury Furnace is a simple vault for all the withdrawal fees sent to it and is a furnace for STBZ tokens
// When a user wants to take from the Treasury, they will simply have to burn their STBZ tokens into the treasury
// And they will redeem the percentage compared to the circulating number of STBZ tokens (total - operator - treasury)
// STBZ tokens stored in the treasury are effectively burned and cannot be redeemed again
// If this treasury is replaced in the future, future contracts will need to account for the burned tokens in this contract
contract StabilizeTreasuryFurnace is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// variables
address public stbzAddress; // The address for the STBZ tokens
address public operatorAddress; // The address for the operator contract
IERC20 private _stabilizeT; // Instance of stabilize token
address[] private activeTokens; // A list of all the acceptable reward tokens to this treasury
address[] public furnaceList; // A list of all the furnaces used previously
// Events
event TreasuryBurn(address indexed user, uint256 amount);
constructor(
address _stbz,
address _operator
) public {
stbzAddress = _stbz;
operatorAddress = _operator;
_stabilizeT = IERC20(stbzAddress);
initialTokens();
initialFurnaces();
}
// Initial operations
function initialTokens() internal {
// Testnet
/*
activeTokens.push(address(0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD)); // DAI
activeTokens.push(address(0xe22da380ee6B445bb8273C81944ADEB6E8450422)); // USDC
activeTokens.push(address(0x13512979ADE267AB5100878E2e0f485B568328a4)); // USDT
activeTokens.push(address(0xD868790F57B39C9B2B51b12de046975f986675f9)); // sUSD
*/
// Mainnet
activeTokens.push(address(0x6B175474E89094C44Da98b954EedeAC495271d0F)); // DAI
activeTokens.push(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)); // USDC
activeTokens.push(address(0xdAC17F958D2ee523a2206206994597C13D831ec7)); // USDT
activeTokens.push(address(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51)); // sUSD
}
function initialFurnaces() internal {
// Testnet
//furnaceList.push(address(0x0B5F5ECeA3835a5C5f6F528353fae50c75B60c3e)); // Treasury #1
//furnaceList.push(address(0x81C878E0B9261622192183415969a00dA12685ef)); // Treasury #2
// Mainnet
// None yet
}
// functions
function circulatingSupply() public view returns (uint256) {
if(_stabilizeT.totalSupply() == 0){
return 0;
}else{
// Circulating supply is total supply minus operator contract minus treasury account
uint256 total = _stabilizeT.totalSupply().sub(_stabilizeT.balanceOf(operatorAddress)).sub(_stabilizeT.balanceOf(address(this)));
// Now factor in all previous furnaces
if(furnaceList.length > 0){
for(uint256 i = 0; i < furnaceList.length; i++){
total = total.sub(_stabilizeT.balanceOf(furnaceList[i]));
}
}
return total;
}
}
function totalTokens() external view returns (uint256) {
return activeTokens.length;
}
function getTokenAddress(uint256 _pos) external view returns (address) {
return activeTokens[_pos];
}
function getTokenBalance(uint256 _pos) external view returns (uint256) {
IERC20 token = IERC20(activeTokens[_pos]);
return token.balanceOf(address(this));
}
function claim(uint256 amount) external {
require(amount > 0, "Cannot claim with 0 amount");
require(activeTokens.length > 0, "There are no redeemable tokens in the treasury");
uint256 supply = circulatingSupply(); // Get the current circulating supply before burning this token into treasury
require(supply > 0, "There are no circulating tokens");
_stabilizeT.safeTransferFrom(_msgSender(), address(this), amount);
// Now process the treasury funds for each token
uint256 i = 0;
uint256 transferAmount = 0;
for(i = 0; i < activeTokens.length; i++){
IERC20 token = IERC20(activeTokens[i]);
transferAmount = amount.mul(token.balanceOf(address(this))).div(supply);
if(transferAmount > 0){
token.safeTransfer(_msgSender(), transferAmount);
}
}
emit TreasuryBurn(_msgSender(), amount);
}
// Governance only functions
// Timelock variables
// Timelock doesn't activate until someone has burned tokens to this address
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant _timelockDuration = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(_stabilizeT.balanceOf(address(this)) > 0){
// Timelock is only required after tokens burned into contract
require(now >= _timelockStart + _timelockDuration, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Add a new token to the treasury
// --------------------
function startAddNewToken(address _address) external onlyGovernance {
// Prevent the possibility of adding the burnt tokens as rewards
require(_address != stbzAddress, "Cannot add token that is the same as the burnt tokens");
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishAddNewToken() public onlyGovernance timelockConditionsMet(2) {
// This adds a new tokens
activeTokens.push(_timelock_address);
}
// --------------------
// Select a token to remove from treasury discovery
// --------------------
function startRemoveToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishRemoveToken() external onlyGovernance timelockConditionsMet(3) {
uint256 length = activeTokens.length;
for(uint256 i = 0; i < length; i++){
if(activeTokens[i] == _timelock_address){
// Move all the remaining elements down one
for(uint256 i2 = i; i2 < length-1; i2++){
activeTokens[i2] = activeTokens[i2 + 1]; // Shift the data down one
}
activeTokens.pop(); //Remove last element
break;
}
}
}
// --------------------
// Add a new furnace to treasury
// --------------------
function startAddNewFurnace(address _address) external onlyGovernance {
// Prevent the possibility of adding the burnt tokens as rewards
require(_address != stbzAddress, "Cannot add STBZ address as a furnace");
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishAddNewFurnace() public onlyGovernance timelockConditionsMet(4) {
// This adds a new furnace
furnaceList.push(_timelock_address);
}
// --------------------
} | Move all the remaining elements down one | function finishRemoveToken() external onlyGovernance timelockConditionsMet(3) {
uint256 length = activeTokens.length;
for(uint256 i = 0; i < length; i++){
if(activeTokens[i] == _timelock_address){
for(uint256 i2 = i; i2 < length-1; i2++){
}
break;
}
}
}
| 10,720,027 |
pragma solidity >=0.4.22 < 0.4.25;
pragma experimental ABIEncoderV2;
/**
* @title MetadataRegistry
* @author Cory Dickson (@gh1dra)
* @dev On-chain registry that stores IPFS (multihash) hash for contract addresses. A multihash entry is in the format
* of <varint hash function code><varint digest size in bytes><hash function output>
* See https://github.com/multiformats/multihash
*
* Currently IPFS hash is 34 bytes long with first two segments represented as a single byte (uint8)
* The digest is 32 bytes long and can be stored using bytes32 efficiently.
*
* Only deployment keys can set an initial entry for a contract. From that point on,
* they can delegate that ability to another address. Delegates then become sole owners
* of publishing permissions for specified contract in the registry.
* Inspired by: https://github.com/saurfang/ipfs-multihash-on-solidity
*/
contract MetadataRegistry {
// The hash of the string calculated by keccak256('deployer')
bytes32 constant DEPLOYER_CATEGORY = 0xdbe2b933bb7d57444cdba9c71b5ceb79b60dc455ad691d856e6e4025cf542caa;
address constant ANY_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
struct Entry {
bool selfAttested;
address delegate;
bytes32 digest;
uint8 hashFunction;
uint8 size;
}
mapping (address => mapping (bytes32 => Entry)) private entries;
mapping (address => mapping (bytes32 => uint)) private versions;
mapping (address => mapping(bytes32 => bool)) private approvedCategories;
mapping (address => address) private deployers;
event EntrySet (
address indexed contractAddress,
address indexed delegate,
bytes32 digest,
uint8 hashFunction,
uint8 size
);
event EntryDeleted (
address indexed contractAddress,
uint latest
);
event SetDelegate (
address indexed contractAddress,
address indexed delegate
);
event CategoryAdded (
address indexed contractAddress,
bytes32 indexed category,
address delegate
);
event CategoryDeleted (
address indexed contractAddress,
bytes32 indexed category
);
modifier onlyDelegate(address _contract, bytes32 _categoryID) {
address _delegate = entries[_contract][_categoryID].delegate;
if (msg.sender != _contract) {
if (_delegate != ANY_ADDRESS && _delegate != address(0x0)) {
require(msg.sender == entries[_contract][_categoryID].delegate, "Error: msg.sender is not a delegate");
}
}
_;
}
modifier onlyDeployer(address _contract, bool _create2, int _nonce, bytes32 _salt, bytes memory _code) {
require(entries[_contract][DEPLOYER_CATEGORY].delegate == address(0), "Error: contract entry has already been initialized");
if (_contract != msg.sender) {
address _res = address(0);
if (_create2) {
_res = calculateCreate2Addr(msg.sender, _salt, _code);
} else {
require(_nonce > 0, "Error: invalid nonce provided");
_res = addressFrom(msg.sender, _nonce);
}
require(_res == _contract, "Error: msg.sender must be the deployment key");
deployers[_contract] = msg.sender;
}
_;
}
/**
* @dev Initialize association of a multihash with a contract if the deployer sends a tx
* @param _contract address of the associated contract
* @param _digest hash digest produced by hashing content using hash function
* @param _hashFunction hashFunction code for the hash function used
* @param _size length of the digest
* @param _nonce number of tx of deployment key
* @param _salt vanity bytes used to generate the contract address
* @param _code initialization bytecode used to the logic in the contract
* @param _opcode represents which opcode used to calculate the contract address, where create2 = true and create = false
*/
function createEntry(
address _contract,
bytes32 _digest,
uint8 _hashFunction,
uint8 _size,
int _nonce,
bytes32 _salt,
bytes memory _code,
bool _opcode
)
public
onlyDeployer(_contract, _opcode, _nonce, _salt, _code)
{
_setEntry(_contract, _digest, _hashFunction, _size, DEPLOYER_CATEGORY);
emit EntrySet(
_contract,
msg.sender,
_digest,
_hashFunction,
_size
);
}
/**
* @dev Update an associated multihash with a contract if sender has delegate permissions
* @param _contract address of the associated contract
* @param _digest hash digest produced by hashing content using hash function
* @param _hashFunction hashFunction code for the hash function used
* @param _size length of the digest
* @param _categoryID The keccak256 hash of the string representing the category
*/
function updateEntry (
address _contract,
bytes32 _digest,
uint8 _hashFunction,
uint8 _size,
bytes32 _categoryID
)
public
onlyDelegate(_contract, _categoryID)
{
require(approvedCategories[_contract][_categoryID], "Error: deployer must consent to category update");
_setEntry(_contract, _digest, _hashFunction, _size, _categoryID);
emit EntrySet(
_contract,
msg.sender,
_digest,
_hashFunction,
_size
);
}
/**
* @dev Deassociate a multihash entry of a contract address if one exists and sender is a delegate(deployer)
* @param _contract address of the deassociated contract
* @param _categoryID The keccak256 hash of the string representing the category
*/
function clearEntry(address _contract, bytes32 _categoryID)
public
onlyDelegate(_contract, _categoryID)
{
require(entries[_contract][_categoryID].digest != 0, "Error: missing entry");
delete entries[_contract][_categoryID];
versions[_contract][_categoryID] -= 1;
emit EntryDeleted(msg.sender, versions[_contract][_categoryID]);
}
/**
* @dev Deassociate a multihash entry of a contract address if one exists and sender is a delegate(or original deployer)
* @param _contract address of the deassociated contract
* @param _categoryID The keccak256 hash of the string representing the category
*/
function setDelegate(address _contract, address _delegate, bytes32 _categoryID)
public
onlyDelegate(_contract, _categoryID)
{
require(entries[_contract][_categoryID].delegate != ANY_ADDRESS, "Error: Deployer made all ethereum addresses' delegates");
entries[_contract][_categoryID].delegate = _delegate;
emit SetDelegate(_contract, _delegate);
}
/**
* @dev Deployer can approve a category hash for a particular contract
* @param _contract Address of the contract used in the registry
* @param _categoryID The keccak256 hash of the string representing the category
*/
function addCategory(address _contract, bytes32 _categoryID, address _initialDelegate)
public
{
require(deployers[_contract] == msg.sender || msg.sender == _contract, "Error: you do not have permission to add a category");
require(_categoryID != DEPLOYER_CATEGORY, "Error: default category already initialized");
require(_categoryID != bytes32(0), "Error: valid category hash must not be zero");
approvedCategories[_contract][_categoryID] = true;
if (_initialDelegate == address(0x0)) {
setDelegate(_contract, msg.sender, _categoryID);
} else {
setDelegate(_contract, _initialDelegate, _categoryID);
}
emit CategoryAdded(_contract, _categoryID, msg.sender);
}
/**
* @dev Deletes a category as well as the corresponding entry
* @param _contract Address of the contract used in the registry
* @param _categoryID The keccak256 hash of the string representing the category
*/
function deleteCategory(address _contract, bytes32 _categoryID)
public
onlyDelegate(_contract, _categoryID)
{
require(approvedCategories[_contract][_categoryID], "Error: provided category must exist");
approvedCategories[_contract][_categoryID] = false;
clearEntry(_contract, _categoryID);
emit CategoryDeleted(_contract, _categoryID);
}
/**
* @dev Gets the status of valid categories for a particular contract
* @param _contract Address of the contract used in the registry
* @param _categoryID The keccak256 hash of the string representing the category
*/
function getCategoryStatus(address _contract, bytes32 _categoryID)
public
view
returns(bool)
{
return approvedCategories[_contract][_categoryID];
}
/**
* @dev Retrieve multihash entry associated with an address
* @param _address Contract address used in the registry
* @param _categoryID The keccak256 hash of the string representing the category
*/
function getIPFSMultihash(address _address, bytes32 _categoryID)
public
view
returns(bytes32 digest, uint8 hashFunction, uint8 size)
{
Entry storage entry = entries[_address][_categoryID];
return (entry.digest, entry.hashFunction, entry.size);
}
/**
* @dev Retrieve delegate address associated with a contract
* @param _address address used as key
* @param _categoryID The keccak256 hash of the string representing the category
*/
function getDelegate(address _address, bytes32 _categoryID)
public
view
returns(address delegate)
{
Entry storage entry = entries[_address][_categoryID];
return (entry.delegate);
}
/**
* @dev Retrieve number of versions published for a contract
* @param _address address used as key
* @param _categoryID The keccak256 hash of the string representing the category
*/
function getVersion(address _address, bytes32 _categoryID)
public
view
returns(uint)
{
uint version = versions[_address][_categoryID];
return version;
}
/**
* @dev Retrieves the address of the deployment key for a particular contract in the registry
* @param _contract address of the contract with an entry in the registry
*/
function getRegisteredDeployer(address _contract)
public
view
returns(address)
{
return deployers[_contract];
}
/**
* @dev Calculates the address generated using the create2 opcode. For testing purposes only...
* @return calculated Address
*/
function calculateCreate2Addr(address _origin, bytes32 _salt, bytes memory _code) public pure returns (address) {
// Assumes no memory expansion
// keccak256( 0xff ++ address ++ salt ++ keccak256(init_code))[12:]
return address(keccak256(byte(0xff), _origin, _salt, keccak256(_code)));
}
function _setEntry(
address _contract,
bytes32 _digest,
uint8 _hashFunction,
uint8 _size,
bytes32 _categoryID
)
private
{
require(_size != uint8(0), "Error: a size must be given");
bool selfAttested = _contract == msg.sender;
if (!selfAttested) {
uint size;
assembly {
size := extcodesize(_contract)
}
require(size > 0, "Error: code must be deployed at contract address");
}
Entry memory entry = Entry(
selfAttested,
msg.sender,
_digest,
_hashFunction,
_size
);
entries[_contract][_categoryID] = entry;
versions[_contract][_categoryID] += 1;
approvedCategories[_contract][_categoryID] = true;
}
function addressFrom(address _origin, int _nonce) private pure returns (address) {
// https://ethereum.stackexchange.com/a/47083
if (_nonce == 0x00)
return address(keccak256(byte(0xd6), byte(0x94), _origin, byte(0x80)));
if (_nonce <= 0x7f)
return address(keccak256(byte(0xd6), byte(0x94), _origin, byte(_nonce)));
if (_nonce <= 0xff)
return address(keccak256(byte(0xd7), byte(0x94), _origin, byte(0x81), uint8(_nonce)));
if (_nonce <= 0xffff)
return address(keccak256(byte(0xd8), byte(0x94), _origin, byte(0x82), uint16(_nonce)));
if (_nonce <= 0xffffff)
return address(keccak256(byte(0xd9), byte(0x94), _origin, byte(0x83), uint24(_nonce)));
return address(keccak256(byte(0xda), byte(0x94), _origin, byte(0x84), uint32(_nonce))); // more than 2^32 nonces not realistic
}
}
| Retrieve number of versions published for a contract _address address used as key _categoryID The keccak256 hash of the string representing the category/ | function getVersion(address _address, bytes32 _categoryID)
public
view
returns(uint)
{
uint version = versions[_address][_categoryID];
return version;
}
| 13,114,927 |
./full_match/11155111/0xaf6EeD5e61BE0936BDE7fc347a218230FA661E9e/sources/contracts/Latest2_HRTCrowdfunding.sol | Internal function to check if the caller is the campaign owner | function isCampaignOwner(uint256 _campaignId) internal view returns (bool) {
return msg.sender == campaigns[_campaignId].owner;
}
| 3,800,239 |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../interfaces/IUniswapRouter.sol";
import "./StrategyBase.sol";
interface IVSPPool is IERC20{
function deposit() external payable;
function deposit(uint256) external;
function sweepErc20(address) external;
function withdraw(uint256) external;
function withdrawETH(uint256) external;
function withdrawByStrategy(uint256) external;
function getPricePerShare() external view returns (uint256);
function token() external view returns (address);
function tokensHere() external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
function convertFrom18(uint256) external pure returns (uint256);
}
interface IPoolRewards {
function notifyRewardAmount(uint256) external;
function claimReward(address) external;
function updateReward(address) external;
function rewardForDuration() external view returns (uint256);
function claimable(address) external view returns (uint256);
function pool() external view returns (address);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
}
contract VesperStrategy is StrategyBase {
using SafeERC20 for IERC20;
using SafeMath for uint256;
IERC20 public token;
IVSPPool vspPool;
IPoolRewards poolRewards = IPoolRewards(0x93567318aaBd27E21c52F766d2844Fc6De9Dc738);
address vspToken = 0x1b40183EFB4Dd766f11bDa7A7c3AD8982e998421;
uint32 lastVSPClaim; //TODO If no smaller Datatypes come, change to uint256
constructor(address _controller, address _pool, address _token, address _vspPool) StrategyBase(_controller, _pool) {
token = IERC20(_token);
vspPool = IVSPPool(_vspPool);
IERC20(vspToken).approve(controller.uniswapRouter(), 2**256-1);
//TODO Debug
require(IERC20(vspToken).allowance(controller.uniswapRouter(), address(this)) == 2**256-1, "failed");
lastVSPClaim = uint32(block.timestamp);
}
function rebalance() public override {
uint256 currentBalance = token.balanceOf(address(this));
uint256 locked = lockedInVSP();
uint256 p1 = locked.div(100);
if(currentBalance > p1.mul(2)){ //Greater than 2% -> Reduce to 1%
uint256 depositAmount = currentBalance - p1;
vspPool.deposit(depositAmount);
}
// else if(currentBalance < 1p){}
}
// event Log(uint256 index, uint256 a);
// event Log4(uint256 index, address a);
function deposit(uint256 amount) public override onlyPool {
// emit Log(1, amount);
// emit Log4(2, msg.sender);
// emit Log4(3, address(pool));
// emit Log4(4, address(this));
token.transferFrom(pool, address(this), amount);
}
function withdraw(uint256 amount) public override onlyPool {
//TODO Check if there is enough WETH, if not withdraw collateral
token.transfer(pool, amount);
}
function withdrawAll() public override onlyController {
claimVspAndSwap(claimableVSP());
vspPool.withdraw(vspPool.balanceOf(address(this)));
// withdrawFromVSP(totalLocked());
token.safeTransfer(pool, token.balanceOf(address(this)));
}
function claimableVSP() public view returns (uint256){
return poolRewards.claimable(address(this));
}
/// @dev Withdraws specified ETH amount from vETH Pool, either using VSP Rewards or withdrawing Collateral
function withdrawFromVSP(uint256 amount) internal {
// uint vspclaimable = claimableVSP();
// uint vspcollateral = vspCollateral();
// if(vspclaimable >= amount.mul(controller.interestFee(address(pool))) { //TODO Has to be multiplied by price
// if(block.timestamp > lastVSPClaim + 12 hours){
// claimVspAndSwap(vspclaimable);
// }
// }
uint256 shares = amount.mul(vspPool.convertFrom18(1e18)).div(vspPool.getPricePerShare());
//TODO Make sure, it isnΒ΄t too less because of rounding errors
vspPool.withdraw(shares);
}
function claimVspAndSwap(uint256 vspclaimable) internal {
poolRewards.claimReward(address(this));
uint256 swapped = swapVSP(vspclaimable);
uint256 fee = swapped.mul(15).div(100);
token.transfer(controller.feeCollector(), fee);
}
function swapVSP(uint256 amount) internal returns (uint256) {
uint256 deadline = block.timestamp + 15;
address[] memory path = new address[](2); //TODO Maybe als Storage Array vorinitialisieren?
path[0] = vspToken;
path[1] = address(token);
IUniswapV2Router01 router = IUniswapV2Router01(controller.uniswapRouter());
uint256 swapped = router.swapExactTokensForTokens(amount, 1 /*TODO*/, path, address(this), deadline)[path.length - 1];
return swapped;
}
function vspPrice() internal view returns (uint256) {
address[] memory path = new address[](2);
path[0] = vspToken;
path[1] = address(token);
uint256 price = IUniswapV2Router01(controller.uniswapRouter()).getAmountsOut(1e18, path)[0];
return price;
}
//function isUpgradable() external view returns (bool);
//function isReservedToken(address _token) external view returns (bool);
//function token() external view returns (address);
function vspCollateral() internal view returns (uint256) {
return vspPool.balanceOf(address(this)).mul(vspPool.getPricePerShare()).div(1e18);
}
function lockedInVSP() public view returns (uint256) {
return vspCollateral().add(claimableVSP());
}
function totalLocked() public override view returns (uint256) {
//TODO ADD VSP Logic
return token.balanceOf(address(this))
.add(lockedInVSP());
}
//DEBUG ------------
function deposit() public payable {
}
} | TODO Check if there is enough WETH, if not withdraw collateral | function withdraw(uint256 amount) public override onlyPool {
token.transfer(pool, amount);
}
| 12,865,805 |
./full_match/1/0x653050F11B5f20213C9d1Ee62Cc02A76518649c6/sources/contracts/DullahanVault.sol | Get the maximum amount that can be minted by the user user User address return uint256 : Max amount to mint/ | function maxMint(address user) public view returns (uint256) {
return type(uint256).max;
}
| 9,800,050 |
/**
*Submitted for verification at Etherscan.io on 2021-08-11
*/
/*
___ _ ___ _
| .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___
| _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._>
|_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___.
* PeriFinance: PeriFinanceToEthereum.sol
*
* Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/PeriFinanceToEthereum.sol
* Docs: Will be added in the future.
* https://docs.peri.finance/contracts/source/contracts/PeriFinanceToEthereum
*
* Contract Dependencies:
* - BasePeriFinance
* - ExternStateToken
* - IAddressResolver
* - IERC20
* - IPeriFinance
* - MixinResolver
* - Owned
* - PeriFinance
* - Proxyable
* - State
* Libraries:
* - SafeDecimalMath
* - SafeMath
* - VestingEntries
*
* MIT License
* ===========
*
* Copyright (c) 2021 PeriFinance
*
* 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
*/
pragma solidity 0.5.16;
// https://docs.peri.finance/contracts/source/interfaces/ierc20
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// https://docs.peri.finance/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/proxy
contract Proxy is Owned {
Proxyable public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(Proxyable _target) external onlyOwner {
target = _target;
emit TargetUpdated(_target);
}
function _emit(
bytes calldata callData,
uint numTopics,
bytes32 topic1,
bytes32 topic2,
bytes32 topic3,
bytes32 topic4
) external onlyTarget {
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
// solhint-disable no-complex-fallback
function() external payable {
// Mutable call setting Proxyable.messageSender as this is using call not delegatecall
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) {
revert(free_ptr, returndatasize)
}
return(free_ptr, returndatasize)
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/proxyable
contract Proxyable is Owned {
// This contract should be treated like an abstract contract
/* The proxy this contract exists behind. */
Proxy public proxy;
Proxy public integrationProxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address public messageSender;
constructor(address payable _proxy) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address payable _proxy) external onlyOwner {
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setIntegrationProxy(address payable _integrationProxy) external onlyOwner {
integrationProxy = Proxy(_integrationProxy);
}
function setMessageSender(address sender) external onlyProxy {
messageSender = sender;
}
modifier onlyProxy {
_onlyProxy();
_;
}
function _onlyProxy() private view {
require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
}
modifier optionalProxy {
_optionalProxy();
_;
}
function _optionalProxy() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
}
modifier optionalProxy_onlyOwner {
_optionalProxy_onlyOwner();
_;
}
// solhint-disable-next-line func-name-mixedcase
function _optionalProxy_onlyOwner() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
require(messageSender == owner, "Owner only function");
}
event ProxyUpdated(address proxyAddress);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.peri.finance/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @dev Round down the value with given number
*/
function roundDownDecimal(uint x, uint d) internal pure returns (uint) {
return x.div(10**d).mul(10**d);
}
/**
* @dev Round up the value with given number
*/
function roundUpDecimal(uint x, uint d) internal pure returns (uint) {
uint _decimal = 10**d;
if (x % _decimal > 0) {
x = x.add(10**d);
}
return x.div(_decimal).mul(_decimal);
}
}
// Inheritance
// https://docs.peri.finance/contracts/source/contracts/state
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _associatedContract) internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract) external onlyOwner {
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract {
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
// Inheritance
// https://docs.peri.finance/contracts/source/contracts/tokenstate
contract TokenState is Owned, State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(
address tokenOwner,
address spender,
uint value
) external onlyAssociatedContract {
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value) external onlyAssociatedContract {
balanceOf[account] = value;
}
}
// Inheritance
// Libraries
// Internal references
// https://docs.peri.finance/contracts/source/contracts/externstatetoken
contract ExternStateToken is Owned, Proxyable {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields. */
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _name,
string memory _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
) public Owned(_owner) Proxyable(_proxy) {
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender) public view returns (uint) {
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account) external view returns (uint) {
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
tokenState = _tokenState;
emitTokenStateUpdated(address(_tokenState));
}
function _internalTransfer(
address from,
address to,
uint value
) internal returns (bool) {
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
// Insufficient balance will be handled by the safe subtraction.
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transferByProxy(
address from,
address to,
uint value
) internal returns (bool) {
return _internalTransfer(from, to, value);
}
/*
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFromByProxy(
address sender,
address from,
address to,
uint value
) internal returns (bool) {
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value);
}
function _mintByProxy(address _minter, uint _value) internal returns (bool) {
tokenState.setBalanceOf(_minter, tokenState.balanceOf(_minter).add(_value));
emitTransfer(address(0), _minter, _value);
return true;
}
function _burnByProxy(address _burner, uint _value) internal returns (bool) {
tokenState.setBalanceOf(_burner, tokenState.balanceOf(_burner).sub(_value));
emitTransfer(_burner, address(0), _value);
return true;
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value) public optionalProxy returns (bool) {
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
function addressToBytes32(address input) internal pure returns (bytes32) {
return bytes32(uint256(uint160(input)));
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(
address from,
address to,
uint value
) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(
address owner,
address spender,
uint value
) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
// https://docs.peri.finance/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getPynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.peri.finance/contracts/source/interfaces/ipynth
interface IPynth {
// Views
function currencyKey() external view returns (bytes32);
function transferablePynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to PeriFinance
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function canBurnPynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function externalTokenLimit() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function externalTokenQuota(
address _account,
uint _addtionalpUSD,
uint _addtionalExToken,
bool _isIssue
) external view returns (uint);
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota);
function minimumStakeTime() external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to PeriFinance
function issuePynths(
address _issuer,
bytes32 _currencyKey,
uint _issueAmount
) external;
function issueMaxPynths(address _issuer) external;
function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external;
function burnPynths(
address _from,
bytes32 _currencyKey,
uint _burnAmount
) external;
function fitToClaimable(address _from) external;
function exit(address _from) external;
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getPynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.pynths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.peri.finance/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
interface IVirtualPynth {
// Views
function balanceOfUnderlying(address account) external view returns (uint);
function rate() external view returns (uint);
function readyToSettle() external view returns (bool);
function secsLeftInWaitingPeriod() external view returns (uint);
function settled() external view returns (bool);
function pynth() external view returns (IPynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinance
interface IPeriFinance {
// Views
function getRequiredAddress(bytes32 contractName) external view returns (address);
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint);
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool);
function maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function externalTokenQuota(
address _account,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey) external view returns (uint);
function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint);
function transferablePeriFinance(address account) external view returns (uint transferable);
// Mutative Functions
function issuePynths(bytes32 _currencyKey, uint _issueAmount) external;
function issueMaxPynths() external;
function issuePynthsToMaxQuota(bytes32 _currencyKey) external;
function burnPynths(bytes32 _currencyKey, uint _burnAmount) external;
function fitToClaimable() external;
function exit() external;
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function mint(address _user, uint _amount) external returns (bool);
function inflationalMint(uint _networkDebtShare) external returns (bool);
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
// Liquidations
function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool);
// Restricted Functions
function mintSecondary(address account, uint amount) external;
function mintSecondaryRewards(uint amount) external;
function burnSecondary(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinancestate
interface IPeriFinanceState {
// Views
function debtLedger(uint index) external view returns (uint);
function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex);
function debtLedgerLength() external view returns (uint);
function hasIssued(address account) external view returns (bool);
function lastDebtLedgerEntry() external view returns (uint);
// Mutative functions
function incrementTotalIssuerCount() external;
function decrementTotalIssuerCount() external;
function setCurrentIssuanceData(address account, uint initialDebtOwnership) external;
function appendDebtLedgerValue(uint value) external;
function clearIssuanceData(address account) external;
}
// https://docs.peri.finance/contracts/source/interfaces/isystemstatus
interface ISystemStatus {
struct Status {
bool canSuspend;
bool canResume;
}
struct Suspension {
bool suspended;
// reason is an integer code,
// 0 => no reason, 1 => upgrading, 2+ => defined by system usage
uint248 reason;
}
// Views
function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume);
function requireSystemActive() external view;
function requireIssuanceActive() external view;
function requireExchangeActive() external view;
function requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requirePynthActive(bytes32 currencyKey) external view;
function requirePynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function systemSuspension() external view returns (bool suspended, uint248 reason);
function issuanceSuspension() external view returns (bool suspended, uint248 reason);
function exchangeSuspension() external view returns (bool suspended, uint248 reason);
function pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getPynthExchangeSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getPynthSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendPynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isPynthRateInvalid(bytes32 currencyKey) external view returns (bool);
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint);
function settlementOwing(address account, bytes32 currencyKey)
external
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
);
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool);
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate);
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
);
function priceDeviationThresholdFactor() external view returns (uint);
function waitingPeriodSecs() external view returns (uint);
// Mutative functions
function exchange(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForPynth(bytes32 currencyKey, uint rate) external;
function suspendPynthWithInvalidRate(bytes32 currencyKey) external;
}
// https://docs.peri.finance/contracts/source/interfaces/irewardsdistribution
interface IRewardsDistribution {
// Structs
struct DistributionData {
address destination;
uint amount;
}
// Views
function authority() external view returns (address);
function distributions(uint index) external view returns (address destination, uint amount); // DistributionData
function distributionsLength() external view returns (uint);
// Mutative Functions
function distributeRewards(uint amount) external returns (bool);
}
// Inheritance
// Libraries
// Internal references
interface IBlacklistManager {
function flagged(address _account) external view returns (bool);
}
contract BasePeriFinance is IERC20, ExternStateToken, MixinResolver, IPeriFinance {
using SafeMath for uint;
using SafeDecimalMath for uint;
// ========== STATE VARIABLES ==========
// Available Pynths which can be used with the system
string public constant TOKEN_NAME = "Peri Finance Token";
string public constant TOKEN_SYMBOL = "PERI";
uint8 public constant DECIMALS = 18;
bytes32 public constant pUSD = "pUSD";
// ========== ADDRESS RESOLVER CONFIGURATION ==========
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
IBlacklistManager public blacklistManager;
// ========== CONSTRUCTOR ==========
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver,
address _blacklistManager
)
public
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner)
MixinResolver(_resolver)
{
blacklistManager = IBlacklistManager(_blacklistManager);
}
// ========== VIEWS ==========
// Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](5);
addresses[0] = CONTRACT_PERIFINANCESTATE;
addresses[1] = CONTRACT_SYSTEMSTATUS;
addresses[2] = CONTRACT_EXCHANGER;
addresses[3] = CONTRACT_ISSUER;
addresses[4] = CONTRACT_REWARDSDISTRIBUTION;
}
function periFinanceState() internal view returns (IPeriFinanceState) {
return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function rewardsDistribution() internal view returns (IRewardsDistribution) {
return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION));
}
function getRequiredAddress(bytes32 _contractName) external view returns (address) {
return requireAndGetAddress(_contractName);
}
function debtBalanceOf(address account, bytes32 currencyKey) external view returns (uint) {
return issuer().debtBalanceOf(account, currencyKey);
}
function totalIssuedPynths(bytes32 currencyKey) external view returns (uint) {
return issuer().totalIssuedPynths(currencyKey, false);
}
function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint) {
return issuer().totalIssuedPynths(currencyKey, true);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return issuer().availableCurrencyKeys();
}
function availablePynthCount() external view returns (uint) {
return issuer().availablePynthCount();
}
function availablePynths(uint index) external view returns (IPynth) {
return issuer().availablePynths(index);
}
function pynths(bytes32 currencyKey) external view returns (IPynth) {
return issuer().pynths(currencyKey);
}
function pynthsByAddress(address pynthAddress) external view returns (bytes32) {
return issuer().pynthsByAddress(pynthAddress);
}
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool) {
return exchanger().maxSecsLeftInWaitingPeriod(messageSender, currencyKey) > 0;
}
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) {
return issuer().anyPynthOrPERIRateIsInvalid();
}
function maxIssuablePynths(address account) external view returns (uint maxIssuable) {
return issuer().maxIssuablePynths(account);
}
function externalTokenQuota(
address _account,
uint _additionalpUSD,
uint _additionalExToken,
bool _isIssue
) external view returns (uint) {
return issuer().externalTokenQuota(_account, _additionalpUSD, _additionalExToken, _isIssue);
}
function remainingIssuablePynths(address account)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
return issuer().remainingIssuablePynths(account);
}
function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey)
external
view
returns (uint issueAmountToQuota, uint stakeAmountToQuota)
{
return issuer().maxExternalTokenStakeAmount(_account, _currencyKey);
}
function collateralisationRatio(address _issuer) external view returns (uint) {
return issuer().collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return issuer().collateral(account);
}
function transferablePeriFinance(address account) external view returns (uint transferable) {
(transferable, ) = issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account));
}
function _canTransfer(address account, uint value) internal view returns (bool) {
(uint initialDebtOwnership, ) = periFinanceState().issuanceData(account);
if (initialDebtOwnership > 0) {
(uint transferable, bool anyRateIsInvalid) =
issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account));
require(value <= transferable, "Cannot transfer staked or escrowed PERI");
require(!anyRateIsInvalid, "A pynth or PERI rate is invalid");
}
return true;
}
// ========== MUTATIVE FUNCTIONS ==========
function setBlacklistManager(address _blacklistManager) external onlyOwner {
require(_blacklistManager != address(0), "address cannot be empty");
blacklistManager = IBlacklistManager(_blacklistManager);
}
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
exchangeActive(sourceCurrencyKey, destinationCurrencyKey)
optionalProxy
blacklisted(messageSender)
returns (uint amountReceived)
{
_notImplemented();
return exchanger().exchange(messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender);
}
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
exchangeActive(sourceCurrencyKey, destinationCurrencyKey)
optionalProxy
blacklisted(messageSender)
blacklisted(exchangeForAddress)
returns (uint amountReceived)
{
_notImplemented();
return
exchanger().exchangeOnBehalf(
exchangeForAddress,
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey
);
}
function settle(bytes32 currencyKey)
external
optionalProxy
blacklisted(messageSender)
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
_notImplemented();
return exchanger().settle(messageSender, currencyKey);
}
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
)
external
exchangeActive(sourceCurrencyKey, destinationCurrencyKey)
optionalProxy
blacklisted(messageSender)
returns (uint amountReceived)
{
_notImplemented();
return
exchanger().exchangeWithTracking(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
originator,
trackingCode
);
}
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
)
external
exchangeActive(sourceCurrencyKey, destinationCurrencyKey)
optionalProxy
blacklisted(messageSender)
blacklisted(exchangeForAddress)
returns (uint amountReceived)
{
_notImplemented();
return
exchanger().exchangeOnBehalfWithTracking(
exchangeForAddress,
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
originator,
trackingCode
);
}
function transfer(address to, uint value) external optionalProxy systemActive blacklisted(messageSender) returns (bool) {
// Ensure they're not trying to exceed their locked amount -- only if they have debt.
_canTransfer(messageSender, value);
// Perform the transfer: if there is a problem an exception will be thrown in this call.
_transferByProxy(messageSender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint value
) external optionalProxy systemActive blacklisted(messageSender) blacklisted(from) returns (bool) {
// Ensure they're not trying to exceed their locked amount -- only if they have debt.
_canTransfer(from, value);
// Perform the transfer: if there is a problem,
// an exception will be thrown in this call.
return _transferFromByProxy(messageSender, from, to, value);
}
function issuePynths(bytes32 _currencyKey, uint _issueAmount)
external
issuanceActive
optionalProxy
blacklisted(messageSender)
{
issuer().issuePynths(messageSender, _currencyKey, _issueAmount);
}
function issueMaxPynths() external issuanceActive optionalProxy blacklisted(messageSender) {
issuer().issueMaxPynths(messageSender);
}
function issuePynthsToMaxQuota(bytes32 _currencyKey) external issuanceActive optionalProxy blacklisted(messageSender) {
issuer().issuePynthsToMaxQuota(messageSender, _currencyKey);
}
function burnPynths(bytes32 _currencyKey, uint _burnAmount)
external
issuanceActive
optionalProxy
blacklisted(messageSender)
{
issuer().burnPynths(messageSender, _currencyKey, _burnAmount);
}
function fitToClaimable() external issuanceActive optionalProxy blacklisted(messageSender) {
issuer().fitToClaimable(messageSender);
}
function exit() external issuanceActive optionalProxy blacklisted(messageSender) {
issuer().exit(messageSender);
}
function exchangeWithVirtual(
bytes32,
uint,
bytes32,
bytes32
) external returns (uint, IVirtualPynth) {
_notImplemented();
}
function liquidateDelinquentAccount(address, uint) external returns (bool) {
_notImplemented();
}
function mintSecondary(address, uint) external {
_notImplemented();
}
function mintSecondaryRewards(uint) external {
_notImplemented();
}
function burnSecondary(address, uint) external {
_notImplemented();
}
function _notImplemented() internal pure {
revert("Cannot be run on this layer");
}
// ========== MODIFIERS ==========
modifier systemActive() {
_systemActive();
_;
}
function _systemActive() private view {
systemStatus().requireSystemActive();
}
modifier issuanceActive() {
_issuanceActive();
_;
}
function _issuanceActive() private view {
systemStatus().requireIssuanceActive();
}
function _blacklisted(address _account) private view {
require(address(blacklistManager) != address(0), "Required contract is not set yet");
require(!blacklistManager.flagged(_account), "Account is on blacklist");
}
modifier blacklisted(address _account) {
_blacklisted(_account);
_;
}
modifier exchangeActive(bytes32 src, bytes32 dest) {
_exchangeActive(src, dest);
_;
}
function _exchangeActive(bytes32 src, bytes32 dest) private view {
systemStatus().requireExchangeBetweenPynthsAllowed(src, dest);
}
modifier onlyExchanger() {
_onlyExchanger();
_;
}
function _onlyExchanger() private view {
require(msg.sender == address(exchanger()), "Only Exchanger can invoke this");
}
// ========== EVENTS ==========
event PynthExchange(
address indexed account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
);
bytes32 internal constant PYNTHEXCHANGE_SIG =
keccak256("PynthExchange(address,bytes32,uint256,bytes32,uint256,address)");
function emitPynthExchange(
address account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
) external onlyExchanger {
proxy._emit(
abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress),
2,
PYNTHEXCHANGE_SIG,
addressToBytes32(account),
0,
0
);
}
event ExchangeTracking(bytes32 indexed trackingCode, bytes32 toCurrencyKey, uint256 toAmount);
bytes32 internal constant EXCHANGE_TRACKING_SIG = keccak256("ExchangeTracking(bytes32,bytes32,uint256)");
function emitExchangeTracking(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount
) external onlyExchanger {
proxy._emit(abi.encode(toCurrencyKey, toAmount), 2, EXCHANGE_TRACKING_SIG, trackingCode, 0, 0);
}
event ExchangeReclaim(address indexed account, bytes32 currencyKey, uint amount);
bytes32 internal constant EXCHANGERECLAIM_SIG = keccak256("ExchangeReclaim(address,bytes32,uint256)");
function emitExchangeReclaim(
address account,
bytes32 currencyKey,
uint256 amount
) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGERECLAIM_SIG, addressToBytes32(account), 0, 0);
}
event ExchangeRebate(address indexed account, bytes32 currencyKey, uint amount);
bytes32 internal constant EXCHANGEREBATE_SIG = keccak256("ExchangeRebate(address,bytes32,uint256)");
function emitExchangeRebate(
address account,
bytes32 currencyKey,
uint256 amount
) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGEREBATE_SIG, addressToBytes32(account), 0, 0);
}
}
// https://docs.peri.finance/contracts/source/interfaces/irewardescrow
interface IRewardEscrow {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory);
function getNextVestingIndex(address account) external view returns (uint);
// Mutative functions
function appendVestingEntry(address account, uint quantity) external;
function vest() external;
}
pragma experimental ABIEncoderV2;
library VestingEntries {
struct VestingEntry {
uint64 endTime;
uint256 escrowAmount;
}
struct VestingEntryWithID {
uint64 endTime;
uint256 escrowAmount;
uint256 entryID;
}
}
interface IRewardEscrowV2 {
// Views
function balanceOf(address account) external view returns (uint);
function numVestingEntries(address account) external view returns (uint);
function totalEscrowedAccountBalance(address account) external view returns (uint);
function totalVestedAccountBalance(address account) external view returns (uint);
function getVestingQuantity(address account, uint256[] calldata entryIDs) external view returns (uint);
function getVestingSchedules(
address account,
uint256 index,
uint256 pageSize
) external view returns (VestingEntries.VestingEntryWithID[] memory);
function getAccountVestingEntryIDs(
address account,
uint256 index,
uint256 pageSize
) external view returns (uint256[] memory);
function getVestingEntryClaimable(address account, uint256 entryID) external view returns (uint);
function getVestingEntry(address account, uint256 entryID) external view returns (uint64, uint256);
// Mutative functions
function vest(uint256[] calldata entryIDs) external;
function createEscrowEntry(
address beneficiary,
uint256 deposit,
uint256 duration
) external;
function appendVestingEntry(
address account,
uint256 quantity,
uint256 duration
) external;
function migrateVestingSchedule(address _addressToMigrate) external;
function migrateAccountEscrowBalances(
address[] calldata accounts,
uint256[] calldata escrowBalances,
uint256[] calldata vestedBalances
) external;
// Account Merging
function startMergingWindow() external;
function mergeAccount(address accountToMerge, uint256[] calldata entryIDs) external;
function nominateAccountToMerge(address account) external;
function accountMergingIsOpen() external view returns (bool);
// L2 Migration
function importVestingEntries(
address account,
uint256 escrowedAmount,
VestingEntries.VestingEntry[] calldata vestingEntries
) external;
// Return amount of PERI transfered to PeriFinanceBridgeToOptimism deposit contract
function burnForMigration(address account, uint256[] calldata entryIDs)
external
returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries);
}
// https://docs.peri.finance/contracts/source/interfaces/isupplyschedule
interface ISupplySchedule {
// Views
function mintableSupply() external view returns (uint);
function isMintable() external view returns (bool);
function minterReward() external view returns (uint);
// Mutative functions
function recordMintEvent(uint supplyMinted) external returns (bool);
}
interface IBridgeState {
// ----VIEWS
function networkOpened(uint chainId) external view returns (bool);
function accountOutboundings(
address account,
uint periodId,
uint index
) external view returns (uint);
function accountInboundings(address account, uint index) external view returns (uint);
function inboundings(uint index)
external
view
returns (
address,
uint,
uint,
uint,
bool
);
function outboundings(uint index)
external
view
returns (
address,
uint,
uint,
uint
);
function outboundPeriods(uint index)
external
view
returns (
uint,
uint,
uint[] memory,
bool
);
function outboundIdsToProcess(uint index) external view returns (uint);
function numberOfOutboundPerPeriod() external view returns (uint);
function periodDuration() external view returns (uint);
function outboundingsLength() external view returns (uint);
function inboundingsLength() external view returns (uint);
function outboundIdsInPeriod(uint outboundPeriodId) external view returns (uint[] memory);
function isOnRole(bytes32 roleKey, address account) external view returns (bool);
function accountOutboundingsInPeriod(address _account, uint _period) external view returns (uint[] memory);
function applicableInboundIds(address account) external view returns (uint[] memory);
function outboundRequestIdsInPeriod(address account, uint periodId) external view returns (uint[] memory);
function periodIdsToProcess() external view returns (uint[] memory);
// ----MUTATIVES
function appendOutboundingRequest(
address account,
uint amount,
uint destChainIds
) external;
function appendMultipleInboundingRequests(
address[] calldata accounts,
uint[] calldata amounts,
uint[] calldata srcChainIds,
uint[] calldata srcOutboundingIds
) external;
function appendInboundingRequest(
address account,
uint amount,
uint srcChainId,
uint srcOutboundingId
) external;
function claimInbound(uint index) external;
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/periFinance
contract PeriFinance is BasePeriFinance {
// ========== ADDRESS RESOLVER CONFIGURATION ==========
bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_SUPPLYSCHEDULE = "SupplySchedule";
address public minterRole;
address public inflationMinter;
IBridgeState public bridgeState;
// ========== CONSTRUCTOR ==========
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver,
address _minterRole,
address _blacklistManager
) public BasePeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver, _blacklistManager) {
minterRole = _minterRole;
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = BasePeriFinance.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](3);
newAddresses[0] = CONTRACT_REWARD_ESCROW;
newAddresses[1] = CONTRACT_REWARDESCROW_V2;
newAddresses[2] = CONTRACT_SUPPLYSCHEDULE;
return combineArrays(existingAddresses, newAddresses);
}
// ========== VIEWS ==========
function rewardEscrow() internal view returns (IRewardEscrow) {
return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function supplySchedule() internal view returns (ISupplySchedule) {
return ISupplySchedule(requireAndGetAddress(CONTRACT_SUPPLYSCHEDULE));
}
// ========== OVERRIDDEN FUNCTIONS ==========
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
)
external
exchangeActive(sourceCurrencyKey, destinationCurrencyKey)
optionalProxy
blacklisted(messageSender)
returns (uint amountReceived, IVirtualPynth vPynth)
{
_notImplemented();
return
exchanger().exchangeWithVirtual(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
trackingCode
);
}
function settle(bytes32 currencyKey)
external
optionalProxy
blacklisted(messageSender)
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
_notImplemented();
return exchanger().settle(messageSender, currencyKey);
}
function inflationalMint(uint _networkDebtShare) external issuanceActive returns (bool) {
require(msg.sender == inflationMinter, "Not allowed to mint");
require(SafeDecimalMath.unit() >= _networkDebtShare, "Invalid network debt share");
require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set");
ISupplySchedule _supplySchedule = supplySchedule();
IRewardsDistribution _rewardsDistribution = rewardsDistribution();
uint supplyToMint = _supplySchedule.mintableSupply();
supplyToMint = supplyToMint.multiplyDecimal(_networkDebtShare);
require(supplyToMint > 0, "No supply is mintable");
// record minting event before mutation to token supply
_supplySchedule.recordMintEvent(supplyToMint);
// Set minted PERI balance to RewardEscrow's balance
// Minus the minterReward and set balance of minter to add reward
uint minterReward = _supplySchedule.minterReward();
// Get the remainder
uint amountToDistribute = supplyToMint.sub(minterReward);
// Set the token balance to the RewardsDistribution contract
tokenState.setBalanceOf(
address(_rewardsDistribution),
tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute)
);
emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute);
// Kick off the distribution of rewards
_rewardsDistribution.distributeRewards(amountToDistribute);
// Assign the minters reward.
tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
emitTransfer(address(this), msg.sender, minterReward);
totalSupply = totalSupply.add(supplyToMint);
return true;
}
function mint(address _user, uint _amount) external optionalProxy returns (bool) {
require(minterRole != address(0), "Mint is not available");
require(minterRole == messageSender, "Caller is not allowed to mint");
// It won't change totalsupply since it is only for bridge purpose.
tokenState.setBalanceOf(_user, tokenState.balanceOf(_user).add(_amount));
emitTransfer(address(0), _user, _amount);
return true;
}
function liquidateDelinquentAccount(address account, uint pusdAmount)
external
systemActive
optionalProxy
blacklisted(messageSender)
returns (bool)
{
_notImplemented();
(uint totalRedeemed, uint amountLiquidated) =
issuer().liquidateDelinquentAccount(account, pusdAmount, messageSender);
emitAccountLiquidated(account, totalRedeemed, amountLiquidated, messageSender);
// Transfer PERI redeemed to messageSender
// Reverts if amount to redeem is more than balanceOf account, ie due to escrowed balance
return _transferByProxy(account, messageSender, totalRedeemed);
}
// ------------- Bridge Experiment
function overchainTransfer(uint _amount, uint _destChainId) external optionalProxy onlyTester {
require(_amount > 0, "Cannot transfer zero");
require(_burnByProxy(messageSender, _amount), "burning failed");
bridgeState.appendOutboundingRequest(messageSender, _amount, _destChainId);
}
function claimAllBridgedAmounts() external optionalProxy onlyTester {
uint[] memory applicableIds = bridgeState.applicableInboundIds(messageSender);
require(applicableIds.length > 0, "No claimable");
for (uint i = 0; i < applicableIds.length; i++) {
_claimBridgedAmount(applicableIds[i]);
}
}
function claimBridgedAmount(uint _index) external optionalProxy onlyTester {
_claimBridgedAmount(_index);
}
function _claimBridgedAmount(uint _index) internal returns (bool) {
// Validations are checked from bridge state
(address account, uint amount, , , ) = bridgeState.inboundings(_index);
require(account == messageSender, "Caller is not matched");
bridgeState.claimInbound(_index);
require(_mintByProxy(account, amount), "Mint failed");
return true;
}
modifier onlyTester() {
require(address(bridgeState) != address(0), "BridgeState is not set");
bytes32 tester = "Tester";
require(bridgeState.isOnRole(tester, messageSender), "Not tester");
_;
}
/* Once off function for SIP-60 to migrate PERI balances in the RewardEscrow contract
* To the new RewardEscrowV2 contract
*/
function migrateEscrowBalanceToRewardEscrowV2() external onlyOwner {
// Record balanceOf(RewardEscrow) contract
uint rewardEscrowBalance = tokenState.balanceOf(address(rewardEscrow()));
// transfer all of RewardEscrow's balance to RewardEscrowV2
// _internalTransfer emits the transfer event
_internalTransfer(address(rewardEscrow()), address(rewardEscrowV2()), rewardEscrowBalance);
}
function setMinterRole(address _newMinter) external onlyOwner {
// If address is set to zero address, mint is not prohibited
minterRole = _newMinter;
}
function setinflationMinter(address _newinflationMinter) external onlyOwner {
inflationMinter = _newinflationMinter;
}
function setBridgeState(address _newBridgeState) external onlyOwner {
bridgeState = IBridgeState(_newBridgeState);
}
// ========== EVENTS ==========
event AccountLiquidated(address indexed account, uint periRedeemed, uint amountLiquidated, address liquidator);
bytes32 internal constant ACCOUNTLIQUIDATED_SIG = keccak256("AccountLiquidated(address,uint256,uint256,address)");
function emitAccountLiquidated(
address account,
uint256 periRedeemed,
uint256 amountLiquidated,
address liquidator
) internal {
proxy._emit(
abi.encode(periRedeemed, amountLiquidated, liquidator),
2,
ACCOUNTLIQUIDATED_SIG,
addressToBytes32(account),
0,
0
);
}
}
contract PeriFinanceToEthereum is PeriFinance {
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver,
address _minterRole,
address _blacklistManager
) public PeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver, _minterRole, _blacklistManager) {}
} | Validations are checked from bridge state | function _claimBridgedAmount(uint _index) internal returns (bool) {
(address account, uint amount, , , ) = bridgeState.inboundings(_index);
require(account == messageSender, "Caller is not matched");
bridgeState.claimInbound(_index);
require(_mintByProxy(account, amount), "Mint failed");
return true;
}
| 10,567,829 |
./full_match/43113/0xe2B4Af9921C0d89B4404Baa3aD9223904Bb8C876/sources/Avalanche/burnvault.sol | setlockPeriod/ | function setlockPeriod(uint256 _lockPeriod)public onlyOwner{
lockPeriod=_lockPeriod;
}
| 7,183,562 |
/*************************************************************************
* This contract has been merged with solidify
* https://github.com/tiesnetwork/solidify
*************************************************************************/
pragma solidity ^0.4.10;
/*************************************************************************
* import "../common/Manageable.sol" : start
*************************************************************************/
/*************************************************************************
* import "../common/Owned.sol" : start
*************************************************************************/
contract Owned {
address public owner;
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**@dev allows transferring the contract ownership. */
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
owner = _newOwner;
}
}
/*************************************************************************
* import "../common/Owned.sol" : end
*************************************************************************/
///A token that have an owner and a list of managers that can perform some operations
///Owner is always a manager too
contract Manageable is Owned {
event ManagerSet(address manager, bool state);
mapping (address => bool) public managers;
function Manageable() Owned() {
managers[owner] = true;
}
/**@dev Allows execution by managers only */
modifier managerOnly {
assert(managers[msg.sender]);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
super.transferOwnership(_newOwner);
managers[_newOwner] = true;
managers[msg.sender] = false;
}
function setManager(address manager, bool state) ownerOnly {
managers[manager] = state;
ManagerSet(manager, state);
}
}/*************************************************************************
* import "../common/Manageable.sol" : end
*************************************************************************/
/*************************************************************************
* import "./ValueToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./ERC20StandardToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./IERC20Token.sol" : start
*************************************************************************/
/**@dev ERC20 compliant token interface.
https://theethereum.wiki/w/index.php/ERC20_Token_Standard
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string _name) { _name; }
function symbol() public constant returns (string _symbol) { _symbol; }
function decimals() public constant returns (uint8 _decimals) { _decimals; }
function totalSupply() constant returns (uint total) {total;}
function balanceOf(address _owner) constant returns (uint balance) {_owner; balance;}
function allowance(address _owner, address _spender) constant returns (uint remaining) {_owner; _spender; remaining;}
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/*************************************************************************
* import "./IERC20Token.sol" : end
*************************************************************************/
/*************************************************************************
* import "../common/SafeMath.sol" : start
*************************************************************************/
/**dev Utility methods for overflow-proof arithmetic operations
*/
contract SafeMath {
/**dev Returns the sum of a and b. Throws an exception if it exceeds uint256 limits*/
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**dev Returns the difference of a and b. Throws an exception if a is less than b*/
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(a >= b);
return a - b;
}
/**dev Returns the product of a and b. Throws an exception if it exceeds uint256 limits*/
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0) || (z / x == y));
return z;
}
function safeDiv(uint256 x, uint256 y) internal returns (uint256) {
assert(y != 0);
return x / y;
}
}/*************************************************************************
* import "../common/SafeMath.sol" : end
*************************************************************************/
/**@dev Standard ERC20 compliant token implementation */
contract ERC20StandardToken is IERC20Token, SafeMath {
string public name;
string public symbol;
uint8 public decimals;
//tokens already issued
uint256 tokensIssued;
//balances for each account
mapping (address => uint256) balances;
//one account approves the transfer of an amount to another account
mapping (address => mapping (address => uint256)) allowed;
function ERC20StandardToken() {
}
//
//IERC20Token implementation
//
function totalSupply() constant returns (uint total) {
total = tokensIssued;
}
function balanceOf(address _owner) constant returns (uint balance) {
balance = balances[_owner];
}
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
// safeSub inside doTransfer will throw if there is not enough balance.
doTransfer(msg.sender, _to, _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
// Check for allowance is not needed because sub(_allowance, _value) will throw if this condition is not met
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
// safeSub inside doTransfer will throw if there is not enough balance.
doTransfer(_from, _to, _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
remaining = allowed[_owner][_spender];
}
//
// Additional functions
//
/**@dev Gets real token amount in the smallest token units */
function getRealTokenAmount(uint256 tokens) constant returns (uint256) {
return tokens * (uint256(10) ** decimals);
}
//
// Internal functions
//
function doTransfer(address _from, address _to, uint256 _value) internal {
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
}
}/*************************************************************************
* import "./ERC20StandardToken.sol" : end
*************************************************************************/
/*************************************************************************
* import "../token/ValueTokenAgent.sol" : start
*************************************************************************/
/**@dev Watches transfer operation of tokens to validate value-distribution state */
contract ValueTokenAgent {
/**@dev Token whose transfers that contract watches */
ValueToken public valueToken;
/**@dev Allows only token to execute method */
modifier valueTokenOnly {require(msg.sender == address(valueToken)); _;}
function ValueTokenAgent(ValueToken token) {
valueToken = token;
}
/**@dev Called just before the token balance update*/
function tokenIsBeingTransferred(address from, address to, uint256 amount);
/**@dev Called when non-transfer token state change occurs: burn, issue, change of valuable tokens.
holder - address of token holder that committed the change
amount - amount of new or deleted tokens */
function tokenChanged(address holder, uint256 amount);
}/*************************************************************************
* import "../token/ValueTokenAgent.sol" : end
*************************************************************************/
/**@dev Can be relied on to distribute values according to its balances
Can set some reserve addreses whose tokens don't take part in dividend distribution */
contract ValueToken is Manageable, ERC20StandardToken {
/**@dev Watches transfer operation of this token */
ValueTokenAgent valueAgent;
/**@dev Holders of reserved tokens */
mapping (address => bool) public reserved;
/**@dev Reserved token amount */
uint256 public reservedAmount;
function ValueToken() {}
/**@dev Sets new value agent */
function setValueAgent(ValueTokenAgent newAgent) managerOnly {
valueAgent = newAgent;
}
function doTransfer(address _from, address _to, uint256 _value) internal {
if (address(valueAgent) != 0x0) {
//first execute agent method
valueAgent.tokenIsBeingTransferred(_from, _to, _value);
}
//first check if addresses are reserved and adjust reserved amount accordingly
if (reserved[_from]) {
reservedAmount = safeSub(reservedAmount, _value);
//reservedAmount -= _value;
}
if (reserved[_to]) {
reservedAmount = safeAdd(reservedAmount, _value);
//reservedAmount += _value;
}
//then do actual transfer
super.doTransfer(_from, _to, _value);
}
/**@dev Returns a token amount that is accounted in the process of dividend calculation */
function getValuableTokenAmount() constant returns (uint256) {
return totalSupply() - reservedAmount;
}
/**@dev Sets specific address to be reserved */
function setReserved(address holder, bool state) managerOnly {
uint256 holderBalance = balanceOf(holder);
if (address(valueAgent) != 0x0) {
valueAgent.tokenChanged(holder, holderBalance);
}
//change reserved token amount according to holder's state
if (state) {
//reservedAmount += holderBalance;
reservedAmount = safeAdd(reservedAmount, holderBalance);
} else {
//reservedAmount -= holderBalance;
reservedAmount = safeSub(reservedAmount, holderBalance);
}
reserved[holder] = state;
}
}/*************************************************************************
* import "./ValueToken.sol" : end
*************************************************************************/
/*************************************************************************
* import "./ReturnableToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./ReturnTokenAgent.sol" : start
*************************************************************************/
///Returnable tokens receiver
contract ReturnTokenAgent is Manageable {
//ReturnableToken public returnableToken;
/**@dev List of returnable tokens in format token->flag */
mapping (address => bool) public returnableTokens;
/**@dev Allows only token to execute method */
//modifier returnableTokenOnly {require(msg.sender == address(returnableToken)); _;}
modifier returnableTokenOnly {require(returnableTokens[msg.sender]); _;}
/**@dev Executes when tokens are transferred to this */
function returnToken(address from, uint256 amountReturned);
/**@dev Sets token that can call returnToken method */
function setReturnableToken(ReturnableToken token) managerOnly {
returnableTokens[address(token)] = true;
}
/**@dev Removes token that can call returnToken method */
function removeReturnableToken(ReturnableToken token) managerOnly {
returnableTokens[address(token)] = false;
}
}/*************************************************************************
* import "./ReturnTokenAgent.sol" : end
*************************************************************************/
///Token that when sent to specified contract (returnAgent) invokes additional actions
contract ReturnableToken is Manageable, ERC20StandardToken {
/**@dev List of return agents */
mapping (address => bool) public returnAgents;
function ReturnableToken() {}
/**@dev Sets new return agent */
function setReturnAgent(ReturnTokenAgent agent) managerOnly {
returnAgents[address(agent)] = true;
}
/**@dev Removes return agent from list */
function removeReturnAgent(ReturnTokenAgent agent) managerOnly {
returnAgents[address(agent)] = false;
}
function doTransfer(address _from, address _to, uint256 _value) internal {
super.doTransfer(_from, _to, _value);
if (returnAgents[_to]) {
ReturnTokenAgent(_to).returnToken(_from, _value);
}
}
}/*************************************************************************
* import "./ReturnableToken.sol" : end
*************************************************************************/
/*************************************************************************
* import "./IBurnableToken.sol" : start
*************************************************************************/
/**@dev A token that can be burnt */
contract IBurnableToken {
function burn(uint256 _value);
}/*************************************************************************
* import "./IBurnableToken.sol" : end
*************************************************************************/
/**@dev bcshop.io crowdsale token */
contract BCSToken is ValueToken, ReturnableToken, IBurnableToken {
/**@dev Specifies allowed address that always can transfer tokens in case of global transfer lock */
mapping (address => bool) public transferAllowed;
/**@dev Specifies timestamp when specific token holder can transfer funds */
mapping (address => uint256) public transferLockUntil;
/**@dev True if transfer is locked for all holders, false otherwise */
bool public transferLocked;
event Burn(address sender, uint256 value);
/**@dev Creates a token with given initial supply */
function BCSToken(uint256 _initialSupply, uint8 _decimals) {
name = "BCShop.io Token";
symbol = "BCS";
decimals = _decimals;
tokensIssued = _initialSupply * (uint256(10) ** decimals);
//store all tokens at the owner's address;
balances[msg.sender] = tokensIssued;
transferLocked = true;
transferAllowed[msg.sender] = true;
}
/**@dev ERC20StandatdToken override */
function doTransfer(address _from, address _to, uint256 _value) internal {
require(canTransfer(_from));
super.doTransfer(_from, _to, _value);
}
/**@dev Returns true if given address can transfer tokens */
function canTransfer(address holder) constant returns (bool) {
if(transferLocked) {
return transferAllowed[holder];
} else {
return now > transferLockUntil[holder];
}
//return !transferLocked && now > transferLockUntil[holder];
}
/**@dev Lock transfer for a given holder for a given amount of days */
function lockTransferFor(address holder, uint256 daysFromNow) managerOnly {
transferLockUntil[holder] = daysFromNow * 1 days + now;
}
/**@dev Sets transfer allowance for specific holder */
function allowTransferFor(address holder, bool state) managerOnly {
transferAllowed[holder] = state;
}
/**@dev Locks or allows transfer for all holders, for emergency reasons*/
function setLockedState(bool state) managerOnly {
transferLocked = state;
}
function burn(uint256 _value) managerOnly {
require (balances[msg.sender] >= _value); // Check if the sender has enough
if (address(valueAgent) != 0x0) {
valueAgent.tokenChanged(msg.sender, _value);
}
balances[msg.sender] -= _value; // Subtract from the sender
tokensIssued -= _value; // Updates totalSupply
Burn(msg.sender, _value);
}
} | Locks or allows transfer for all holders, for emergency reasons/ | function setLockedState(bool state) managerOnly {
transferLocked = state;
}
| 2,500,679 |
// File: soltsice/contracts/MultiOwnable.sol
pragma solidity ^0.4.18;
/*
* A minimum multisig wallet interface. Compatible with MultiSigWallet by Gnosis.
*/
contract WalletBasic {
function isOwner(address owner) public returns (bool);
}
/**
* @dev MultiOwnable contract.
*/
contract MultiOwnable {
WalletBasic public wallet;
event MultiOwnableWalletSet(address indexed _contract, address indexed _wallet);
function MultiOwnable
(address _wallet)
public
{
wallet = WalletBasic(_wallet);
MultiOwnableWalletSet(this, wallet);
}
/** Check if a caller is the MultiSig wallet. */
modifier onlyWallet() {
require(wallet == msg.sender);
_;
}
/** Check if a caller is one of the current owners of the MultiSig wallet or the wallet itself. */
modifier onlyOwner() {
require (isOwner(msg.sender));
_;
}
function isOwner(address _address)
public
constant
returns(bool)
{
// NB due to lazy eval wallet could be a normal address and isOwner won't be called if the first condition is met
return wallet == _address || wallet.isOwner(_address);
}
/* PAUSABLE with upause callable only by wallet */
bool public paused = false;
event Pause();
event Unpause();
/**
* @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 any MSW owner to pause, triggers stopped state
*/
function pause()
onlyOwner
whenNotPaused
public
{
paused = true;
Pause();
}
/**
* @dev called by the MSW (all owners) to unpause, returns to normal state
*/
function unpause()
onlyWallet
whenPaused
public
{
paused = false;
Unpause();
}
}
// File: soltsice/contracts/BotManageable.sol
pragma solidity ^0.4.18;
/**
* @dev BotManaged contract provides a modifier isBot and methods to enable/disable bots.
*/
contract BotManageable is MultiOwnable {
uint256 constant MASK64 = 18446744073709551615;
// NB packing saves gas even in memory due to stack size
// struct StartEndTimeLayout {
// uint64 startTime;
// uint64 endTime;
// }
/**
* Bot addresses and their start/end times (two uint64 timestamps)
*/
mapping (address => uint128) internal botsStartEndTime;
event BotsStartEndTimeChange(address indexed _botAddress, uint64 _startTime, uint64 _endTime);
function BotManageable
(address _wallet)
public
MultiOwnable(_wallet)
{ }
/** Check if a caller is an active bot. */
modifier onlyBot() {
require (isBot(msg.sender));
_;
}
/** Check if a caller is an active bot or an owner or the wallet. */
modifier onlyBotOrOwner() {
require (isBot(msg.sender) || isOwner(msg.sender));
_;
}
/** Enable bot address. */
function enableBot(address _botAddress)
onlyWallet()
public
{
uint128 botLifetime = botsStartEndTime[_botAddress];
// cannot re-enable existing bot
require((botLifetime >> 64) == 0 && (botLifetime & MASK64) == 0);
botLifetime |= uint128(now) << 64;
botsStartEndTime[_botAddress] = botLifetime;
BotsStartEndTimeChange(_botAddress, uint64(botLifetime >> 64), uint64(botLifetime & MASK64));
}
/** Disable bot address. */
function disableBot(address _botAddress, uint64 _fromTimeStampSeconds)
onlyOwner()
public
{
uint128 botLifetime = botsStartEndTime[_botAddress];
// bot must have been enabled previously and not disabled before
require((botLifetime >> 64) > 0 && (botLifetime & MASK64) == 0);
botLifetime |= uint128(_fromTimeStampSeconds);
botsStartEndTime[_botAddress] = botLifetime;
BotsStartEndTimeChange(_botAddress, uint64(botLifetime >> 64), uint64(botLifetime & MASK64));
}
/** Operational contracts call this method to check if a caller is an approved bot. */
function isBot(address _botAddress)
public
constant
returns(bool)
{
return isBotAt(_botAddress, uint64(now));
}
// truffle-contract doesn't like method overloading, use a different name
function isBotAt(address _botAddress, uint64 _atTimeStampSeconds)
public
constant
returns(bool)
{
uint128 botLifetime = botsStartEndTime[_botAddress];
if ((botLifetime >> 64) == 0 || (botLifetime >> 64) > _atTimeStampSeconds) {
return false;
}
if ((botLifetime & MASK64) == 0) {
return true;
}
if (_atTimeStampSeconds < (botLifetime & MASK64)) {
return true;
}
return false;
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
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;
}
}
// File: contracts/Auction.sol
pragma solidity ^0.4.18;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function transfer(address to, uint256 value) public returns (bool);
}
contract AuctionHub is BotManageable {
using SafeMath for uint256;
/*
* Data structures
*/
struct TokenBalance {
address token;
uint256 value;
}
struct TokenRate {
uint256 value;
uint256 decimals;
}
struct BidderState {
uint256 etherBalance;
uint256 tokensBalanceInEther;
//uint256 managedBid;
TokenBalance[] tokenBalances;
uint256 etherBalanceInUsd; // (decimals = 2)
uint256 tokensBalanceInUsd; // (decimals = 2)
//uint256 managedBidInUsd;
}
struct ActionState {
uint256 endSeconds; // end time in Unix seconds, 1514160000 for Dec 25, 2017 (need to double check!)
uint256 maxTokenBidInEther; // ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡΠ½Π°Ρ ΡΡΠ°Π²ΠΊΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π² ΡΡΠΈΡΠ΅. ΠΡΠΌΠ°Ρ ΡΠ±ΡΠ°ΡΡ ΡΡΠΎ ΠΎΠ³ΡΠ°Π½ΠΈΡΠ΅Π½ΠΈΠ΅.
uint256 minPrice; // ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡΠ½Π°Ρ ΡΠ΅Π½Π° Π»ΠΎΡΠ° Π² WEI
uint256 highestBid;
// next 5 fields should be packed into one 32-bytes slot
address highestBidder;
//uint64 highestManagedBidder;
//bool allowManagedBids;
bool cancelled;
bool finalized;
uint256 maxTokenBidInUsd; // max token bid in usd (decimals = 2)
uint256 highestBidInUsd; // highest bid in usd (decimals = 2)
address highestBidderInUsd; // highest bidder address in usd (decimals = 2)
//uint64 highestManagedBidderInUsd; // highest manage bid in usd
mapping(address => BidderState) bidderStates;
bytes32 item;
}
/*
* Storage
*/
mapping(address => ActionState) public auctionStates;
mapping(address => TokenRate) public tokenRates;
// ether rate in usd
uint256 public etherRate;
/*
* Events
*/
event NewAction(address indexed auction, string item);
event Bid(address indexed auction, address bidder, uint256 totalBidInEther, uint256 indexed tokensBidInEther, uint256 totalBidInUsd, uint256 indexed tokensBidInUsd);
event TokenBid(address indexed auction, address bidder, address token, uint256 numberOfTokens);
//event ManagedBid(address indexed auction, uint64 bidder, uint256 bid, address knownManagedBidder);
//event NewHighestBidder(address indexed auction, address bidder, uint64 managedBidder, uint256 totalBid);
event NewHighestBidder(address indexed auction, address bidder, uint256 totalBid);
//event NewHighestBidderInUsd(address indexed auction, address bidder, uint64 managedBidderInUsd, uint256 totalBidInUsd);
event NewHighestBidderInUsd(address indexed auction, address bidder, uint256 totalBidInUsd);
event TokenRateUpdate(address indexed token, uint256 rate);
event EtherRateUpdate(uint256 rate); // in usdt
event Withdrawal(address indexed auction, address bidder, uint256 etherAmount, uint256 tokensBidInEther);
event Charity(address indexed auction, address bidder, uint256 etherAmount, uint256 tokensAmount); // not used
//event Finalized(address indexed auction, address highestBidder, uint64 highestManagedBidder, uint256 amount);
event Finalized(address indexed auction, address highestBidder, uint256 amount);
event FinalizedInUsd(address indexed auction, address highestBidderInUsd, uint256 amount);
event FinalizedTokenTransfer(address indexed auction, address token, uint256 tokensBidInEther);
event FinalizedEtherTransfer(address indexed auction, uint256 etherAmount);
event ExtendedEndTime(address indexed auction, uint256 newEndtime);
event Cancelled(address indexed auction);
/*
* Modifiers
*/
modifier onlyActive {
// NB this modifier also serves as check that an auction exists (otherwise endSeconds == 0)
ActionState storage auctionState = auctionStates[msg.sender];
require (now < auctionState.endSeconds && !auctionState.cancelled);
_;
}
modifier onlyBeforeEnd {
// NB this modifier also serves as check that an auction exists (otherwise endSeconds == 0)
ActionState storage auctionState = auctionStates[msg.sender];
require (now < auctionState.endSeconds);
_;
}
modifier onlyAfterEnd {
ActionState storage auctionState = auctionStates[msg.sender];
require (now > auctionState.endSeconds && auctionState.endSeconds > 0);
_;
}
modifier onlyNotCancelled {
ActionState storage auctionState = auctionStates[msg.sender];
require (!auctionState.cancelled);
_;
}
/*modifier onlyAllowedManagedBids {
ActionState storage auctionState = auctionStates[msg.sender];
require (auctionState.allowManagedBids);
_;
}*/
/*
* _rates are per big token (e.g. Ether vs. wei), i.e. number of wei per [number of tokens]*[10 ** decimals]
*/
function AuctionHub
(address _wallet, address[] _tokens, uint256[] _rates, uint256[] _decimals, uint256 _etherRate)
public
BotManageable(_wallet)
{
// make sender a bot to avoid an additional step
botsStartEndTime[msg.sender] = uint128(now) << 64;
require(_tokens.length == _rates.length);
require(_tokens.length == _decimals.length);
// save initial token list
for (uint i = 0; i < _tokens.length; i++) {
require(_tokens[i] != 0x0);
require(_rates[i] > 0);
ERC20Basic token = ERC20Basic(_tokens[i]);
tokenRates[token] = TokenRate(_rates[i], _decimals[i]);
emit TokenRateUpdate(token, _rates[i]);
}
// save ether rate in usd
require(_etherRate > 0);
etherRate = _etherRate;
emit EtherRateUpdate(_etherRate);
}
function stringToBytes32(string memory source) returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function createAuction(
uint _endSeconds,
uint256 _maxTokenBidInEther,
uint256 _minPrice,
string _item
//bool _allowManagedBids
)
onlyBot
public
returns (address)
{
require (_endSeconds > now);
require(_maxTokenBidInEther <= 1000 ether);
require(_minPrice > 0);
Auction auction = new Auction(this);
ActionState storage auctionState = auctionStates[auction];
auctionState.endSeconds = _endSeconds;
auctionState.maxTokenBidInEther = _maxTokenBidInEther;
// ΠΏΠΎΠΊΠ° Π½Π΅ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΡΡΡ Π² ΠΊΠΎΠ΄Π΅
auctionState.maxTokenBidInUsd = _maxTokenBidInEther.mul(etherRate).div(10 ** 2);
auctionState.minPrice = _minPrice;
//auctionState.allowManagedBids = _allowManagedBids;
string memory item = _item;
auctionState.item = stringToBytes32(item);
emit NewAction(auction, _item);
return address(auction);
}
function ()
payable
public
{
throw;
// It's charity!
// require(wallet.send(msg.value));
// Charity(0x0, msg.sender, msg.value, 0);
}
function bid(address _bidder, uint256 _value, address _token, uint256 _tokensNumber)
// onlyActive - inline check to reuse auctionState variable
public
returns (bool isHighest, bool isHighestInUsd)
{
ActionState storage auctionState = auctionStates[msg.sender];
// same as onlyActive modifier, but we already have a variable here
require (now < auctionState.endSeconds && !auctionState.cancelled);
BidderState storage bidderState = auctionState.bidderStates[_bidder];
uint256 totalBid;
uint256 totalBidInUsd;
if (_tokensNumber > 0) {
(totalBid, totalBidInUsd) = tokenBid(msg.sender, _bidder, _token, _tokensNumber);
}else {
require(_value > 0);
// NB if current token bid == 0 we still could have previous token bids
(totalBid, totalBidInUsd) = (bidderState.tokensBalanceInEther, bidderState.tokensBalanceInUsd);
}
uint256 etherBid = bidderState.etherBalance + _value;
// error "CompilerError: Stack too deep, try removing local variables"
bidderState.etherBalance = etherBid;
//totalBid = totalBid + etherBid + bidderState.managedBid;
totalBid = totalBid + etherBid;
//totalBidInUsd = totalBidInUsd + etherBidInUsd + bidderState.managedBidInUsd;
if (totalBid > auctionState.highestBid && totalBid >= auctionState.minPrice) {
auctionState.highestBid = totalBid;
auctionState.highestBidder = _bidder;
//auctionState.highestManagedBidder = 0;
emit NewHighestBidder(msg.sender, _bidder, totalBid);
if ((auctionState.endSeconds - now) < 1800) {
/*uint256 newEnd = now + 1800;
auctionState.endSeconds = newEnd;
ExtendedEndTime(msg.sender, newEnd);*/
//uint256 newEnd = now + 1800;
// ΡΠ±ΠΈΡΠ°Π΅ΠΌ ΡΠ²Π΅Π»ΠΈΡΠ΅Π½ΠΈΠ΅ Π²ΡΠ΅ΠΌΠ΅Π½ΠΈ Π°ΡΠΊΡΠΈΠΎΠ½Π° Π½Π° 30 ΠΌΠΈΠ½. ΠΏΡΠΈ Π²ΡΡΠΎΠΊΠΎΠΉ ΡΡΠ°Π²ΠΊΠΈ Π² Ether
/*auctionState.endSeconds = now + 1800;
ExtendedEndTime(msg.sender, auctionState.endSeconds);*/
}
isHighest = true;
}
/*
uint256 etherBidInUsd = bidderState.etherBalanceInUsd + _value.mul(etherRate);
bidderState.etherBalanceInUsd = etherBidInUsd;
totalBidInUsd = totalBidInUsd + etherBidInUsd;*/
uint256 etherBidInUsd = bidderState.etherBalanceInUsd + _value.mul(etherRate).div(10 ** 2);
bidderState.etherBalanceInUsd = etherBidInUsd;
totalBidInUsd = totalBidInUsd + etherBidInUsd;
if (totalBidInUsd > auctionState.highestBidInUsd && totalBidInUsd >= auctionState.minPrice.mul(etherRate).div(10 ** 2)) {
auctionState.highestBidInUsd = totalBidInUsd;
auctionState.highestBidderInUsd = _bidder;
//auctionState.highestManagedBidderInUsd = 0;
emit NewHighestBidderInUsd(msg.sender, _bidder, totalBidInUsd);
if ((auctionState.endSeconds - now) < 1800) {
//uint256 newEndUsd = now + 1800;
//auctionState.endSeconds = newEndUsd;
//ExtendedEndTime(msg.sender, newEndUsd);
//uint256 newEndUsd = now + 1800;
auctionState.endSeconds = now + 1800;
emit ExtendedEndTime(msg.sender, auctionState.endSeconds);
}
isHighestInUsd = true;
}
emit Bid(msg.sender, _bidder, totalBid, totalBid - etherBid, totalBidInUsd, totalBidInUsd - etherBidInUsd);
return (isHighest, isHighestInUsd);
}
function tokenBid(address _auction, address _bidder, address _token, uint256 _tokensNumber)
internal
returns (uint256 tokenBid, uint256 tokenBidInUsd)
{
// NB actual token transfer happens in auction contracts, which owns both ether and tokens
// This Hub contract is for accounting
ActionState storage auctionState = auctionStates[_auction];
BidderState storage bidderState = auctionState.bidderStates[_bidder];
uint256 totalBid = bidderState.tokensBalanceInEther;
uint256 totalBidInUsd = bidderState.tokensBalanceInUsd;
TokenRate storage tokenRate = tokenRates[_token];
require(tokenRate.value > 0);
// find token index
uint256 index = bidderState.tokenBalances.length;
for (uint i = 0; i < index; i++) {
if (bidderState.tokenBalances[i].token == _token) {
index = i;
break;
}
}
// array was empty/token not found - push empty to the end
if (index == bidderState.tokenBalances.length) {
bidderState.tokenBalances.push(TokenBalance(_token, _tokensNumber));
} else {
// safe math is already in transferFrom
bidderState.tokenBalances[index].value += _tokensNumber;
}
//totalBid = totalBid + _tokensNumber.mul(tokenRate.value).div(10 ** tokenRate.decimals);
totalBid = calcTokenTotalBid(totalBid, _token, _tokensNumber);
//totalBidInUsd = totalBidInUsd + _tokensNumber.mul(tokenRate.value).mul(etherRate).div(10 ** 2).div(10 ** tokenRate.decimals);
totalBidInUsd = calcTokenTotalBidInUsd(totalBidInUsd, _token, _tokensNumber);
// !Note! Π·Π°ΡΠ΅ΠΌ ΡΡΡ ΠΎΠ³ΡΠ°Π½ΠΈΡΠΈΠ²Π°ΡΡ ΠΌΠ°ΠΊΡ ΡΡΠ°Π²ΠΊΡ ΡΠΎΠΊΠ΅Π½Π° ΡΡΠΈΡΠΎΠΌ
//require(totalBid <= auctionState.maxTokenBidInEther);
bidderState.tokensBalanceInEther = totalBid;
bidderState.tokensBalanceInUsd = totalBidInUsd;
//TokenBid(_auction, _bidder, _token, _tokensNumber);
//emit TokenBid(_auction, _bidder, _token, _tokensNumber, _tokensNumber.mul(tokenRate.value).div(10 ** tokenRate.decimals), _tokensNumber.mul(tokenRate.value).mul(etherRate).div(10 ** 2).div(10 ** tokenRate.decimals));
emit TokenBid(_auction, _bidder, _token, _tokensNumber);
return (totalBid, totalBidInUsd);
}
function calcTokenTotalBid(uint256 totalBid, address _token, uint256 _tokensNumber)
internal
//returns(uint256 _totalBid, uint256 _bidInEther){
returns(uint256 _totalBid){
TokenRate storage tokenRate = tokenRates[_token];
// tokenRate.value is for a whole/big token (e.g. ether vs. wei) but _tokensNumber is in small/wei tokens, need to divide by decimals
uint256 bidInEther = _tokensNumber.mul(tokenRate.value).div(10 ** tokenRate.decimals);
//totalBid = totalBid + _tokensNumber.mul(tokenRate.value).div(10 ** tokenRate.decimals);
totalBid += bidInEther;
//return (totalBid, bidInEther);
return totalBid;
}
function calcTokenTotalBidInUsd(uint256 totalBidInUsd, address _token, uint256 _tokensNumber)
internal
returns(uint256 _totalBidInUsd){
TokenRate storage tokenRate = tokenRates[_token];
uint256 bidInUsd = _tokensNumber.mul(tokenRate.value).mul(etherRate).div(10 ** 2).div(10 ** tokenRate.decimals);
//totalBidInUsd = totalBidInUsd + _tokensNumber.mul(tokenRate.value).mul(etherRate).div(10 ** 2).div(10 ** tokenRate.decimals);
totalBidInUsd += bidInUsd;
return totalBidInUsd;
}
function totalDirectBid(address _auction, address _bidder)
view
public
returns (uint256 _totalBid)
{
ActionState storage auctionState = auctionStates[_auction];
BidderState storage bidderState = auctionState.bidderStates[_bidder];
return bidderState.tokensBalanceInEther + bidderState.etherBalance;
}
function totalDirectBidInUsd(address _auction, address _bidder)
view
public
returns (uint256 _totalBidInUsd)
{
ActionState storage auctionState = auctionStates[_auction];
BidderState storage bidderState = auctionState.bidderStates[_bidder];
return bidderState.tokensBalanceInUsd + bidderState.etherBalanceInUsd;
}
function setTokenRate(address _token, uint256 _tokenRate)
onlyBot
public
{
TokenRate storage tokenRate = tokenRates[_token];
require(tokenRate.value > 0);
tokenRate.value = _tokenRate;
emit TokenRateUpdate(_token, _tokenRate);
}
function setEtherRate(uint256 _etherRate)
onlyBot
public
{
require(_etherRate > 0);
etherRate = _etherRate;
emit EtherRateUpdate(_etherRate);
}
function withdraw(address _bidder)
public
returns (bool success)
{
ActionState storage auctionState = auctionStates[msg.sender];
BidderState storage bidderState = auctionState.bidderStates[_bidder];
bool sent;
// anyone could withdraw at any time except the highest bidder
// if cancelled, the highest bidder could withdraw as well
//require((_bidder != auctionState.highestBidder) || auctionState.cancelled);
require((_bidder != auctionState.highestBidderInUsd) || auctionState.cancelled);
uint256 tokensBalanceInEther = bidderState.tokensBalanceInEther;
uint256 tokensBalanceInUsd = bidderState.tokensBalanceInUsd;
if (bidderState.tokenBalances.length > 0) {
for (uint i = 0; i < bidderState.tokenBalances.length; i++) {
uint256 tokenBidValue = bidderState.tokenBalances[i].value;
if (tokenBidValue > 0) {
bidderState.tokenBalances[i].value = 0;
sent = Auction(msg.sender).sendTokens(bidderState.tokenBalances[i].token, _bidder, tokenBidValue);
require(sent);
}
}
bidderState.tokensBalanceInEther = 0;
bidderState.tokensBalanceInUsd = 0;
} else {
require(tokensBalanceInEther == 0);
}
uint256 etherBid = bidderState.etherBalance;
if (etherBid > 0) {
bidderState.etherBalance = 0;
bidderState.etherBalanceInUsd = 0;
sent = Auction(msg.sender).sendEther(_bidder, etherBid);
require(sent);
}
emit Withdrawal(msg.sender, _bidder, etherBid, tokensBalanceInEther);
return true;
}
function finalize()
// onlyNotCancelled - inline check to reuse auctionState variable
// onlyAfterEnd - inline check to reuse auctionState variable
public
returns (bool)
{
ActionState storage auctionState = auctionStates[msg.sender];
// same as onlyNotCancelled+onlyAfterEnd modifiers, but we already have a variable here
require (!auctionState.finalized && now > auctionState.endSeconds && auctionState.endSeconds > 0 && !auctionState.cancelled);
// Π΅ΡΠ»ΠΈ Π΅ΡΡΡ Ρ
ΠΎΡΡ ΠΎΠ΄Π½Π° ΡΡΠ°Π²ΠΊΠ°
if (auctionState.highestBidder != address(0)) {
bool sent;
BidderState storage bidderState = auctionState.bidderStates[auctionState.highestBidder];
uint256 tokensBalanceInEther = bidderState.tokensBalanceInEther;
uint256 tokensBalanceInUsd = bidderState.tokensBalanceInUsd;
if (bidderState.tokenBalances.length > 0) {
for (uint i = 0; i < bidderState.tokenBalances.length; i++) {
uint256 tokenBid = bidderState.tokenBalances[i].value;
if (tokenBid > 0) {
bidderState.tokenBalances[i].value = 0;
sent = Auction(msg.sender).sendTokens(bidderState.tokenBalances[i].token, wallet, tokenBid);
require(sent);
emit FinalizedTokenTransfer(msg.sender, bidderState.tokenBalances[i].token, tokenBid);
}
}
bidderState.tokensBalanceInEther = 0;
bidderState.tokensBalanceInUsd = 0;
} else {
require(tokensBalanceInEther == 0);
}
uint256 etherBid = bidderState.etherBalance;
if (etherBid > 0) {
bidderState.etherBalance = 0;
bidderState.etherBalanceInUsd = 0;
sent = Auction(msg.sender).sendEther(wallet, etherBid);
require(sent);
emit FinalizedEtherTransfer(msg.sender, etherBid);
}
}
auctionState.finalized = true;
emit Finalized(msg.sender, auctionState.highestBidder, auctionState.highestBid);
emit FinalizedInUsd(msg.sender, auctionState.highestBidderInUsd, auctionState.highestBidInUsd);
return true;
}
function cancel()
// onlyActive - inline check to reuse auctionState variable
public
returns (bool success)
{
ActionState storage auctionState = auctionStates[msg.sender];
// same as onlyActive modifier, but we already have a variable here
require (now < auctionState.endSeconds && !auctionState.cancelled);
auctionState.cancelled = true;
emit Cancelled(msg.sender);
return true;
}
}
contract Auction {
AuctionHub public owner;
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier onlyBot {
require(owner.isBot(msg.sender));
_;
}
modifier onlyNotBot {
require(!owner.isBot(msg.sender));
_;
}
function Auction(
address _owner
)
public
{
require(_owner != address(0x0));
owner = AuctionHub(_owner);
}
function ()
payable
public
{
owner.bid(msg.sender, msg.value, 0x0, 0);
}
function bid(address _token, uint256 _tokensNumber)
payable
public
returns (bool isHighest, bool isHighestInUsd)
{
if (_token != 0x0 && _tokensNumber > 0) {
require(ERC20Basic(_token).transferFrom(msg.sender, this, _tokensNumber));
}
return owner.bid(msg.sender, msg.value, _token, _tokensNumber);
}
function sendTokens(address _token, address _to, uint256 _amount)
onlyOwner
public
returns (bool)
{
return ERC20Basic(_token).transfer(_to, _amount);
}
function sendEther(address _to, uint256 _amount)
onlyOwner
public
returns (bool)
{
return _to.send(_amount);
}
function withdraw()
public
returns (bool success)
{
return owner.withdraw(msg.sender);
}
function finalize()
onlyBot
public
returns (bool)
{
return owner.finalize();
}
function cancel()
onlyBot
public
returns (bool success)
{
return owner.cancel();
}
function totalDirectBid(address _bidder)
public
view
returns (uint256)
{
return owner.totalDirectBid(this, _bidder);
}
function totalDirectBidInUsd(address _bidder)
public
view
returns (uint256)
{
return owner.totalDirectBidInUsd(this, _bidder);
}
function maxTokenBidInEther()
public
view
returns (uint256)
{
//var (,maxTokenBidInEther,,,,,,,,,,,) = owner.auctionStates(this);
//var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,allowManagedBids,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,bidderStates) = owner.auctionStates(this);
//(endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
var (,maxTokenBidInEther,,,,,,,,,) = owner.auctionStates(this);
return maxTokenBidInEther;
}
function maxTokenBidInUsd()
public
view
returns (uint256)
{
//var (,,,,,,,,,,maxTokenBidInUsd,,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
return maxTokenBidInUsd;
}
function endSeconds()
public
view
returns (uint256)
{
//var (endSeconds,,,,,,,,,) = owner.auctionStates(this);
//(endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
var (endSeconds,,,,,,,,,,) = owner.auctionStates(this);
return endSeconds;
}
function item()
public
view
returns (string)
{
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
//var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,allowManagedBids,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,bidderStates,item) = owner.auctionStates(this);
bytes memory bytesArray = new bytes(32);
for (uint256 i; i < 32; i++) {
bytesArray[i] = item[i];
}
return string(bytesArray);
}
function minPrice()
public
view
returns (uint256)
{
//var (,,minPrice,,,,,,,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
return minPrice;
}
function cancelled()
public
view
returns (bool)
{
//var (,,,,,,cancelled,,,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
return cancelled;
}
function finalized()
public
view
returns (bool)
{
//var (,,,,,,,finalized,,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
return finalized;
}
function highestBid()
public
view
returns (uint256)
{
//var (,,,highestBid,,,,,,,,,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
// ,,,,,,,,,,,,
// ,,,highestBid,,,,,,,,,
return highestBid;
}
function highestBidInUsd()
public
view
returns (uint256)
{
//var (,,,,,,,,,,,highestBidInUsd,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
// ,,,,,,,,,,,,
return highestBidInUsd;
}
function highestBidder()
public
view
returns (address)
{
//var (,,,,highestBidder,,,,,) = owner.auctionStates(this);
//var (,,,,highestBidder,,,,,,,,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
// ,,,,highestBidder,,,,,,,,
return highestBidder;
}
function highestBidderInUsd()
public
view
returns (address)
{
//var (,,,,highestBidder,,,,,) = owner.auctionStates(this);
//var (,,,,,,,,,,,,highestBidderInUsd) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
// ,,,,,,,,,,,,
return highestBidderInUsd;
}
/*function highestManagedBidder()
public
view
returns (uint64)
{
//var (,,,,,highestManagedBidder,,,,) = owner.auctionStates(this);
var (,,,,,highestManagedBidder,,,,,,,) = owner.auctionStates(this);
// ,,,,,highestManagedBidder,,,,,,,
return highestManagedBidder;
}*/
/*function allowManagedBids()
public
view
returns (bool)
{
//var (,,,,,,allowManagedBids,,,) = owner.auctionStates(this);
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,allowManagedBids,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,bidderStates) = owner.auctionStates(this);
return allowManagedBids;
}*/
// mapping(address => uint256) public etherBalances;
// mapping(address => uint256) public tokenBalances;
// mapping(address => uint256) public tokenBalancesInEther;
// mapping(address => uint256) public managedBids;
// bool allowManagedBids;
}
// File: contracts/TokenStarsAuction.sol
pragma solidity ^0.4.18;
contract TokenStarsAuctionHub is AuctionHub {
//real
address public ACE = 0x06147110022B768BA8F99A8f385df11a151A9cc8;
//renkeby
//address public ACE = 0xa0813ad2e1124e0779dc04b385f5229776dcbba8;
//real
address public TEAM = 0x1c79ab32C66aCAa1e9E81952B8AAa581B43e54E7;
// rinkeby
//address public TEAM = 0x10b882e7da9ef31ef6e0e9c4c5457dfaf8dd9a24;
//address public wallet = 0x963dF7904cF180aB2C033CEAD0be8687289f05EC;
address public wallet = 0x0C9b07209750BbcD1d1716DA52B591f371eeBe77;//
address[] public tokens = [ACE, TEAM];
// ACE = 0.01 ETH;
// TEAM = 0,002 ETH
uint256[] public rates = [10000000000000000, 2000000000000000];
uint256[] public decimals = [0, 4];
// ETH = $138.55
uint256 public etherRate = 13855;
function TokenStarsAuctionHub()
public
AuctionHub(wallet, tokens, rates, decimals, etherRate)
{
}
function createAuction(
address _wallet,
uint _endSeconds,
uint256 _maxTokenBidInEther,
uint256 _minPrice,
string _item
//bool _allowManagedBids
)
onlyBot
public
returns (address)
{
require (_endSeconds > now);
require(_maxTokenBidInEther <= 1000 ether);
require(_minPrice > 0);
Auction auction = new TokenStarsAuction(this);
ActionState storage auctionState = auctionStates[auction];
auctionState.endSeconds = _endSeconds;
auctionState.maxTokenBidInEther = _maxTokenBidInEther;
auctionState.minPrice = _minPrice;
//auctionState.allowManagedBids = _allowManagedBids;
string memory item = _item;
auctionState.item = stringToBytes32(item);
NewAction(auction, _item);
return address(auction);
}
}
contract TokenStarsAuctionHubMock is AuctionHub {
uint256[] public rates = [2400000000000000, 2400000000000000];
uint256[] public decimals = [0, 4];
uint256 public etherRate = 13855;
function TokenStarsAuctionHubMock(address _wallet, address[] _tokens)
public
AuctionHub(_wallet, _tokens, rates, decimals, etherRate)
{
}
function createAuction(
uint _endSeconds,
uint256 _maxTokenBidInEther,
uint256 _minPrice,
string _item
//bool _allowManagedBids
)
onlyBot
public
returns (address)
{
require (_endSeconds > now);
require(_maxTokenBidInEther <= 1000 ether);
require(_minPrice > 0);
Auction auction = new TokenStarsAuction(this);
ActionState storage auctionState = auctionStates[auction];
auctionState.endSeconds = _endSeconds;
auctionState.maxTokenBidInEther = _maxTokenBidInEther;
auctionState.maxTokenBidInUsd = _maxTokenBidInEther.mul(etherRate).div(10 ** 2);
auctionState.minPrice = _minPrice;
//auctionState.allowManagedBids = _allowManagedBids;
string memory item = _item;
auctionState.item = stringToBytes32(item);
NewAction(auction, _item);
return address(auction);
}
}
contract TokenStarsAuction is Auction {
function TokenStarsAuction(
address _owner)
public
Auction(_owner)
{
}
function bidAce(uint256 _tokensNumber)
payable
public
returns (bool isHighest, bool isHighestInUsd)
{
return super.bid(TokenStarsAuctionHub(owner).ACE(), _tokensNumber);
}
function bidTeam(uint256 _tokensNumber)
payable
public
returns (bool isHighest, bool isHighestInUsd)
{
return super.bid(TokenStarsAuctionHub(owner).TEAM(), _tokensNumber);
}
} | var (,,minPrice,,,,,,,) = owner.auctionStates(this); | function minPrice()
public
view
returns (uint256)
{
var (endSeconds,maxTokenBidInEther,minPrice,highestBid,highestBidder,cancelled,finalized,maxTokenBidInUsd,highestBidInUsd,highestBidderInUsd,item) = owner.auctionStates(this);
return minPrice;
}
| 12,904,586 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../ShareholderRegistry/IShareholderRegistry.sol";
import "./IVoting.sol";
contract VotingBase {
IShareholderRegistry _shareholderRegistry;
IERC20Upgradeable _token;
bytes32 private _contributorRole;
// TODO Turn into struct
mapping(address => address) _delegates;
mapping(address => uint256) _votingPower;
mapping(address => uint256) _delegators;
uint256 _totalVotingPower;
event DelegateChanged(
address indexed delegator,
address currentDelegate,
address newDelegate
);
event DelegateVotesChanged(
address indexed account,
uint256 oldVotingPower,
uint256 newVotingPower
);
modifier onlyToken() {
require(
msg.sender == address(_token),
"Voting: only Token contract can call this method."
);
_;
}
function canVote(address account) public view returns (bool) {
return getDelegate(account) != address(0);
}
function _setToken(IERC20Upgradeable token) internal {
_token = token;
}
function _setShareholderRegistry(IShareholderRegistry shareholderRegistry)
internal
{
_shareholderRegistry = shareholderRegistry;
_contributorRole = _shareholderRegistry.CONTRIBUTOR_STATUS();
}
function _beforeRemoveContributor(address account) internal {
address delegated = getDelegate(account);
if (delegated == account) {
_beforeDelegate(account);
} else {
_delegate(account, account);
}
delete _delegates[account];
uint256 individualVotingPower = _token.balanceOf(account);
if (individualVotingPower > 0) {
_moveVotingPower(account, address(0), individualVotingPower);
}
}
function _afterAddContributor(address account) internal {
_delegate(account, account);
}
/// @dev Hook to be called by the companion token upon token transfer
/// @notice Only the companion token can call this method
/// @notice The voting power transfer logic relies on the correct usage of this hook from the companion token
/// @param from The sender's address
/// @param to The receiver's address
/// @param amount The amount sent
function afterTokenTransfer(
address from,
address to,
uint256 amount
) external onlyToken {
_moveVotingPower(getDelegate(from), getDelegate(to), amount);
}
/// @dev Returns the account's current delegate
/// @param account The account whose delegate is requested
/// @return Account's voting power
function getDelegate(address account) public view returns (address) {
return _delegates[account];
}
/// @dev Returns the amount of valid votes for a given address
/// @notice An address that is not a contributor, will have always 0 voting power
/// @notice An address that has not delegated at least itself, will have always 0 voting power
/// @param account The account whose voting power is requested
/// @return Account's voting power
function getVotingPower(address account) public view returns (uint256) {
return _votingPower[account];
}
/// @dev Returns the total amount of valid votes
/// @notice It's the sum of all tokens owned by contributors who has been at least delegated to themselves
/// @return Total voting power
function getTotalVotingPower() public view returns (uint256) {
return _totalVotingPower;
}
/// @dev Allows sender to delegate another address for voting
/// @notice The first address to be delegated must be the sender itself
/// @notice Sub-delegation is not allowed
/// @param newDelegate Destination address of module transaction.
function delegate(address newDelegate) public {
_delegate(msg.sender, newDelegate);
}
function _delegate(address delegator, address newDelegate) internal {
address currentDelegate = getDelegate(delegator);
address newDelegateDelegate = getDelegate(newDelegate);
uint256 countDelegatorDelegators = _delegators[delegator];
// pre conditions
// - participants are contributors
// (this automatically enforces also that the address is not 0)
require(
_shareholderRegistry.isAtLeast(_contributorRole, delegator),
"Voting: only contributors can delegate."
);
require(
_shareholderRegistry.isAtLeast(_contributorRole, newDelegate),
"Voting: only contributors can be delegated."
);
// - no sub delegation allowed
require(
newDelegate == newDelegateDelegate || delegator == newDelegate,
"Voting: new delegate is not self delegated"
);
require(
countDelegatorDelegators == 0 || delegator == newDelegate,
"Voting: delegator is already delegated"
);
// - first delegate should be self
require(
(currentDelegate == address(0) && delegator == newDelegate) ||
currentDelegate != address(0),
"Voting: first delegate should be self"
);
// - no double delegation
require(
newDelegate != currentDelegate,
"Voting: new delegate equal to old delegate"
);
_beforeDelegate(delegator);
uint256 delegatorBalance = _token.balanceOf(delegator);
_delegates[delegator] = newDelegate;
if (delegator != newDelegate && newDelegate != address(0)) {
_delegators[newDelegate]++;
}
if (delegator != currentDelegate && currentDelegate != address(0)) {
_delegators[currentDelegate]--;
}
emit DelegateChanged(delegator, currentDelegate, newDelegate);
_moveVotingPower(currentDelegate, newDelegate, delegatorBalance);
}
function _moveVotingPower(
address from,
address to,
uint256 amount
) private {
if (from != to && amount > 0) {
if (from != address(0)) {
_beforeMoveVotingPower(from);
uint256 oldVotingPower = _votingPower[from];
_votingPower[from] = oldVotingPower - amount;
emit DelegateVotesChanged(
from,
oldVotingPower,
_votingPower[from]
);
} else {
_beforeUpdateTotalVotingPower();
_totalVotingPower += amount;
}
if (to != address(0)) {
_beforeMoveVotingPower(to);
uint256 oldVotingPower = _votingPower[to];
_votingPower[to] = oldVotingPower + amount;
emit DelegateVotesChanged(to, oldVotingPower, _votingPower[to]);
} else {
_beforeUpdateTotalVotingPower();
_totalVotingPower -= amount;
}
}
}
function _beforeDelegate(address delegator) internal virtual {}
function _beforeMoveVotingPower(address account) internal virtual {}
function _beforeUpdateTotalVotingPower() internal virtual {}
}
| Returns the amount of valid votes for a given address An address that is not a contributor, will have always 0 voting power An address that has not delegated at least itself, will have always 0 voting power account The account whose voting power is requested return Account's voting power | function getVotingPower(address account) public view returns (uint256) {
return _votingPower[account];
}
| 5,400,869 |
/**
*Submitted for verification at Etherscan.io on 2020-08-15
*/
pragma solidity ^0.5.15;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
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));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
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 decimals() external view returns (uint);
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);
}
interface Yam {
function getReward() external;
function stake(uint) external;
function balanceOf(address) external view returns (uint);
function exit() external;
}
interface UniswapRouter {
function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts);
function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external returns (uint amountA, uint amountB, uint liquidity);
function removeLiquidity(address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB);
}
contract YamAutomation {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address constant public yam = address(0x0e2298E3B3390e3b945a5456fBf59eCc3f55DA16);
address constant public ycrv = address(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8);
address constant public univ2 = address(0x2C7a51A357d5739C5C74Bf3C96816849d2c9F726);
address constant public stakingpool = address(0xADDBCd6A68BFeb6E312e82B30cE1EB4a54497F4c);
address constant public unirouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address constant public admin = address(0x341722BA06a760d24b487e68Dc93679339A0cc2F);
function harvest() external {
//Harvest YAM's
Yam(stakingpool).getReward();
//Swap 50% of YAMs to yCRV
IERC20(yam).safeApprove(unirouter, uint(-1));
address[] memory path2 = new address[](2);
path2[0] = address(yam);
path2[1] = address(ycrv);
UniswapRouter(unirouter).swapExactTokensForTokens(
IERC20(yam).balanceOf(msg.sender).div(2),
0,
path2,
msg.sender,
now.add(1800)
);
//Add liquidity
IERC20(ycrv).safeApprove(unirouter, uint(-1));
UniswapRouter(unirouter).addLiquidity(
address(yam),
address(ycrv),
IERC20(yam).balanceOf(msg.sender),
IERC20(ycrv).balanceOf(msg.sender),
0,
0,
msg.sender,
now.add(1800)
);
//Stake all UNI-V2
IERC20(univ2).safeApprove(stakingpool, IERC20(univ2).balanceOf(msg.sender));
Yam(stakingpool).stake(IERC20(univ2).balanceOf(msg.sender));
}
function withdrawToken(IERC20 asset) public {
require(msg.sender == admin, "no admin");
asset.safeTransfer(admin, asset.balanceOf(address(this)));
}
//function withdrawETH(uint amount) public {
// require(msg.sender == admin, "no admin");
// admin.transfer(amount);
//}
function exitPool() external {
//harvest and unstake
Yam(stakingpool).exit();
//swap univ2 LPToken to YAM / yCRV
IERC20(yam).safeApprove(unirouter, uint(-1));
IERC20(ycrv).safeApprove(unirouter, uint(-1));
UniswapRouter(unirouter).removeLiquidity(
address(yam),
address(ycrv),
IERC20(univ2).balanceOf(msg.sender),
0,
0,
msg.sender,
now.add(1800)
);
}
} | harvest and unstakeswap univ2 LPToken to YAM / yCRV | function exitPool() external {
Yam(stakingpool).exit();
IERC20(yam).safeApprove(unirouter, uint(-1));
IERC20(ycrv).safeApprove(unirouter, uint(-1));
UniswapRouter(unirouter).removeLiquidity(
address(yam),
address(ycrv),
IERC20(univ2).balanceOf(msg.sender),
0,
0,
msg.sender,
now.add(1800)
);
}
| 13,054,786 |
./full_match/1313161555/0x5A824f809B300bEeC20eB5b931747726Bd2afdd2/sources/contracts/helpers/ITemporarilyPausable.sol | Interface for the TemporarilyPausable helper./ | interface ITemporarilyPausable {
event PausedStateChanged(bool paused);
function getPausedState()
external
view
returns (bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime);
}
| 7,095,885 |
pragma solidity >=0.4.9 <0.6.0;
contract r {
function s() public view {}
}
contract a is r {
uint x = 1;
function getX() public view returns (uint) {
return x;
}
}
contract b is a {
uint y = 2;
uint x = 3;
function getY(uint z, bool r) public returns (uint) {
return y++;
}
function getY(string storage n) internal view returns (uint) { return 10; }
}
contract c is b {
string x;
function d() public returns (uint a, uint b) {
//d();
//sha3("bla");
address payable o = msg.sender;
o.call.gas(200000).value(address(this).balance)(abi.encode("pay()"));
//x++;
getY(x);
a = getX() + getY(1, false);
b = getX() + getY(x);
}
}
| d();sha3("bla");x++; | function d() public returns (uint a, uint b) {
address payable o = msg.sender;
o.call.gas(200000).value(address(this).balance)(abi.encode("pay()"));
getY(x);
a = getX() + getY(1, false);
b = getX() + getY(x);
}
| 12,591,743 |
// Sources flattened with hardhat v2.9.3 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
// 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);
}
// File @openzeppelin/contracts/token/ERC1155/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
// File @openzeppelin/contracts/token/ERC1155/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
/**
* @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.
*
* NOTE: 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.
*
* NOTE: 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);
}
// File @openzeppelin/contracts/token/ERC1155/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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/utils/[email protected]
// 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/utils/introspection/[email protected]
// 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/access/[email protected]
// 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 contracts/kabuto.sol
pragma solidity ^0.8.0;
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 initialize(Counter storage counter, uint256 _value) internal {
counter._value = _value;
}
function reset(Counter storage counter) internal {
counter._value = 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 These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
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) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
interface Shiburai {
function balanceOf(address account) external view returns (uint256);
}
interface Kimono {
function onMintingWithKimono(address _samurai) external;
function canClaimWithKimono(address _samurai) external view returns (bool);
function kimonosMintedFor(address _samurai)
external
view
returns (uint256[] memory);
function useKimonoDiscount(address _samurai) external returns (bool);
function usedKimonoDiscounts(address _samurai)
external
view
returns (uint256);
}
interface SHIBURAIVESTKEEPER {
function remainingVestedBalance(address _address)
external
view
returns (uint256);
}
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract Kabuto is ERC165, IERC1155, IERC1155MetadataURI, Ownable {
using Strings for uint256;
using Address for address;
using Counters for Counters.Counter;
uint256 public constant FIRST_GIFTS = 51;
uint256 public constant MAX_SUPPLY_PLUS_ONE = 302;
bytes32 public merkleRoot =
0x99f984a0a18cb56a8fa7927b3d847c11dbfc1ea22c551fd765827bfc55f98679;
Counters.Counter private _tokenIdCounter;
Counters.Counter private _giftedIdCounter;
address public kimono;
address public shiburai = 0x275EB4F541b372EfF2244A444395685C32485368;
address public vestKeeper = 0x9f83c3ddd69CCb205eaA2bac013E6851d59E7B43;
address[MAX_SUPPLY_PLUS_ONE] internal _owners; // start counting at 1
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
mapping(address => bool) public rewardClaimed;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
uint256 public price = 0.3 ether;
uint256 public shiburaiDiscountAtAmount = 4000 * 10**9;
// Track mints per wallet to restrict to a given number
mapping(address => uint256) private _mintsPerWallet;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Tracking mint status
bool private _paused = true;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev See {_setURI}.
*/
constructor(
string memory uri_,
string memory name_,
string memory symbol_,
address _kimono
) {
_tokenIdCounter.initialize(FIRST_GIFTS);
name = name_;
symbol = symbol_;
_setURI(uri_);
kimono = _kimono;
}
function setKimono(address _kimono) public onlyOwner {
kimono = _kimono;
}
function setVestKeeper(address _vestKeeper) public onlyOwner {
vestKeeper = _vestKeeper;
}
function claimWithKimono() public returns (uint256) {
require(tx.origin == msg.sender, "Kabuto: Samurai only.");
require(
_tokenIdCounter.current() + 1 < MAX_SUPPLY_PLUS_ONE,
"Kabuto: Max supply exceeded"
);
Kimono(kimono).onMintingWithKimono(msg.sender);
_tokenIdCounter.increment();
uint256 nextTokenId = _tokenIdCounter.current();
_mint(_msgSender(), nextTokenId, 1, "");
return nextTokenId;
}
function setShiburaiDiscountAtAmount(
address _shiburai,
uint256 _shiburaiDiscountAtAmount
) external onlyOwner {
shiburai = _shiburai;
shiburaiDiscountAtAmount = _shiburaiDiscountAtAmount;
}
function priceToPay(address _samurai, uint256 amount)
public
view
returns (uint256)
{
if (
Shiburai(shiburai).balanceOf(_samurai) +
SHIBURAIVESTKEEPER(vestKeeper).remainingVestedBalance(
_samurai
) >=
shiburaiDiscountAtAmount
) {
return (price / 2) * amount;
} else {
uint256 _current = _tokenIdCounter.current() - FIRST_GIFTS;
uint256 toPay;
for (uint256 i; i < amount; i++) {
if (_current + i < 25) {
toPay += price / 2;
} else {
uint256 usedKimonoDiscounts;
if (Kimono(kimono).kimonosMintedFor(_samurai).length == 0) {
usedKimonoDiscounts = 3;
} else {
usedKimonoDiscounts = Kimono(kimono)
.usedKimonoDiscounts(_samurai);
}
for (uint256 j = i; j < amount; j++) {
if (usedKimonoDiscounts + (j - i) < 3) {
toPay += price / 2;
} else {
toPay += price;
}
}
break;
}
}
return toPay;
}
}
function canClaimWithKimono(address _samurai) external view returns (bool) {
return Kimono(kimono).canClaimWithKimono(_samurai);
}
function verifyClaim(
address _account,
uint256 _amount,
bytes32[] calldata _merkleProof
) public view returns (bool) {
bytes32 node = keccak256(abi.encodePacked(_amount, _account));
return MerkleProof.verify(_merkleProof, merkleRoot, node);
}
function claim(uint256 _amount, bytes32[] calldata _merkleProof) public {
require(tx.origin == msg.sender, "Kabuto: Samurai only.");
require(_paused == false, "Kabuto: Minting is paused");
require(
verifyClaim(_msgSender(), _amount, _merkleProof),
"Kabuto: Not eligible for a claim"
);
require(!rewardClaimed[_msgSender()], "Kabuto: Reward already claimed");
rewardClaimed[_msgSender()] = true;
_giftedIdCounter.increment();
uint256 nextTokenId = _giftedIdCounter.current();
require(nextTokenId <= FIRST_GIFTS, "Kabuto: No more rewards");
_mint(_msgSender(), nextTokenId, 1, "");
for (uint256 i = 1; i < _amount; i++) {
if (_giftedIdCounter.current() + 1 > FIRST_GIFTS) {
break;
} else {
_giftedIdCounter.increment();
_mint(_msgSender(), _giftedIdCounter.current(), 1, "");
}
}
}
/**
* Sets a new mint price for the public mint.
*/
function setMintPrice(uint256 newPrice) public onlyOwner {
price = newPrice;
}
/**
* Returns the paused state for the contract.
*/
function isPaused() public view returns (bool) {
return _paused;
}
/**
* Sets the paused state for the contract.
*
* Pausing the contract also stops all minting options.
*/
function setPaused(bool paused_) public onlyOwner {
_paused = paused_;
}
/**
* @dev See {_setURI}
*/
function setUri(string memory newUri) public onlyOwner {
_setURI(newUri);
}
/**
* Public Mint
*/
function mintPublic(uint256 amount) public payable {
require(tx.origin == msg.sender, "Katana: Samurai only.");
uint256 totalPrice = priceToPay(msg.sender, amount);
require(msg.value == totalPrice, "Katana: Wrong mint price");
if (totalPrice < amount * price) {
if (
Shiburai(shiburai).balanceOf(msg.sender) +
SHIBURAIVESTKEEPER(vestKeeper).remainingVestedBalance(
msg.sender
) <
shiburaiDiscountAtAmount
) {
uint256 until = _tokenIdCounter.current() +
amount -
FIRST_GIFTS;
if (until > 25) {
uint256 overDiscount = until - 25;
uint256 discountsLeft = 3 -
Kimono(kimono).usedKimonoDiscounts(msg.sender);
overDiscount = overDiscount < discountsLeft
? overDiscount
: discountsLeft;
for (uint256 i = 0; i < overDiscount; i++) {
Kimono(kimono).useKimonoDiscount(msg.sender);
}
}
}
}
require(
_tokenIdCounter.current() + amount < MAX_SUPPLY_PLUS_ONE,
"Katana: Max supply exceeded"
);
uint256 nextTokenId;
for (uint256 i = 0; i < amount; i++) {
_tokenIdCounter.increment();
nextTokenId = _tokenIdCounter.current();
_mint(_msgSender(), nextTokenId, 1, "");
}
}
/**
* Mint Giveaways (only Owner)
*
* Option for the owner to mint leftover token to be used in giveaways.
*/
function mintGiveaway(address to_, uint256 amount) public onlyOwner {
require(_paused == false, "Kabuto: Minting is paused");
require(
_tokenIdCounter.current() < MAX_SUPPLY_PLUS_ONE,
"Kabuto: Max supply exceeded"
);
uint256 nextTokenId;
for (uint256 i = 0; i < amount; i++) {
_tokenIdCounter.increment();
nextTokenId = _tokenIdCounter.current();
_mint(to_, nextTokenId, 1, "");
}
}
/**
* Withdraws all retrieved funds into the project team wallets.
*
* Splits the funds 90/10 for owner/dev.
*/
function withdraw() public onlyOwner {
Address.sendValue(payable(_msgSender()), address(this).balance);
}
/**
* Returns the number of minted tokens.
*/
function totalSupply() public view returns (uint256) {
return
_tokenIdCounter.current() +
_giftedIdCounter.current() -
FIRST_GIFTS;
}
/**
* @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 {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
return string(abi.encodePacked(_uri, tokenId.toString()));
}
/**
* @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"
);
require(id < MAX_SUPPLY_PLUS_ONE, "ERC1155D: id exceeds maximum");
return _owners[id] == account ? 1 : 0;
}
function erc721BalanceOf(address owner)
public
view
virtual
returns (uint256)
{
require(
owner != address(0),
"ERC721: address zero is not a valid owner"
);
return _balances[owner];
}
/**
* @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(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 {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(
_owners[id] == from && amount < 2,
"ERC1155: insufficient balance for transfer"
);
// The ERC1155 spec allows for transfering zero tokens, but we are still expected
// to run the other checks and emit the event. But we don't want an ownership change
// in that case
if (amount == 1) {
_owners[id] = to;
_balances[to] = _balances[to] + 1;
_balances[from] = _balances[from] - 1;
}
emit TransferSingle(operator, from, to, id, amount);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(
ids.length == amounts.length,
"ERC1155: ids and amounts length mismatch"
);
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
uint256 transfered;
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
require(
_owners[id] == from && amounts[i] < 2,
"ERC1155: insufficient balance for transfer"
);
if (amounts[i] == 1) {
_owners[id] == to;
transfered = transfered + 1;
}
}
_balances[to] = _balances[to] + transfered;
_balances[from] = _balances[from] - transfered;
emit TransferBatch(operator, from, to, ids, amounts);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
ids,
amounts,
data
);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(amount < 2, "ERC1155D: exceeds supply");
require(id < MAX_SUPPLY_PLUS_ONE, "ERC1155D: invalid id");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
// The ERC1155 spec allows for transfering zero tokens, but we are still expected
// to run the other checks and emit the event. But we don't want an ownership change
// in that case
if (amount == 1) {
_owners[id] = to;
_balances[to] = _balances[to] + 1;
}
emit TransferSingle(operator, address(0), to, id, amount);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(
operator,
address(0),
to,
id,
amount,
data
);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
require(
_owners[id] == from && amount < 2,
"ERC1155: burn amount exceeds balance"
);
if (amount == 1) {
_owners[id] = address(0);
}
emit TransferSingle(operator, from, address(0), id, amount);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(
ids.length == amounts.length,
"ERC1155: ids and amounts length mismatch"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
require(
_owners[id] == from && amounts[i] < 2,
"ERC1155: burn amount exceeds balance"
);
if (amounts[i] == 1) {
_owners[id] = address(0);
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @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,
"ERC1155: setting approval status for self"
);
_operatorApprovals[owner_][operator] = approved;
emit ApprovalForAll(owner_, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155Received(
operator,
from,
id,
amount,
data
)
returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (
response != IERC1155Receiver.onERC1155BatchReceived.selector
) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element)
internal
pure
returns (uint256[] memory)
{
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
function getOwnershipRecordOffChain()
external
view
returns (address[MAX_SUPPLY_PLUS_ONE] memory)
{
return _owners;
}
function ownerOfERC721Like(uint256 id) external view returns (address) {
require(id < _owners.length, "ERC1155D: id exceeds maximum");
address owner_ = _owners[id];
require(
owner_ != address(0),
"ERC1155D: owner query for nonexistent token"
);
return owner_;
}
function getERC721BalanceOffChain(address _address)
external
view
returns (uint256)
{
uint256 counter = 0;
for (uint256 i; i < _owners.length; i++) {
if (_owners[i] == _address) {
counter++;
}
}
return counter;
}
} | See {IERC1155MetadataURI-uri}. This implementation returns the same URI for all token types. It relies on the token type ID substitution mechanism Clients calling this function must replace the `\{id\}` substring with the actual token type ID./ | function uri(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
return string(abi.encodePacked(_uri, tokenId.toString()));
}
| 12,214,322 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/token/common/ERC2981.sol";
//
//
//
// ,#((((((((
// (#((((((###(#
// /##(#(((((((((#(###
// #(((##(((((((((## #(%##
// (#(#((((((((((#(.% *##
// ###((((((((#(. . *. *#(
// #(######/(///*,.# . , #.##
// ((#(#####/&%%&*\*,,./%%%%&@#
// ##(####/**# *#%,,,/( *** |
// ,###(### * | ,,*,,,,.|
// (#### / \ ,*&.*
// (@@@@, &&#### % @ ,/@/@ ,@@@@
// @@@@&&&&& ,#(#### (@&&&&@ ,,,&@ &&&&&@@@*
// @@&&&&&&&&&&& , \ °°°° ,/ &&&&&&&&&&@@@
// &&&&&&&&&&&&&&&&, [emailΒ protected]&&&.\, ,,/*&&&@ &&&&&&&&&&&&&&&@
// @&&&&&&&&&&&&&&&&&& &&@& __,,,,,,&&&* &&&&&&&&&&&&&&&&&&&
// @@@@&&&&&&&&&&&&&&&&&&& &&&&&&, ,,@&&&& &&&&&&&&&&&&&&&&&&&@@@@
// @@&@&&&&&&&&&&&&&&&&&&&&.%&&&&&&, @&&&&&& &&&&&&&&&&&&&&&&&&&&&@@(
// &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
// @&&&&&&&&&&&&&&&&@@@&&&&&&&&&&&&& &&&&&&&&&&&&&@@&&&&&&&&&&&&&&&&&
// &&&&&&&&&&&&&&&@@@@@&&&&&&&&&&&&@[emailΒ protected]&&&&&&&&&&&&@@@@&&&&&&&&&&&&&&&&
// &&&&&&&&&&&&&@&&&&&&&&&&&&&&&###(/##&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
// &&&&&&&&&&&&@&&&&&&&&&&&&&&&@*(((@&&&&&&&&&&&&&&&@@&&&&&&&&&&&&
// @@@&&&@@@@@@&@@@&&&&&&&&&@@@@@[emailΒ protected]@@@&&&&&&&&&@@@&&@@@@&&&&&&@&
// @@&&&&&&&&&@@&&&&&&@@@@@##((/#%@@@@&&&&&&@@&&&&&&&&&&@@
/**
* @title WoWGalaxy Contract
* @author Ben Yu, Itzik Lerner, @RMinLA, Mai Akiyoshi, Morgan Giraud, Toomaie, Eugene Strelkov
* @notice This contract handles minting and distribution of World of Women Galaxy tokens.
*/
contract WoWGalaxy is ERC721, ERC721Enumerable, ERC2981, ReentrancyGuard, Ownable {
using ECDSA for bytes32;
using Strings for uint256;
uint256 constant TOTAL_FREE_CLAIM_IDS = 10000;
uint256 constant FIRST_PUBLIC_ID = 10000;
uint256 constant LAST_PUBLIC_ID = 19999;
uint256 constant FIRST_ALLOWLIST_ID = 20000;
uint256 constant LAST_ALLOWLIST_ID = 22221;
uint256 constant MAX_MINTS_PER_TRANSACTION = 20;
address constant WOW_CONTRACT_ADDRESS = 0xe785E82358879F061BC3dcAC6f0444462D4b5330;
address constant WITHDRAW_ADDRESS = 0x646B9Ed09B130899be4c4bEc114A1aA94618bE09;
address public royaltyAddress = 0x646B9Ed09B130899be4c4bEc114A1aA94618bE09;
uint96 public royaltyFee = 400;
// Public vars
string public wowGProvenance;
uint256 public wowGProvenanceTimestamp;
string public baseTokenURI;
uint256 public allowListPrice;
uint256 public dutchAuctionDuration;
uint256[] public dutchAuctionSteps;
uint256 private minutesPerStep;
uint256 public freeClaimSaleStartTime;
uint256 public publicSaleStartTime;
uint256 public allowListSaleStartTime;
bytes32 public merkleRoot;
uint256 public startingIndexFreeClaim;
uint256 public startingIndexFreeClaimTimestamp;
uint256 public startingIndexPublicAndAllowList;
uint256 public startingIndexPublicAndAllowListTimestamp;
mapping(address => bool) public allowListMinted;
uint256 public freeClaimTokensMinted;
uint256 public allowListTokenIdCounter = FIRST_ALLOWLIST_ID;
uint256 public publicSaleTokenIdCounter = FIRST_PUBLIC_ID;
bool public isFreeClaimActive = false;
bool public isPublicSaleActive = false;
bool public isAllowListActive = false;
// support eth transactions to the contract
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
/**
* @notice Construct a WoWG contract instance
* @param _name Token name
* @param _symbol Token symbol
* @param _baseTokenURI Base URI for all tokens
*/
constructor(
string memory _name,
string memory _symbol,
string memory _baseTokenURI
) ERC721(_name, _symbol) {
baseTokenURI = _baseTokenURI;
_setDefaultRoyalty(royaltyAddress, royaltyFee);
}
modifier originalUser() {
require(msg.sender == tx.origin,"MUST_INVOKE_FUNCTION_DIRECTLY");
_;
}
/**
* @notice Update the base token URI
*/
function setBaseURI(string calldata _newBaseURI) external onlyOwner {
baseTokenURI = _newBaseURI;
}
/**
* @notice read the base token URI
*/
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
/**
* @notice Change the royalty fee for the collection
*/
function setRoyaltyFee(uint96 _feeNumerator) external onlyOwner {
royaltyFee = _feeNumerator;
_setDefaultRoyalty(royaltyAddress, royaltyFee);
}
/**
* @notice Change the royalty address where royalty payouts are sent
*/
function setRoyaltyAddress(address _royaltyAddress) external onlyOwner {
royaltyAddress = _royaltyAddress;
_setDefaultRoyalty(royaltyAddress, royaltyFee);
}
/**
* @notice Sets a provenance hash of pregenerated tokens for fairness. Should be set before first token mints
*/
function setProvenanceHash(string memory _provenanceHash) public onlyOwner {
wowGProvenance = _provenanceHash;
wowGProvenanceTimestamp = block.timestamp;
}
/**
* @notice Manually allow the owner to set the starting index for the free claim mint
*/
function setStartingIndexFreeClaim() external onlyOwner {
_setStartingIndexFreeClaim();
}
/**
* @notice Set the starting index for the free claim mint
*/
function _setStartingIndexFreeClaim() internal {
require(startingIndexFreeClaim == 0, "STARTING_INDEX_FREE_CLAIM_ALREADY_SET");
startingIndexFreeClaim = generateRandomStartingIndex(TOTAL_FREE_CLAIM_IDS);
startingIndexFreeClaimTimestamp = block.timestamp;
}
/**
* @notice Manually allow the owner to set the starting index for the public and allow list mints
*/
function setStartingIndexPublicAndAllowList() external onlyOwner {
_setStartingIndexPublicAndAllowList();
}
/**
* @notice Set the starting index for the public and allow list mints
*/
function _setStartingIndexPublicAndAllowList() internal {
require(startingIndexPublicAndAllowList == 0, "STARTING_INDEX_PUBLIC_AND_ALLOWLIST_ALREADY_SET");
startingIndexPublicAndAllowList = generateRandomStartingIndex(
LAST_ALLOWLIST_ID - FIRST_ALLOWLIST_ID + 1 +
LAST_PUBLIC_ID - FIRST_PUBLIC_ID + 1);
startingIndexPublicAndAllowListTimestamp = block.timestamp;
}
/**
* @notice Creates a random starting index to offset pregenerated tokens by for fairness
*/
function generateRandomStartingIndex(uint256 _range) public view returns (uint256) {
uint256 startingIndex;
// Blockhash only works for the most 256 recent blocks.
uint256 _block_shift = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp)));
_block_shift = 1 + (_block_shift % 255);
// This shouldn't happen, but just in case the blockchain gets a reboot?
if (block.number < _block_shift) {
_block_shift = 1;
}
uint256 _block_ref = block.number - _block_shift;
startingIndex = uint(blockhash(_block_ref)) % _range;
// Prevent default sequence
if (startingIndex == 0) {
startingIndex++;
}
return startingIndex;
}
/**
* @notice Set the steps and duration in minutes for the public Dutch auction mint
*/
function setDutchAuctionParams(uint256[] calldata _steps, uint256 _duration)
public
onlyOwner
{
require(_steps.length > 0 && _duration > 0,'ZERO_STEPS_OR_ZERO_DURATION');
dutchAuctionSteps = _steps;
dutchAuctionDuration = _duration;
minutesPerStep = dutchAuctionDuration / dutchAuctionSteps.length;
}
/**
* @notice Retrieve the current Dutch auction price per token
*/
function getCurrentDutchAuctionPrice() public view returns (uint256) {
uint256 minutesPassed =
uint256(block.timestamp - publicSaleStartTime) / 60;
if (minutesPassed >= dutchAuctionDuration) {
return dutchAuctionSteps[dutchAuctionSteps.length - 1];
}
return dutchAuctionSteps[minutesPassed / minutesPerStep];
}
/**
* @notice Set the price per token for the allow list mint
*/
function setAllowListPrice(uint256 _newAllowListPrice) public onlyOwner {
require(_newAllowListPrice > 0 ether, "CANT_SET_ALLOW_LIST_PRICE_BACK_TO_ZERO");
allowListPrice = _newAllowListPrice;
}
/**
* @notice Set the merkle root for the allow list mint
*/
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
/**
* @notice Verify address eligibility for the allow list mint
*/
function isAllowListEligible(address addr, bytes32[] calldata _merkleProof) public view returns (bool) {
bytes32 leaf = keccak256(abi.encodePacked(addr));
return MerkleProof.verify(_merkleProof, merkleRoot, leaf);
}
// Sales
/**
* @notice Set the active/inactive state of the allow list mint
*/
function flipAllowListState() public onlyOwner {
require(isAllowListActive || allowListPrice > 0, "ALLOW_LIST_PRICE_NOT_SET");
isAllowListActive = !isAllowListActive;
if (allowListSaleStartTime == 0) {
allowListSaleStartTime = block.timestamp;
}
}
/**
* @notice Allow an address on the allow list to mint a single token
*/
function allowListMint(bytes32[] calldata _merkleProof)
external
payable
nonReentrant
originalUser
{
require(isAllowListActive, "ALLOW_LIST_SALE_IS_NOT_ACTIVE");
require(allowListTokenIdCounter <= LAST_ALLOWLIST_ID, "INSUFFICIENT_SUPPLY");
require(
!allowListMinted[msg.sender],
"ADDRESS_ALREADY_MINTED_IN_ALLOW_LIST"
);
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(
MerkleProof.verify(_merkleProof, merkleRoot, leaf),
"ADDRESS_NOT_ELIGIBLE_FOR_ALLOW_LIST"
);
require(msg.value == allowListPrice, "INVALID_PRICE");
allowListMinted[msg.sender] = true;
_safeMint(msg.sender, allowListTokenIdCounter);
allowListTokenIdCounter++;
}
/**
* @notice Allow the owner to start/stop the public sale
*/
function flipPublicSaleState() public onlyOwner {
isPublicSaleActive = !isPublicSaleActive;
if (publicSaleStartTime == 0) {
publicSaleStartTime = block.timestamp;
} else {
publicSaleStartTime = 0;
}
}
/**
* @notice Allow anyone to mint tokens publicly
*/
function publicSaleMint(uint256 _numberToMint)
external
payable
nonReentrant
originalUser
{
require(isPublicSaleActive, "PUBLIC_SALE_IS_NOT_ACTIVE");
uint256 costToMint = getCurrentDutchAuctionPrice() * _numberToMint;
require(
_numberToMint <= MAX_MINTS_PER_TRANSACTION,
"EXCEEDS_MAX_MINTS_PER_TRANSACTION"
);
require(
msg.value >= costToMint,
"INSUFFICIENT_PAYMENT"
);
require(
publicSaleTokenIdCounter + _numberToMint <= LAST_PUBLIC_ID + 1,
"INSUFFICIENT_SUPPLY"
);
for (uint256 i; i < _numberToMint; i++) {
_safeMint(msg.sender, publicSaleTokenIdCounter + i);
}
publicSaleTokenIdCounter += _numberToMint;
// last mint will increase the counter past LAST_PUBLIC_ID
if (publicSaleTokenIdCounter > LAST_PUBLIC_ID) {
isPublicSaleActive = false;
if (startingIndexPublicAndAllowList == 0) {
_setStartingIndexPublicAndAllowList();
}
}
if (msg.value > costToMint) {
Address.sendValue(payable(msg.sender), msg.value - costToMint);
}
}
/**
* @notice Allow to owner to start/stop the free claim mint
*/
function flipFreeClaimState() public onlyOwner {
isFreeClaimActive = !isFreeClaimActive;
if (freeClaimSaleStartTime == 0) {
freeClaimSaleStartTime = block.timestamp;
}
}
/**
* @notice Allow an existing WoW holder to mint corresponding WoWG tokens for free
*/
function freeClaimMint(uint256[] calldata _tokenIDs)
external
nonReentrant
{
require(isFreeClaimActive, "FREE_CLAIM_IS_NOT_ACTIVE");
uint256 numberToMint = _tokenIDs.length;
require(
numberToMint <= MAX_MINTS_PER_TRANSACTION,
"EXCEEDS_MAX_MINTS_PER_TRANSACTION"
);
ERC721 WoW = ERC721(WOW_CONTRACT_ADDRESS);
for (uint256 i; i < numberToMint; i++) {
require(WoW.ownerOf(_tokenIDs[i]) == msg.sender, "DOES_NOT_OWN_WOW_TOKEN_ID");
_safeMint(msg.sender, _tokenIDs[i]);
freeClaimTokensMinted++;
}
if (freeClaimTokensMinted == TOTAL_FREE_CLAIM_IDS) {
isFreeClaimActive = false;
}
// set starting index for free claim tokens as soon as the first token is minted
if (startingIndexFreeClaim == 0) {
_setStartingIndexFreeClaim();
}
}
/**
* @notice Easily get the number of steps for the public sale
*/
function getDutchAuctionStepsCount() public view returns (uint256 count) {
return dutchAuctionSteps.length;
}
// Owner
/**
* @notice Allow the owner to gift tokens to an arbitrary number of addresses
*/
function giftMint(address[] calldata _receivers) external onlyOwner {
require(
allowListTokenIdCounter + _receivers.length <= LAST_ALLOWLIST_ID + 1,
"NOT_ENOUGH_ALLOW_LIST_TOKENS_REMAINING"
);
for (uint256 i; i < _receivers.length; i++) {
_safeMint(_receivers[i], allowListTokenIdCounter + i);
}
allowListTokenIdCounter += _receivers.length;
}
/**
* @notice Allow withdrawing funds to the withdrawAddress
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0,'NOTHING_TO_WITHDRAW');
require(payable(WITHDRAW_ADDRESS).send(balance));
}
// Utils
/**
* @notice Returns a list of token IDs owned by a given address
*/
function walletOfOwner(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
/**
* @notice Allow external checks for token existence
*/
function tokenExists(uint256 _tokenId) public view returns(bool) {
return _exists(_tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner");
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);
_afterTokenTransfer(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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @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();
}
}
// 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: 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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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 = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 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));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol)
pragma solidity ^0.8.0;
import "../../interfaces/IERC2981.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
virtual
override
returns (address, uint256)
{
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `tokenId` must be already minted.
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
// 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 (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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/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 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @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);
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol"; | Allow external checks for token existence/ | function tokenExists(uint256 _tokenId) public view returns(bool) {
return _exists(_tokenId);
}
| 1,378,920 |
./full_match/80001/0xb1B3D50811731f55543152FA134D0EF44f082cb6/sources/contracts/Gateway/ClaimHelper.sol | Only admin allowed to call this function | function changeDependentContractAddress() external {
require(
IAccessControl(address(cg)).hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Pool: Caller is not an admin"
);
coverGateway = CoverGateway(cg.getLatestAddress("CG"));
listingGateway = ListingGateway(cg.getLatestAddress("LG"));
coverData = CoverData(cg.getLatestAddress("CD"));
claimData = ClaimData(cg.getLatestAddress("CM"));
listingData = ListingData(cg.getLatestAddress("LD"));
platformData = PlatformData(cg.getLatestAddress("PD"));
pool = Pool(cg.getLatestAddress("PL"));
}
| 9,504,935 |
./full_match/1/0xc751D8c8f7b2fa4d9d01507E5A088F1b136e10c2/sources/src/lib/StringUtils.sol | Splits the slice, setting `self` to everything after the first occurrence of `needle`, and returning everything before it. If `needle` does not occur in `self`, `self` is set to the empty slice, and the entirety of `self` is returned. self The slice to split. needle The text to search for in `self`. return The part of `self` up to the first occurrence of `delim`./ | function split(Slice memory self, Slice memory needle) internal pure returns (Slice memory token) {
split(self, needle, token);
}
| 9,823,810 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
/*
βββββββ ββββββββ ββββββ βββ βββββββββββββββ βββ βββββββ ββββββ βββββββ βββββββ ββββββββ
βββββββββββββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββ βββββββββββ βββ βββ βββββββ βββ βββββββββββββββββββ βββββββββββ
ββββββββββββββ βββββββββββ βββ βββ βββββ βββ βββββββββββββββββββ βββββββββββ
βββ ββββββββββββββ ββββββββββββββ βββ βββ βββββββββββ ββββββ βββββββββββββββββββ
βββ ββββββββββββββ ββββββββββββββ βββ βββ ββββββββββ ββββββ ββββββββββ ββββββββ
*/
import "@openzeppelin/contracts/proxy/Clones.sol";
import "hardhat/console.sol";
import "./interfaces/IRCFactory.sol";
import "./interfaces/IRCTreasury.sol";
import "./interfaces/IRCMarket.sol";
import "./interfaces/IRCNftHubL2.sol";
import "./interfaces/IRCOrderbook.sol";
import "./lib/NativeMetaTransaction.sol";
import "./interfaces/IRealitio.sol";
/// @title Reality Cards Factory
/// @author Andrew Stanger & Daniel Chilvers
/// @notice If you have found a bug, please contact [email protected] no hack pls!!
contract RCFactory is NativeMetaTransaction, IRCFactory {
/*βββββββββββββββββββββββββββββββββββ
β VARIABLES β
βββββββββββββββββββββββββββββββββββ*/
/////// CONTRACT VARIABLES ///////
IRCTreasury public override treasury;
IRCNftHubL2 public override nfthub;
IRCOrderbook public override orderbook;
IRCLeaderboard public override leaderboard;
IRealitio public override realitio;
/// @dev reference contract
address public override referenceContractAddress;
/// @dev increments each time a new reference contract is added
uint256 public override referenceContractVersion;
/// @dev market addresses, mode // address
/// @dev these are not used for anything, just an easy way to get markets
mapping(IRCMarket.Mode => address[]) public marketAddresses;
////// BACKUP MODE //////
/// @dev should the Graph fail the UI needs a way to poll the contracts for market data
/// @dev the IPFS hash for each market
mapping(address => string) public override ipfsHash;
/// @dev the slug each market is hosted at
mapping(string => address) public override slugToAddress;
mapping(address => string) public override addressToSlug;
///// GOVERNANCE VARIABLES- OWNER /////
/// @dev artist / winner / market creator / affiliate / card affiliate
uint256[5] public potDistribution;
/// @dev minimum tokens that must be sent when creating market which forms initial pot
uint256 public override sponsorshipRequired;
/// @dev adjust required price increase (in %)
uint256 public override minimumPriceIncreasePercent;
/// @dev The number of users that are allowed to mint an NFT
uint256 public override nftsToAward;
/// @dev market opening time must be at least this many seconds in the future
uint32 public override advancedWarning;
/// @dev market closing time must be no more than this many seconds in the future
uint32 public override maximumDuration;
/// @dev market closing time must be at least this many seconds after opening
uint32 public override minimumDuration;
/// @dev if false, anyone can create markets
bool public override marketCreationGovernorsOnly = true;
/// @dev if false, anyone can be an affiliate
bool public override approvedAffiliatesOnly = true;
/// @dev if false, anyone can be an artist
bool public override approvedArtistsOnly = true;
/// @dev the maximum number of rent collections to perform in a single transaction
uint256 public override maxRentIterations;
/// @dev the maximum number of rent collections to have performed before locking the market
uint256 public override maxRentIterationsToLockMarket;
/// @dev the address of the arbitrator
address public override arbitrator;
/// @dev the time allowed to dispute the oracle answer
uint32 public override timeout;
/// @dev if true markets default to the paused state
bool public override marketPausedDefaultState;
/// @dev a limit to the number of NFTs to mint per market
uint256 public override cardLimit;
bool public limitNFTsToWinners;
///// GOVERNANCE VARIABLES- GOVERNORS /////
/// @dev unapproved markets hidden from the interface
mapping(address => bool) public override isMarketApproved;
///// OTHER /////
uint256 public constant PER_MILLE = 1000; // in MegaBip so (1000 = 100%)
/// @dev store the tokenURIs for when we need to mint them
/// @dev we may want the original and the copies to have slightly different metadata
/// @dev We also want to apply traits to the winning and losing outcomes
/// @dev this means we need 5 different tokenURIs per card:
/// @dev Original Neutral - Used during the market runtime, not a winner but not a loser
/// @dev Original Winner - Applied to the winning outcome
/// @dev Original Loser - Applied to the losing outcomes
/// @dev Print Winner - Applied to copies of the winning outcome
/// @dev Print Loser - Applied to copies of the losing outcomes
/// @dev Print neutral is not required as you can't print before the result is known
mapping(address => mapping(uint256 => string)) tokenURIs;
/*βββββββββββββββββββββββββββββββββββ
β Access Control β
βββββββββββββββββββββββββββββββββββ*/
bytes32 public constant UBER_OWNER = keccak256("UBER_OWNER");
bytes32 public constant OWNER = keccak256("OWNER");
bytes32 public constant GOVERNOR = keccak256("GOVERNOR");
bytes32 public constant MARKET = keccak256("MARKET");
bytes32 public constant TREASURY = keccak256("TREASURY");
bytes32 public constant ORDERBOOK = keccak256("ORDERBOOK");
bytes32 public constant ARTIST = keccak256("ARTIST");
bytes32 public constant AFFILIATE = keccak256("AFFILIATE");
bytes32 public constant CARD_AFFILIATE = keccak256("CARD_AFFILIATE");
/*βββββββββββββββββββββββββββββββββββ
β EVENTS β
βββββββββββββββββββββββββββββββββββ*/
event LogMarketCreated1(
address contractAddress,
address treasuryAddress,
address nftHubAddress,
uint256 referenceContractVersion
);
event LogMarketCreated2(
address contractAddress,
IRCMarket.Mode mode,
string[] tokenURIs,
string ipfsHash,
uint32[] timestamps,
uint256 totalNftMintCount
);
event LogMarketApproved(address market, bool approved);
event LogMarketTimeRestrictions(
uint256 _newAdvancedWarning,
uint256 _newMinimumDuration,
uint256 _newMaximumDuration
);
event LogMintNFTCopy(
uint256 _originalTokenId,
address _newOwner,
uint256 _newTokenId
);
event LogMintNFT(uint256 _cardId, address _market, uint256 _tokenId);
/*βββββββββββββββββββββββββββββββββββ
β CONSTRUCTOR β
βββββββββββββββββββββββββββββββββββ*/
constructor(
IRCTreasury _treasury,
address _realitioAddress,
address _arbitratorAddress
) {
require(address(_treasury) != address(0), "Must set Address");
// initialise MetaTransactions
_initializeEIP712("RealityCardsFactory", "1");
// store contract instances
treasury = _treasury;
// initialise adjustable parameters
// artist // winner // creator // affiliate // card affiliates
setPotDistribution(20, 0, 0, 20, 100); // 2% artist, 2% affiliate, 10% card affiliate
setMinimumPriceIncreasePercent(10); // 10%
setNumberOfNFTsToAward(3);
setCardLimit(100); // safe limit tested and set at 100, can be adjusted later if gas limit changes
setMaxRentIterations(50, 25); // safe limit tested and set at 50 & 25, can be adjusted later if gas limit changes
// oracle
setArbitrator(_arbitratorAddress);
setRealitioAddress(_realitioAddress);
setTimeout(86400); // 24 hours
limitNFTsToWinners = false;
}
/*βββββββββββββββββββββββββββββββββββ
β VIEW FUNCTIONS β
βββββββββββββββββββββββββββββββββββ*/
/// @notice Fetch the address of the most recently created market
/// @param _mode Filter by market mode, 0=Classic 1=Winner Takes All 2=SafeMode
/// @return the address of the most recent market in the given mode
function getMostRecentMarket(IRCMarket.Mode _mode)
external
view
override
returns (address)
{
if (marketAddresses[_mode].length == 0) return address(0);
return marketAddresses[_mode][marketAddresses[_mode].length - (1)];
}
/// @notice Fetch all the market addresses for a given mode
/// @param _mode Filter by market mode, 0=Classic 1=Winner Takes All 2=SafeMode
/// @return an array of all markets in a given mode
function getAllMarkets(IRCMarket.Mode _mode)
external
view
override
returns (address[] memory)
{
return marketAddresses[_mode];
}
/// @notice Returns the currently set pot distribution
/// @return the pot distribution array: artist, winner, creator, affiliate, card affiliates
function getPotDistribution()
external
view
override
returns (uint256[5] memory)
{
return potDistribution;
}
/// @notice fetch the current oracle, arbitrator and timeout settings
/// @dev called by the market upon initialise
/// @dev not passed to initialise to avoid stack too deep error
/// @return Oracle Address
/// @return Arbitrator Address
/// @return Question timeout in seconds
function getOracleSettings()
external
view
override
returns (
IRealitio,
address,
uint32
)
{
return (realitio, arbitrator, timeout);
}
/// @notice Returns market addresses and ipfs hashes
/// @dev used for the UI backup mode
/// @param _mode return markets only in the given mode
/// @param _state return markets only in the given state
/// @param _results the number of results to return
/// @param _skipResults the number of results to skip
function getMarketInfo(
IRCMarket.Mode _mode,
uint256 _state,
uint256 _results,
uint256 _skipResults
)
external
view
returns (
address[] memory,
string[] memory,
string[] memory,
uint256[] memory
)
{
// start at the end of the marketAddresses array so the most recent market is first
uint256 _marketIndex = marketAddresses[_mode].length;
if (_marketIndex < _results) {
// if we haven't created enough markets yet there's no need to return empty results
_results = _marketIndex;
}
uint256 _resultNumber = 0; // counts the valid results we've found
uint256 _index = 0; // counts how many markets we have checked (valid or invalid)
address[] memory _marketAddresses = new address[](_results); // store the addresses of valid markets
while (_resultNumber < _results && _marketIndex > 1) {
_marketIndex--;
address _market = marketAddresses[_mode][_marketIndex];
if (IRCMarket(_market).state() == IRCMarket.States(_state)) {
// we found an appropriate market
if (_index < _skipResults) {
// we need to skip it however
_index++;
} else {
// we can use this one, add the address and increment
_marketAddresses[_resultNumber] = _market;
_resultNumber++;
_index++;
}
}
}
return _getMarketInfo(_marketAddresses);
}
/// @notice Assembles all the Slugs, IPFS hashes and PotSizes for the markets given
/// @dev separated from getMarketInfo to avoid Stack too deep
function _getMarketInfo(address[] memory _marketAddresses)
internal
view
returns (
address[] memory,
string[] memory,
string[] memory,
uint256[] memory
)
{
string[] memory _ipfsHashes = new string[](_marketAddresses.length);
uint256[] memory _potSizes = new uint256[](_marketAddresses.length);
string[] memory _slugs = new string[](_marketAddresses.length);
for (uint256 i = 0; i < _marketAddresses.length; i++) {
if (_marketAddresses[i] == address(0)) break;
_ipfsHashes[i] = ipfsHash[_marketAddresses[i]];
_slugs[i] = addressToSlug[_marketAddresses[i]];
_potSizes[i] = IRCMarket(_marketAddresses[i]).totalRentCollected();
}
return (_marketAddresses, _ipfsHashes, _slugs, _potSizes);
}
/*βββββββββββββββββββββββββββββββββββ
β MODIFIERS β
βββββββββββββββββββββββββββββββββββ*/
modifier onlyUberOwner() {
require(
treasury.checkPermission(UBER_OWNER, msgSender()),
"Not approved"
);
_;
}
modifier onlyOwner() {
require(treasury.checkPermission(OWNER, msgSender()), "Not approved");
_;
}
modifier onlyGovernors() {
require(
treasury.checkPermission(GOVERNOR, msgSender()),
"Not approved"
);
_;
}
modifier onlyMarkets() {
require(treasury.checkPermission(MARKET, msgSender()), "Not approved");
_;
}
/*βββββββββββββββββββββββββββββββββββ
β GOVERNANCE - OWNER β
βββββββββββββββββββββββββββββββββββ*/
/// @dev all functions should have onlyOwner modifier
// Min price increase & pot distribution emitted by Market.
// Advanced Warning and Maximum Duration events emitted here. Nothing else need be emitted.
/*ββββββββββββββββββββββββββββββββββββββ
β CALLED WITHIN CONSTRUCTOR - PUBLIC β
ββββββββββββββββββββββββββββββββββββββ*/
/// @notice update stakeholder payouts
/// @dev in MegaBip (so 1000 = 100%)
/// @param _artistCut The artist that designed the card
/// @param _winnerCut Extra cut for the longest owner
/// @param _creatorCut The creator of the market
/// @param _affiliateCut An affiliate for the market that doesn't fit into the other cuts
/// @param _cardAffiliateCut An affiliate cur for specific cards
function setPotDistribution(
uint256 _artistCut,
uint256 _winnerCut,
uint256 _creatorCut,
uint256 _affiliateCut,
uint256 _cardAffiliateCut
) public override onlyOwner {
require(
_artistCut +
_winnerCut +
_creatorCut +
_affiliateCut +
_cardAffiliateCut <=
PER_MILLE,
"Cuts too big"
);
potDistribution[0] = _artistCut;
potDistribution[1] = _winnerCut;
potDistribution[2] = _creatorCut;
potDistribution[3] = _affiliateCut;
potDistribution[4] = _cardAffiliateCut;
}
/// @notice how much above the current price a user must bid, in %
/// @param _percentIncrease the percentage to set, e.g. 10 = 10%
function setMinimumPriceIncreasePercent(uint256 _percentIncrease)
public
override
onlyOwner
{
minimumPriceIncreasePercent = _percentIncrease;
}
/// @notice how many NFTs will be awarded to the leaderboard
/// @param _nftsToAward the number of NFTs to award
function setNumberOfNFTsToAward(uint256 _nftsToAward)
public
override
onlyOwner
{
nftsToAward = _nftsToAward;
}
/// @notice A limit to the number of NFTs to mint per market
/// @dev to avoid gas limits
/// @param _cardLimit the limit to set
function setCardLimit(uint256 _cardLimit) public override onlyOwner {
cardLimit = _cardLimit;
}
/// @notice A limit to the number of rent collections per transaction
/// @dev to avoid gas limits
/// @param _rentLimit the limit to set
function setMaxRentIterations(uint256 _rentLimit, uint256 _rentLimitLocking)
public
override
onlyOwner
{
maxRentIterations = _rentLimit;
maxRentIterationsToLockMarket = _rentLimitLocking;
}
/// @notice set the address of the reality.eth contracts
/// @param _newAddress the address to set
function setRealitioAddress(address _newAddress) public override onlyOwner {
require(_newAddress != address(0), "Must set address");
realitio = IRealitio(_newAddress);
}
/// @notice address of the arbitrator, in case of continued disputes on reality.eth
/// @param _newAddress the address to set
function setArbitrator(address _newAddress) public override onlyOwner {
require(_newAddress != address(0), "Must set address");
arbitrator = _newAddress;
}
/// @notice set how long reality.eth waits for disputes before finalising
/// @param _newTimeout the timeout to set in seconds, 86400 = 24hrs
function setTimeout(uint32 _newTimeout) public override onlyOwner {
// event is emitted from the Oracle when the question is asked
timeout = _newTimeout;
}
/// @notice To set is markets should default to paused or not
/// @param _state The default state for all new markets
function setMarketPausedDefaultState(bool _state)
external
override
onlyOwner
{
/// @dev the event is emitted when a market is created
marketPausedDefaultState = _state;
}
/// @notice To limit NFT copies to the winning outcome only
/// @param _limitEnabled Set to True to limit to the winning outcome only
function setLimitNFTsToWinners(bool _limitEnabled)
public
override
onlyOwner
{
limitNFTsToWinners = _limitEnabled;
}
/*ββββββββββββββββββββββββββββββββββββββββββββ
β NOT CALLED WITHIN CONSTRUCTOR - EXTERNAL β
ββββββββββββββββββββββββββββββββββββββββββββ*/
/// @notice whether or not only governors can create the market
function changeMarketCreationGovernorsOnly() external override onlyOwner {
marketCreationGovernorsOnly = !marketCreationGovernorsOnly;
}
/// @notice whether or not anyone can be an artist
function changeApprovedArtistsOnly() external override onlyOwner {
approvedArtistsOnly = !approvedArtistsOnly;
}
/// @notice whether or not anyone can be an affiliate
function changeApprovedAffiliatesOnly() external override onlyOwner {
approvedAffiliatesOnly = !approvedAffiliatesOnly;
}
/// @notice how many tokens must be sent in the createMarket tx which forms the initial pot
/// @param _amount the sponsorship required in wei
function setSponsorshipRequired(uint256 _amount)
external
override
onlyOwner
{
sponsorshipRequired = _amount;
}
/// @notice To set the market time restrictions, market opening and min/max duration.
/// @param _newAdvancedWarning the warning time to set in seconds
/// @param _newMinimumDuration the minimum market duration
/// @param _newMaximumDuration the maximum market duration
/// @dev might be nicer to have these separate but takes up too much space
function setMarketTimeRestrictions(
uint32 _newAdvancedWarning,
uint32 _newMinimumDuration,
uint32 _newMaximumDuration
) external override onlyOwner {
advancedWarning = _newAdvancedWarning;
minimumDuration = _newMinimumDuration;
maximumDuration = _newMaximumDuration;
emit LogMarketTimeRestrictions(
_newAdvancedWarning,
_newMinimumDuration,
_newMaximumDuration
);
}
/// @notice Allow the owner to update a token URI.
/// @notice only updates for tokens not yet minted
/// @dev after calling this existing token URIs should be changed on
/// @dev .. the NFT hubs using setTokenURI()
/// @param _market the market address the token belongs to
/// @param _cardId the index 0 card id of the token to change
/// @param _newTokenURIs the new URIs to set
function updateTokenURI(
address _market,
uint256 _cardId,
string[] calldata _newTokenURIs
) external override onlyUberOwner {
IRCMarket.Mode _mode = IRCMarket(_market).mode();
uint256 _numberOfCards = IRCMarket(_market).numberOfCards();
tokenURIs[_market][_cardId] = _newTokenURIs[0];
tokenURIs[_market][(_cardId + _numberOfCards)] = _newTokenURIs[1];
tokenURIs[_market][(_cardId + (_numberOfCards * 2))] = _newTokenURIs[2];
tokenURIs[_market][(_cardId + (_numberOfCards * 3))] = _newTokenURIs[3];
tokenURIs[_market][(_cardId + (_numberOfCards * 4))] = _newTokenURIs[4];
// assemble the rest of the data so we can reuse the event
string[] memory _tokenURIs = new string[](_numberOfCards * 5);
for (uint256 i = 0; i < _tokenURIs.length; i++) {
_tokenURIs[i] = tokenURIs[_market][i];
}
uint32[] memory _timestamps = new uint32[](3);
_timestamps[0] = IRCMarket(_market).marketOpeningTime();
_timestamps[1] = IRCMarket(_market).marketLockingTime();
_timestamps[2] = IRCMarket(_market).oracleResolutionTime();
// reuse this event so the frontend can pickup the change
emit LogMarketCreated2(
_market,
IRCMarket.Mode(_mode),
_tokenURIs,
ipfsHash[_market],
_timestamps,
nfthub.totalSupply()
);
}
/*βββββββββββββββββββββββββββββββββββ
β GOVERNANCE - GOVERNORS β
βββββββββββββββββββββββββββββββββββ*/
/// @dev all functions should have onlyGovernors modifier
/// @notice markets are default hidden from the interface, this reveals them
/// @param _market the market address to change approval for
function changeMarketApproval(address _market)
external
override
onlyGovernors
{
require(_market != address(0), "Must set Address");
// check it's an RC contract
require(treasury.checkPermission(MARKET, _market), "Not Market");
isMarketApproved[_market] = !isMarketApproved[_market];
// governors shouldn't have the ability to pause a market, only un-pause.
// .. if a governor accidentally approves a market they should seek
// .. assistance from the owner to decide if it should be paused.
treasury.unPauseMarket(_market);
// the market will however be hidden from the UI in the meantime
emit LogMarketApproved(_market, isMarketApproved[_market]);
}
/*βββββββββββββββββββββββββββββββββββ
β GOVERNANCE - UBER OWNER β
β ββββββββββββββββββββββββββββββββββ£
β ******** DANGER ZONE ******** β
βββββββββββββββββββββββββββββββββββ*/
/// @dev uber owner required for upgrades, this is separated so owner can be
/// @dev .. set to multisig, or burn address to relinquish upgrade ability
/// @dev ... while maintaining governance over other governance functions
/// @notice change the reference contract for the contract logic
/// @param _newAddress the address of the new reference contract to set
function setReferenceContractAddress(address _newAddress)
external
override
onlyUberOwner
{
require(_newAddress != address(0));
// check it's an RC contract
IRCMarket newContractVariable = IRCMarket(_newAddress);
require(newContractVariable.isMarket(), "Not Market");
// set
referenceContractAddress = _newAddress;
// increment version
referenceContractVersion += 1;
}
/// @notice where the NFTs live
/// @param _newAddress the address to set
function setNftHubAddress(IRCNftHubL2 _newAddress)
external
override
onlyUberOwner
{
require(address(_newAddress) != address(0), "Must set Address");
nfthub = _newAddress;
}
/// @notice set the address of the orderbook contract
/// @param _newOrderbook the address to set
/// @dev set by the treasury to ensure all contracts use the same orderbook
function setOrderbookAddress(IRCOrderbook _newOrderbook) external override {
require(
treasury.checkPermission(TREASURY, msgSender()),
"Not approved"
);
orderbook = _newOrderbook;
}
/// @notice set the address of the leaderboard contract
/// @param _newLeaderboard the address to set
/// @dev set by the treasury to ensure all contracts use the same leaderboard
function setLeaderboardAddress(IRCLeaderboard _newLeaderboard)
external
override
{
require(
treasury.checkPermission(TREASURY, msgSender()),
"Not approved"
);
leaderboard = _newLeaderboard;
}
/// @notice set the address of the treasury contract
/// @param _newTreasury the address to set
function setTreasuryAddress(IRCTreasury _newTreasury)
external
override
onlyUberOwner
{
require(address(_newTreasury) != address(0), "Must set Address");
treasury = _newTreasury;
}
/*βββββββββββββββββββββββββββββββββββ
β MARKET CREATION β
βββββββββββββββββββββββββββββββββββ*/
// The factory contract has one job, this is it!
/// @notice Creates a new market with the given parameters
/// @param _mode 0 = normal, 1 = winner takes all, 2 = Safe mode
/// @param _ipfsHash the IPFS location of the market metadata
/// @param _slug the URL subdomain in the UI
/// @param _timestamps for market opening, locking, and oracle resolution
/// @param _tokenURIs location of NFT metadata, 5 versions for originals, copies, winners and losers
/// @param _artistAddress where to send artist's cut, if any
/// @param _affiliateAddress where to send affiliates cut, if any
/// @param _cardAffiliateAddresses where to send card specific affiliates cut, if any
/// @param _realitioQuestion the details of the event to send to the oracle
/// @param _sponsorship amount of sponsorship to create the market with
/// @return The address of the new market
function createMarket(
uint32 _mode,
string memory _ipfsHash,
string memory _slug,
uint32[] memory _timestamps,
string[] memory _tokenURIs,
address _artistAddress,
address _affiliateAddress,
address[] memory _cardAffiliateAddresses,
string memory _realitioQuestion,
uint256 _sponsorship
) external override returns (address) {
address _creator = msgSender();
// check nfthub has been set
require(address(nfthub) != address(0), "Nfthub not set");
require(
address(referenceContractAddress) != address(0),
"Reference not set"
);
// check sponsorship
require(
_sponsorship >= sponsorshipRequired,
"Insufficient sponsorship"
);
treasury.checkSponsorship(_creator, _sponsorship);
// check the number of NFTs to mint is within limits
/// @dev we want different tokenURIs for originals and copies
/// @dev ..the copies are appended to the end of the array
/// @dev ..so half the array length is the number of tokens.
require(_tokenURIs.length <= cardLimit * 5, "Hit mint limit");
require(_tokenURIs.length % 5 == 0, "TokenURI Length Error");
// check stakeholder addresses
// artist
if (approvedArtistsOnly) {
require(
_artistAddress == address(0) ||
treasury.checkPermission(ARTIST, _artistAddress),
"Artist not approved"
);
}
// affiliate
require(
_cardAffiliateAddresses.length == 0 ||
_cardAffiliateAddresses.length * 5 == _tokenURIs.length,
"Card Affiliate Length Error"
);
if (approvedAffiliatesOnly) {
require(
_affiliateAddress == address(0) ||
treasury.checkPermission(AFFILIATE, _affiliateAddress),
"Affiliate not approved"
);
// card affiliates
for (uint256 i = 0; i < _cardAffiliateAddresses.length; i++) {
require(
_cardAffiliateAddresses[i] == address(0) ||
treasury.checkPermission(
CARD_AFFILIATE,
_cardAffiliateAddresses[i]
),
"Card affiliate not approved"
);
}
}
// check market creator is approved
if (marketCreationGovernorsOnly) {
require(
treasury.checkPermission(GOVERNOR, _creator),
"Not approved"
);
}
_checkTimestamps(_timestamps);
// create the market and emit the appropriate events
// two events to avoid stack too deep error
address _newAddress = Clones.clone(referenceContractAddress);
emit LogMarketCreated1(
_newAddress,
address(treasury),
address(nfthub),
referenceContractVersion
);
emit LogMarketCreated2(
_newAddress,
IRCMarket.Mode(_mode),
_tokenURIs,
_ipfsHash,
_timestamps,
nfthub.totalSupply()
);
// tell Treasury about new market
// before initialize as during initialize the market may call the treasury
treasury.addMarket(_newAddress, marketPausedDefaultState);
// update internals
marketAddresses[IRCMarket.Mode(_mode)].push(_newAddress);
ipfsHash[_newAddress] = _ipfsHash;
slugToAddress[_slug] = _newAddress;
addressToSlug[_newAddress] = _slug;
// initialize the market
IRCMarket(_newAddress).initialize(
IRCMarket.Mode(_mode),
_timestamps,
(_tokenURIs.length / 5),
_artistAddress,
_affiliateAddress,
_cardAffiliateAddresses,
_creator,
_realitioQuestion,
nftsToAward
);
// store token URIs
for (uint256 i = 0; i < _tokenURIs.length; i++) {
tokenURIs[_newAddress][i] = _tokenURIs[i];
}
// pay sponsorship, if applicable
if (_sponsorship > 0) {
IRCMarket(_newAddress).sponsor(_creator, _sponsorship);
}
return _newAddress;
}
function _checkTimestamps(uint32[] memory _timestamps) internal view {
// check timestamps
require(_timestamps.length == 3, "Incorrect number of array elements");
// check market opening time
if (advancedWarning != 0) {
// different statements to give clearer revert messages
require(
_timestamps[0] >= block.timestamp,
"Market opening time not set"
);
require(
_timestamps[0] - advancedWarning > block.timestamp,
"Market opens too soon"
);
}
// check market locking time
if (maximumDuration != 0) {
require(
_timestamps[1] < block.timestamp + maximumDuration,
"Market locks too late"
);
}
require(
_timestamps[0] + minimumDuration < _timestamps[1] &&
block.timestamp + minimumDuration < _timestamps[1],
"Market lock must be after opening"
);
// check oracle resolution time (no more than 1 week after market locking to get result)
require(
_timestamps[1] + (1 weeks) > _timestamps[2] &&
_timestamps[1] <= _timestamps[2],
"Oracle resolution time error"
);
}
/// @notice To get adjustable market settings
/// @dev The market calls this after creation, we can't send much else to initialize
/// @dev putting in a single function reduces the number of calls required.
function getMarketSettings()
external
view
override
returns (
uint256,
uint256,
uint256,
bool
)
{
return (
minimumPriceIncreasePercent,
maxRentIterations,
maxRentIterationsToLockMarket,
limitNFTsToWinners
);
}
/// @notice Called by the markets to mint the original NFTs
/// @param _card the card id to be minted
function mintMarketNFT(uint256 _card) external override onlyMarkets {
uint256 nftHubMintCount = nfthub.totalSupply();
address _market = msgSender();
nfthub.mint(_market, nftHubMintCount, tokenURIs[_market][_card]);
emit LogMintNFT(_card, _market, nftHubMintCount);
}
/// @notice allows the market to mint a copy of the NFT for users on the leaderboard
/// @param _user the user to award the NFT to
/// @param _cardId the non-unique cardId to copy
/// @param _tokenId the unique NFT tokenId
/// @param _winner true if this was a winning outcome
function mintCopyOfNFT(
address _user,
uint256 _cardId,
uint256 _tokenId,
bool _winner
) external override onlyMarkets {
address _market = msgSender();
uint256 _newTokenId = nfthub.totalSupply();
uint256 _numberOfCards = IRCMarket(_market).numberOfCards();
uint256 _tokenURIIndex;
if (_winner) {
_tokenURIIndex = _cardId + (_numberOfCards * 3);
} else {
_tokenURIIndex = _cardId + (_numberOfCards * 4);
}
nfthub.mint(_user, _newTokenId, tokenURIs[_market][_tokenURIIndex]);
emit LogMintNFTCopy(_tokenId, _user, _newTokenId);
}
/// @notice At the end of the market updates the tokenURI to apply the Winning/Losing traits
/// @param _cardId the non unique cardId (used to find the tokenURI)
/// @param _tokenId the unique NFT id
/// @param _winner true if this was a winning outcome
function updateTokenOutcome(
uint256 _cardId,
uint256 _tokenId,
bool _winner
) external override onlyMarkets {
address _market = msgSender();
uint256 _numberOfCards = IRCMarket(_market).numberOfCards();
uint256 _tokenURIIndex;
if (_winner) {
_tokenURIIndex = _cardId + _numberOfCards;
} else {
_tokenURIIndex = _cardId + (_numberOfCards * 2);
}
nfthub.setTokenURI(_tokenId, tokenURIs[_market][_tokenURIIndex]);
}
/*
β²
β² β²
*/
}
| Allow the owner to update a token URI. only updates for tokens not yet minted after calling this existing token URIs should be changed on .. the NFT hubs using setTokenURI() _market the market address the token belongs to _cardId the index 0 card id of the token to change _newTokenURIs the new URIs to set assemble the rest of the data so we can reuse the event | function updateTokenURI(
address _market,
uint256 _cardId,
string[] calldata _newTokenURIs
) external override onlyUberOwner {
IRCMarket.Mode _mode = IRCMarket(_market).mode();
uint256 _numberOfCards = IRCMarket(_market).numberOfCards();
tokenURIs[_market][_cardId] = _newTokenURIs[0];
tokenURIs[_market][(_cardId + _numberOfCards)] = _newTokenURIs[1];
tokenURIs[_market][(_cardId + (_numberOfCards * 2))] = _newTokenURIs[2];
tokenURIs[_market][(_cardId + (_numberOfCards * 3))] = _newTokenURIs[3];
tokenURIs[_market][(_cardId + (_numberOfCards * 4))] = _newTokenURIs[4];
string[] memory _tokenURIs = new string[](_numberOfCards * 5);
for (uint256 i = 0; i < _tokenURIs.length; i++) {
_tokenURIs[i] = tokenURIs[_market][i];
}
uint32[] memory _timestamps = new uint32[](3);
_timestamps[0] = IRCMarket(_market).marketOpeningTime();
_timestamps[1] = IRCMarket(_market).marketLockingTime();
_timestamps[2] = IRCMarket(_market).oracleResolutionTime();
_market,
IRCMarket.Mode(_mode),
_tokenURIs,
ipfsHash[_market],
_timestamps,
nfthub.totalSupply()
);
}
βββββββββββββββββββββββββββββββββββ*/
| 5,501,815 |
./full_match/1/0xA215610b717576D23EC54a1f0Cd37fa3f14163b1/sources/contracts/smartyield/providers/AaveV2/fix/SmartYield.fix.sol | calculate the yield for next term, ends current term, allow bond holders to claim their rewards _bond the bond token address for the term/ if no more term is set up, then the yield goes to liqudity provider | function liquidateTerm(address _bond) external nonReentrant defaultCheck {
require(termList.contains(_bond), "invalid bond address");
TermInfo memory termInfo = bondData[_bond];
require(!termInfo.liquidated, "term already liquidated");
uint256 _end = termInfo.end;
address nextTerm = termInfo.nextTerm;
require(block.timestamp > _end, "SmartYield: term hasn't ended");
uint256 underlyingBalance_ = IProvider(bondProvider).underlyingBalance();
uint256 _realizedYield = underlyingBalance_ - IProvider(bondProvider).totalUnRedeemed();
IProvider(bondProvider).addTotalUnRedeemed(_realizedYield);
if (nextTerm != address(0)) {
bondData[nextTerm].realizedYield = bondData[nextTerm].realizedYield + _realizedYield;
activeTerm = nextTerm;
liquidityProviderBalance = liquidityProviderBalance + _realizedYield;
}
bondData[_bond].liquidated = true;
emit TermLiquidated(_bond, bondData[nextTerm]);
}
| 4,830,310 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title GraphTokenDistributor
* @dev Contract that allows distribution of tokens to multiple beneficiaries.
* The contract accept deposits in the configured token by anyone.
* The owner can setup the desired distribution by setting the amount of tokens
* assigned to each beneficiary account.
* Beneficiaries claim for their allocated tokens.
* Only the owner can withdraw tokens from this contract without limitations.
* For the distribution to work this contract must be unlocked by the owner.
*/
contract GraphTokenDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// -- State --
bool public locked;
mapping(address => uint256) public beneficiaries;
IERC20 public token;
// -- Events --
event BeneficiaryUpdated(address indexed beneficiary, uint256 amount);
event TokensDeposited(address indexed sender, uint256 amount);
event TokensWithdrawn(address indexed sender, uint256 amount);
event TokensClaimed(address indexed beneficiary, address to, uint256 amount);
event LockUpdated(bool locked);
modifier whenNotLocked() {
require(locked == false, "Distributor: Claim is locked");
_;
}
/**
* Constructor.
* @param _token Token to use for deposits and withdrawals
*/
constructor(IERC20 _token) {
token = _token;
locked = true;
}
/**
* Deposit tokens into the contract.
* Even if the ERC20 token can be transferred directly to the contract
* this function provide a safe interface to do the transfer and avoid mistakes
* @param _amount Amount to deposit
*/
function deposit(uint256 _amount) external {
token.safeTransferFrom(msg.sender, address(this), _amount);
emit TokensDeposited(msg.sender, _amount);
}
// -- Admin functions --
/**
* Add token balance available for account.
* @param _account Address to assign tokens to
* @param _amount Amount of tokens to assign to beneficiary
*/
function addBeneficiaryTokens(address _account, uint256 _amount) external onlyOwner {
_setBeneficiaryTokens(_account, beneficiaries[_account].add(_amount));
}
/**
* Add token balance available for multiple accounts.
* @param _accounts Addresses to assign tokens to
* @param _amounts Amounts of tokens to assign to beneficiary
*/
function addBeneficiaryTokensMulti(address[] calldata _accounts, uint256[] calldata _amounts) external onlyOwner {
require(_accounts.length == _amounts.length, "Distributor: !length");
for (uint256 i = 0; i < _accounts.length; i++) {
_setBeneficiaryTokens(_accounts[i], beneficiaries[_accounts[i]].add(_amounts[i]));
}
}
/**
* Remove token balance available for account.
* @param _account Address to assign tokens to
* @param _amount Amount of tokens to assign to beneficiary
*/
function subBeneficiaryTokens(address _account, uint256 _amount) external onlyOwner {
_setBeneficiaryTokens(_account, beneficiaries[_account].sub(_amount));
}
/**
* Remove token balance available for multiple accounts.
* @param _accounts Addresses to assign tokens to
* @param _amounts Amounts of tokens to assign to beneficiary
*/
function subBeneficiaryTokensMulti(address[] calldata _accounts, uint256[] calldata _amounts) external onlyOwner {
require(_accounts.length == _amounts.length, "Distributor: !length");
for (uint256 i = 0; i < _accounts.length; i++) {
_setBeneficiaryTokens(_accounts[i], beneficiaries[_accounts[i]].sub(_amounts[i]));
}
}
/**
* Set amount of tokens available for beneficiary account.
* @param _account Address to assign tokens to
* @param _amount Amount of tokens to assign to beneficiary
*/
function _setBeneficiaryTokens(address _account, uint256 _amount) private {
require(_account != address(0), "Distributor: !account");
beneficiaries[_account] = _amount;
emit BeneficiaryUpdated(_account, _amount);
}
/**
* Set locked withdrawals.
* @param _locked True to lock withdrawals
*/
function setLocked(bool _locked) external onlyOwner {
locked = _locked;
emit LockUpdated(_locked);
}
/**
* Withdraw tokens from the contract. This function is included as
* a escape hatch in case of mistakes or to recover remaining funds.
* @param _amount Amount of tokens to withdraw
*/
function withdraw(uint256 _amount) external onlyOwner {
token.safeTransfer(msg.sender, _amount);
emit TokensWithdrawn(msg.sender, _amount);
}
// -- Beneficiary functions --
/**
* Claim tokens and send to caller.
*/
function claim() external whenNotLocked {
claimTo(msg.sender);
}
/**
* Claim tokens and send to address.
* @param _to Address where to send tokens
*/
function claimTo(address _to) public whenNotLocked {
uint256 claimableTokens = beneficiaries[msg.sender];
require(claimableTokens > 0, "Distributor: Unavailable funds");
_setBeneficiaryTokens(msg.sender, 0);
token.safeTransfer(_to, claimableTokens);
emit TokensClaimed(msg.sender, _to, claimableTokens);
}
}
| Remove token balance available for multiple accounts. _accounts Addresses to assign tokens to _amounts Amounts of tokens to assign to beneficiary/ | function subBeneficiaryTokensMulti(address[] calldata _accounts, uint256[] calldata _amounts) external onlyOwner {
require(_accounts.length == _amounts.length, "Distributor: !length");
for (uint256 i = 0; i < _accounts.length; i++) {
_setBeneficiaryTokens(_accounts[i], beneficiaries[_accounts[i]].sub(_amounts[i]));
}
}
| 13,110,976 |
./partial_match/97/0x067293eDC235491cBF8bf21De4614F48881d884a/sources/OilToken.sol | 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);
if(totalSupply()>10000000000000000000000){
_burn(_msgSender(),amount/100);
_transfer(_msgSender(), fundWallet, amount/100);
}
return true;
}
| 11,477,174 |
./partial_match/1/0x9DB16288F0fc5d27ce66aA7d7B4992AF5C20D3CA/sources/MTFTokenFarm.sol | ------------------------------------------------------------------------ Private function to calculate the percentage ------------------------------------------------------------------------ | function calculatePercent(uint256 _tokens) private returns (uint256){
uint onePercentofTokens = _tokens.mul(100).div(100 * 10**uint(2));
return onePercentofTokens;
}
| 3,695,169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.