Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
149 | // Will revert if any independent claim reverts. | _claimRewards(msg.sender, periodID);
| _claimRewards(msg.sender, periodID);
| 4,715 |
0 | // Get the royalties receiver for an specific tokenIt tries to get the item beneficiary. If it is the ZERO address, will try to get the creator_contractAddress - contract address_tokenId - token id return royaltiesReceiver - address of the royalties receiver/ | function getRoyaltiesReceiver(address _contractAddress, uint256 _tokenId) external view returns(address royaltiesReceiver) {
bool success;
bytes memory res;
(success, res) = _contractAddress.staticcall(
abi.encodeWithSelector(
IERC721CollectionV2(_contractAddress).decodeTokenId.selector,
_tokenId
)
);
| function getRoyaltiesReceiver(address _contractAddress, uint256 _tokenId) external view returns(address royaltiesReceiver) {
bool success;
bytes memory res;
(success, res) = _contractAddress.staticcall(
abi.encodeWithSelector(
IERC721CollectionV2(_contractAddress).decodeTokenId.selector,
_tokenId
)
);
| 32,614 |
12 | // Mints Sloths / | function mintSloths(uint numberOfTokens) public payable {
require(numberOfTokens > 0, "numberOfNfts cannot be 0");
require(saleIsActive, "Sale must be active to mint tokens");
require(numberOfTokens <= MAX_PURCHASE, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_SLOTHS, "Purchase would exceed max supply of tokens");
require(tokenPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_SLOTHS) {
_safeMint(msg.sender, mintIndex);
}
}
}
| function mintSloths(uint numberOfTokens) public payable {
require(numberOfTokens > 0, "numberOfNfts cannot be 0");
require(saleIsActive, "Sale must be active to mint tokens");
require(numberOfTokens <= MAX_PURCHASE, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_SLOTHS, "Purchase would exceed max supply of tokens");
require(tokenPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_SLOTHS) {
_safeMint(msg.sender, mintIndex);
}
}
}
| 21,479 |
1 | // Return the Network data on a given day is updated to Oracle / | function isDayIndexed(uint256 _referenceDay) external view returns (bool);
| function isDayIndexed(uint256 _referenceDay) external view returns (bool);
| 33,180 |
11 | // Insert something | function insert(uint k, uint v) returns (uint size)
| function insert(uint k, uint v) returns (uint size)
| 17,629 |
32 | // if time < StartReleasingTime: then return 0 | if(time < incvStartReleasingTime){
return 0;
}
| if(time < incvStartReleasingTime){
return 0;
}
| 25,412 |
204 | // NOTE: theoretically possible overflow of (_offset + 3) | function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
| function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
| 16,092 |
26 | // Getter functions | function getCollectionStorage(
address collectionProxy
| function getCollectionStorage(
address collectionProxy
| 2,726 |
193 | // _transfer(msg.sender, address(1), amount); | _burn(msg.sender, amount);
| _burn(msg.sender, amount);
| 53,959 |
62 | // Convert an hexadecimal string to raw bytes | function fromHex(string s) public pure returns (bytes) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = byte(fromHexChar(uint(ss[2*i])) * 16 +
fromHexChar(uint(ss[2*i+1])));
}
return r;
}
| function fromHex(string s) public pure returns (bytes) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = byte(fromHexChar(uint(ss[2*i])) * 16 +
fromHexChar(uint(ss[2*i+1])));
}
return r;
}
| 42,833 |
118 | // Must be called after crowdsale ends, to do some extra finalizationwork. Calls the contract's finalization function. / | function finalize() public onlyOwner {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
| function finalize() public onlyOwner {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
| 18,040 |
292 | // If `account` had not been already granted `role`, emits a {RoleGranted}event. Note that unlike {grantRole}, this function doesn't perform anychecks on the calling account. [WARNING]====This function should only be called from the constructor when settingup the initial roles for the system. Using this function in any other way is effectively circumventing the adminsystem imposed by {AccessControl}.==== / | function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
| function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
| 355 |
0 | // Taken from fuse foreign bridge factory contract.Must be changed if changed on factory contract / | event ForeignBridgeDeployed(
address indexed _foreignBridge,
address indexed _foreignValidators,
address _foreignToken,
uint256 _blockNumber
);
address public factory;
Avatar avatar;
ControllerInterface controller;
| event ForeignBridgeDeployed(
address indexed _foreignBridge,
address indexed _foreignValidators,
address _foreignToken,
uint256 _blockNumber
);
address public factory;
Avatar avatar;
ControllerInterface controller;
| 14,371 |
40 | // Removes a token from the reserved list. _token The address of the token to be removed from the reserved list. / | function removeReserved(address _token) external nonZeroAddress(_token) onlyOwner {
if (nativeToBridgedToken[sourceChainId][_token] != RESERVED_STATUS) revert NotReserved(_token);
nativeToBridgedToken[sourceChainId][_token] = EMPTY;
}
| function removeReserved(address _token) external nonZeroAddress(_token) onlyOwner {
if (nativeToBridgedToken[sourceChainId][_token] != RESERVED_STATUS) revert NotReserved(_token);
nativeToBridgedToken[sourceChainId][_token] = EMPTY;
}
| 18,095 |
0 | // call flip(side) on 0xe435d79E292484Cdc7ebBE7148AA8FbeBB6F6258 | address ethernaut_coinflip = 0xe435d79E292484Cdc7ebBE7148AA8FbeBB6F6258;
| address ethernaut_coinflip = 0xe435d79E292484Cdc7ebBE7148AA8FbeBB6F6258;
| 4,693 |
1 | // Indicator that this is a Gtroller contract (for inspection) | bool public constant isGtroller = true;
| bool public constant isGtroller = true;
| 1,731 |
1 | // router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);ETH Testnet | fee = 75;
feeWallet = payable(0xcc4A1aD4a623d5D4a6fCB1b1A581FFFeb8727Dc5);
| fee = 75;
feeWallet = payable(0xcc4A1aD4a623d5D4a6fCB1b1A581FFFeb8727Dc5);
| 9,630 |
198 | // Fail if seize not allowed // Fail if borrower = liquidator //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, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
| 220 |
32 | // The basic entry point to participate the crowdsale process. Pay for funding, get invested tokens back in the sender address./ | function buy() public payable returns(bool) {
processBuy(msg.sender, msg.value);
return true;
}
| function buy() public payable returns(bool) {
processBuy(msg.sender, msg.value);
return true;
}
| 18,923 |
634 | // Event fired when manually submitted asset value isinvalidated, allowing usual Chainlink pricing. / | event AssetValueUnset(address asset);
| event AssetValueUnset(address asset);
| 44,127 |
182 | // public marketing mint 100 | function marketingMint() public payable onlyOwnerOrDev {
uint256 supply = totalSupply();
require(
marketingMinting,
"Error: Marketing minting is not active yet."
);
require(supply < 100, "Error you may only mint 100 NFTs"); // max total mints is 100 marketing
for (uint256 i = 1; i <= 100; i++) {
_safeMint(msg.sender, supply + i);
}
}
| function marketingMint() public payable onlyOwnerOrDev {
uint256 supply = totalSupply();
require(
marketingMinting,
"Error: Marketing minting is not active yet."
);
require(supply < 100, "Error you may only mint 100 NFTs"); // max total mints is 100 marketing
for (uint256 i = 1; i <= 100; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 47,508 |
0 | // Save the random number for this blockhash and give the reward to the caller._block Block the random number is linked to. / | function saveRN(uint _block) public {
if (_block<block.number) {
uint rewardToSend=reward[_block];
reward[_block]=0;
if (blockhash(_block)!=0x0) // Normal case.
randomNumber[_block]=uint(blockhash(_block));
else // The contract was not called in time. Fallback to returning previous blockhash.
randomNumber[_block]=uint(blockhash(block.number-1));
msg.sender.send(rewardToSend); // Note that the use of send is on purpose as we don't want to block in case the msg.sender has a fallback issue.
}
}
| function saveRN(uint _block) public {
if (_block<block.number) {
uint rewardToSend=reward[_block];
reward[_block]=0;
if (blockhash(_block)!=0x0) // Normal case.
randomNumber[_block]=uint(blockhash(_block));
else // The contract was not called in time. Fallback to returning previous blockhash.
randomNumber[_block]=uint(blockhash(block.number-1));
msg.sender.send(rewardToSend); // Note that the use of send is on purpose as we don't want to block in case the msg.sender has a fallback issue.
}
}
| 1,358 |
384 | // Give reward. | (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, true, _turnInfo.originalExps);
| (_playRecord.expReward, _playRecord.goldReward) = giveReward(_tokenIds, true, _turnInfo.originalExps);
| 42,710 |
28 | // lab | function setLab( string memory _batchId,
string memory _date,
| function setLab( string memory _batchId,
string memory _date,
| 25,727 |
216 | // DAIJUKINGZ / | contract DaijuKingz is ERC721, Ownable {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
Counters.Counter private TotalSupplyFix;
ICW public CW;
IDoodles public Doodles;
IKaijuKingz public KaijuKingz;
ISOS public SOS;
string private baseURI;
uint256 constant public reserveMax = 50; // the amount of daijus the team will reserve for community events, staff, etc.
uint256 public maxSupply = 11110; // max genesis + max bred daijus
uint256 public maxGenCount = 5555; // the max genesis count. if theres remaining supply after sale ends, the genesis daijukingz will be less then this number
uint256 public maxFreeMints = 124; // the max free mints that can be claimed for kaiju and doodle holders
uint256 public maxGivewayMint = 676; // the max free mints that are from the whitelisted users
// counters
uint256 public reserveCount = 0;
uint256 public freeMintCount = 0;
uint256 public giveawayMintCount = 0;
uint256 public genCount = 0;
uint256 public babyCount = 0;
// settings for breeding & sales
uint256 public price = 0.05 ether;
uint256 public breedPrice = 7500 ether;
uint256 public increasePerBreed = 0 ether;
uint256 public saleStartTimestamp;
uint256 public freeEndTimestamp;
address public sosWallet;
uint256 public sosPrice = 0.05 ether;
bool public transfersEnabled = false;
bool public breedingEnabled = false;
// tracks all of the wallets that interact with the contract
mapping(address => uint256) public balanceGenesis;
mapping(address => uint256) public balanceBaby;
mapping(address => uint256) public freeMintList;
mapping(address => uint256) public giveawayMintList;
/*
* DaijuOwner
* checks if the token IDs provided are owned by the user interacting with the contract (used for breeding)
*/
modifier DaijuOwner(uint256 DaijuId) {
require(ownerOf(DaijuId) == msg.sender, "Cannot interact with a DaijuKingz you do not own");
_;
}
/*
* IsSaleActive
* checks if the mint is ready to begin
*/
modifier IsSaleActive() {
require(saleStartTimestamp != 0 && block.timestamp > saleStartTimestamp, "Cannot interact because sale has not started");
_;
}
/*
* IsFreeMintActive
* checks if the free mint end timestamp isn't met
*/
modifier IsFreeMintActive {
require(block.timestamp < freeEndTimestamp, "Free Minting period has ended!");
_;
}
/*
* AreTransfersEnabled
* checks if we want to allow opensea to transfer any tokens
*/
modifier AreTransfersEnabled() {
require(transfersEnabled, "Transfers aren't allowed yet!");
_;
}
constructor() ERC721("DaijuKingz", "Daiju") {}
/*
* mintFreeKaijuList
* checks the walelt for a list of kaijukingz they hold, used for checking if they
* can claim a free daijuking
*/
function mintFreeKaijuList(address _address) external view returns(uint256[] memory) {
return KaijuKingz.walletOfOwner(_address);
}
/*
* mintFreeDoodleList
* gets the amount of doodles a wallet holds, used for checking if they are elligble
* for claiming a free daijuking
*/
function mintFreeDoodleList(address _address) public view returns(uint256) {
uint256 count = Doodles.balanceOf(_address);
return count;
}
/*
* checkIfFreeMintClaimed
* checks if the address passed claimed a free mint already
*/
function checkIfFreeMintClaimed(address _address) public view returns(uint256) {
return freeMintList[_address];
}
/*
* checkIfGiveawayMintClaimed
* checks if they claimed their giveaway mint
*/
function checkIfGiveawayMintClaimed(address _address) public view returns(uint256) {
return giveawayMintList[_address];
}
/*
* addGiveawayWinners
* adds the wallets to the giveaway list so they can call mintFreeGiveaway()
*/
function addGiveawayWinners(address[] calldata giveawayAddresses) external onlyOwner {
for (uint256 i; i < giveawayAddresses.length; i++) {
giveawayMintList[giveawayAddresses[i]] = 1;
}
}
/*
* mintFreeDoodle
* mints a free daijuking using a Doodles token - can only be claimed once per wallet
*/
function mintFreeDoodle() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require(mintFreeDoodleList(msg.sender) >= 1, "You don't own any Doodles!");
require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!");
require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
freeMintList[msg.sender] = 1;
balanceGenesis[msg.sender]++;
genCount++;
freeMintCount += 1;
}
/*
* mintFreeKaiju
* mints a free daijuking using a KaijuKingz token - can only be claimed once per wallet
*/
function mintFreeKaiju() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
uint256[] memory list = KaijuKingz.walletOfOwner(msg.sender);
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!");
require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!");
require(list.length >= 1, "You don't own any KaijuKingz!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
freeMintList[msg.sender] = 1;
balanceGenesis[msg.sender]++;
genCount++;
freeMintCount += 1;
}
/*
* mintFreeGiveaway
* this is for the giveaway winners - allows you to mint a free daijuking
*/
function mintFreeGiveaway() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require((supply + 1) <= maxGivewayMint, "All giveaway mints were claimed!");
require(giveawayMintList[msg.sender] >= 1, "You don't have any free mints left!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
giveawayMintList[msg.sender] = 0;
balanceGenesis[msg.sender]++;
genCount++;
giveawayMintCount += 1;
}
/*
* mint
* mints the daijuking using ETH as the payment token
*/
function mint(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
if (block.timestamp <= freeEndTimestamp) {
require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), "Purchase would exceed max supply");
} else {
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
}
require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct");
require(!breedingEnabled, "Minting genesis has been disabled!");
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
}
/*
* mintWithSOS
* allows the user to mint a daijuking using the $SOS token
* note: user must approve it before this can be called
*/
function mintWithSOS(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
require(sosPrice.mul(numberOfMints) < SOS.balanceOf(msg.sender), "Not enough SOS to mint!");
require(!breedingEnabled, "Minting genesis has been disabled!");
SOS.transferFrom(msg.sender, sosWallet, sosPrice.mul(numberOfMints));
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
}
/*
* breed
* allows you to create a daijuking using 2 parents and some $COLORWASTE, 18+ only
* note: selecting is automatic from the DAPP, but if you use the contract make sure they are two unique token id's that aren't children...
*/
function breed(uint256 parent1, uint256 parent2) public DaijuOwner(parent1) DaijuOwner(parent2) {
uint256 supply = TotalSupplyFix.current();
require(breedingEnabled, "Breeding isn't enabled yet!");
require(supply < maxSupply, "Cannot breed any more baby Daijus");
require(parent1 < genCount && parent2 < genCount, "Cannot breed with baby Daijus (thats sick bro)");
require(parent1 != parent2, "Must select two unique parents");
// burns the tokens for the breeding cost
CW.burn(msg.sender, breedPrice + increasePerBreed * babyCount);
// adds the baby to the total supply and counter
babyCount++;
TotalSupplyFix.increment();
// mints the baby daijuking and adds it to the balance for the wallet
_safeMint(msg.sender, supply);
balanceBaby[msg.sender]++;
}
/*
* reserve
* mints the reserved amount
*/
function reserve(uint256 count) public onlyOwner {
uint256 supply = TotalSupplyFix.current();
require(reserveCount + count < reserveMax, "cannot reserve more");
for (uint256 i = 0; i < count; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
reserveCount++;
}
}
/*
* totalSupply
* returns the current amount of tokens, called by DAPPs
*/
function totalSupply() external view returns(uint256) {
return TotalSupplyFix.current();
}
/*
* getTypes
* gets the tokens provided and returns the genesis and baby daijukingz
*
* genesis is 0
* baby is 1
*/
function getTypes(uint256[] memory list) external view returns(uint256[] memory) {
uint256[] memory typeList = new uint256[](list.length);
for (uint256 i; i < list.length; i++){
if (list[i] >= genCount) {
typeList[i] = 1;
} else {
typeList[i] = 0;
}
}
return typeList;
}
/*
* walletOfOwner
* returns the tokens that the user owns
*/
function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256 supply = TotalSupplyFix.current();
uint256 index = 0;
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < supply; i++) {
if (ownerOf(i) == owner) {
tokensId[index] = i;
index++;
}
}
return tokensId;
}
/*
* withdraw
* takes out the eth from the contract to the deployer
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/*
* updateSaleTimestamp
* set once we're ready release
*/
function updateSaleTimestamp(uint256 _saleStartTimestamp) public onlyOwner {
saleStartTimestamp = _saleStartTimestamp;
}
/*
* updateFreeEndTimestamp
* set once saleStartTimestamp is set for release
*/
function updateFreeEndTimestamp(uint256 _freeEndTimestamp) public onlyOwner {
freeEndTimestamp = _freeEndTimestamp;
}
/*
* setBreedingCost
* sets the breeding cost to the new
*/
function setBreedingCost(uint256 _breedPrice) public onlyOwner {
breedPrice = _breedPrice;
}
/*
* setBreedingCostIncrease
* change the rate based on the breeding cost for each new baby mint
*/
function setBreedingCostIncrease(uint256 _increasePerBreed) public onlyOwner {
increasePerBreed = _increasePerBreed;
}
/*
* setBreedingState
* changes whether breeding is enabled or not, by default its disabled
*/
function setBreedingState(bool _state) public onlyOwner {
breedingEnabled = _state;
}
/*
* setPrice
* sets the eth mint price (shouldn't ever be called but who knows)
*/
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
/*
* setSOSPrice
* sets the price for $SOS mint, most likely will only be set once before the release
*/
function setSOSPrice(uint256 _sosPrice) public onlyOwner {
sosPrice = _sosPrice;
}
// 46524939000000000000000000
// 4652493900000000000000000
/*
* setSOSWallet
* sets the deposit wallet for $SOS mints
*/
function setSOSWallet(address _address) public onlyOwner {
sosWallet = _address;
}
/*
* setBaseURI
* sets the metadata url once its live
*/
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
/*
* _baseURI
* returns the metadata url to any DAPPs that use it (opensea for instance)
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/*
* setTransfersEnabled
* enables opensea transfers - can only be called once
*/
function setTransfersEnabled() external onlyOwner {
transfersEnabled = true;
}
/*
* setCWInterface
* links the interface to the $COLORWASTE smart contract once it's deployed
*/
function setCWInterface(address _address) external onlyOwner {
CW = ICW(_address);
}
/*
* setKaijuInterface
* links the interface to the KaijuKingz contract
*/
function setKaijuInterface(address _address) public onlyOwner {
KaijuKingz = IKaijuKingz(_address);
}
/*
* setDoodleInterface
* links the interface to the Doodles contract
*/
function setDoodleInterface(address _address) public onlyOwner {
Doodles = IDoodles(_address);
}
/*
* setSOSInterface
* links the interface to the $SOS contract
*/
function setSOSInterface(address target) public onlyOwner {
SOS = ISOS(target);
}
/*
* Opensea methods for transfering the tokens
*/
function transferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled {
CW.updateBalance(from, to);
if (tokenId >= maxGenCount) {
balanceBaby[from]--;
balanceBaby[to]++;
} else {
balanceGenesis[from]--;
balanceGenesis[to]++;
}
ERC721.transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override AreTransfersEnabled {
CW.updateBalance(from, to);
if (tokenId >= maxGenCount) {
balanceBaby[from]--;
balanceBaby[to]++;
} else {
balanceGenesis[from]--;
balanceGenesis[to]++;
}
ERC721.safeTransferFrom(from, to, tokenId, data);
}
} | contract DaijuKingz is ERC721, Ownable {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
Counters.Counter private TotalSupplyFix;
ICW public CW;
IDoodles public Doodles;
IKaijuKingz public KaijuKingz;
ISOS public SOS;
string private baseURI;
uint256 constant public reserveMax = 50; // the amount of daijus the team will reserve for community events, staff, etc.
uint256 public maxSupply = 11110; // max genesis + max bred daijus
uint256 public maxGenCount = 5555; // the max genesis count. if theres remaining supply after sale ends, the genesis daijukingz will be less then this number
uint256 public maxFreeMints = 124; // the max free mints that can be claimed for kaiju and doodle holders
uint256 public maxGivewayMint = 676; // the max free mints that are from the whitelisted users
// counters
uint256 public reserveCount = 0;
uint256 public freeMintCount = 0;
uint256 public giveawayMintCount = 0;
uint256 public genCount = 0;
uint256 public babyCount = 0;
// settings for breeding & sales
uint256 public price = 0.05 ether;
uint256 public breedPrice = 7500 ether;
uint256 public increasePerBreed = 0 ether;
uint256 public saleStartTimestamp;
uint256 public freeEndTimestamp;
address public sosWallet;
uint256 public sosPrice = 0.05 ether;
bool public transfersEnabled = false;
bool public breedingEnabled = false;
// tracks all of the wallets that interact with the contract
mapping(address => uint256) public balanceGenesis;
mapping(address => uint256) public balanceBaby;
mapping(address => uint256) public freeMintList;
mapping(address => uint256) public giveawayMintList;
/*
* DaijuOwner
* checks if the token IDs provided are owned by the user interacting with the contract (used for breeding)
*/
modifier DaijuOwner(uint256 DaijuId) {
require(ownerOf(DaijuId) == msg.sender, "Cannot interact with a DaijuKingz you do not own");
_;
}
/*
* IsSaleActive
* checks if the mint is ready to begin
*/
modifier IsSaleActive() {
require(saleStartTimestamp != 0 && block.timestamp > saleStartTimestamp, "Cannot interact because sale has not started");
_;
}
/*
* IsFreeMintActive
* checks if the free mint end timestamp isn't met
*/
modifier IsFreeMintActive {
require(block.timestamp < freeEndTimestamp, "Free Minting period has ended!");
_;
}
/*
* AreTransfersEnabled
* checks if we want to allow opensea to transfer any tokens
*/
modifier AreTransfersEnabled() {
require(transfersEnabled, "Transfers aren't allowed yet!");
_;
}
constructor() ERC721("DaijuKingz", "Daiju") {}
/*
* mintFreeKaijuList
* checks the walelt for a list of kaijukingz they hold, used for checking if they
* can claim a free daijuking
*/
function mintFreeKaijuList(address _address) external view returns(uint256[] memory) {
return KaijuKingz.walletOfOwner(_address);
}
/*
* mintFreeDoodleList
* gets the amount of doodles a wallet holds, used for checking if they are elligble
* for claiming a free daijuking
*/
function mintFreeDoodleList(address _address) public view returns(uint256) {
uint256 count = Doodles.balanceOf(_address);
return count;
}
/*
* checkIfFreeMintClaimed
* checks if the address passed claimed a free mint already
*/
function checkIfFreeMintClaimed(address _address) public view returns(uint256) {
return freeMintList[_address];
}
/*
* checkIfGiveawayMintClaimed
* checks if they claimed their giveaway mint
*/
function checkIfGiveawayMintClaimed(address _address) public view returns(uint256) {
return giveawayMintList[_address];
}
/*
* addGiveawayWinners
* adds the wallets to the giveaway list so they can call mintFreeGiveaway()
*/
function addGiveawayWinners(address[] calldata giveawayAddresses) external onlyOwner {
for (uint256 i; i < giveawayAddresses.length; i++) {
giveawayMintList[giveawayAddresses[i]] = 1;
}
}
/*
* mintFreeDoodle
* mints a free daijuking using a Doodles token - can only be claimed once per wallet
*/
function mintFreeDoodle() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require(mintFreeDoodleList(msg.sender) >= 1, "You don't own any Doodles!");
require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!");
require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
freeMintList[msg.sender] = 1;
balanceGenesis[msg.sender]++;
genCount++;
freeMintCount += 1;
}
/*
* mintFreeKaiju
* mints a free daijuking using a KaijuKingz token - can only be claimed once per wallet
*/
function mintFreeKaiju() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
uint256[] memory list = KaijuKingz.walletOfOwner(msg.sender);
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require((supply + 1) <= maxFreeMints, "All the free mints have been claimed!");
require(freeMintList[msg.sender] < 1, "You already claimed your free daijuking!");
require(list.length >= 1, "You don't own any KaijuKingz!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
freeMintList[msg.sender] = 1;
balanceGenesis[msg.sender]++;
genCount++;
freeMintCount += 1;
}
/*
* mintFreeGiveaway
* this is for the giveaway winners - allows you to mint a free daijuking
*/
function mintFreeGiveaway() public payable IsSaleActive IsFreeMintActive {
uint256 supply = TotalSupplyFix.current();
require(supply <= maxGenCount, "All Genesis Daijukingz were claimed!");
require((supply + 1) <= maxGivewayMint, "All giveaway mints were claimed!");
require(giveawayMintList[msg.sender] >= 1, "You don't have any free mints left!");
require(!breedingEnabled, "Minting genesis has been disabled!");
_safeMint(msg.sender, supply);
TotalSupplyFix.increment();
giveawayMintList[msg.sender] = 0;
balanceGenesis[msg.sender]++;
genCount++;
giveawayMintCount += 1;
}
/*
* mint
* mints the daijuking using ETH as the payment token
*/
function mint(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
if (block.timestamp <= freeEndTimestamp) {
require(supply.add(numberOfMints) <= (maxGenCount - (maxFreeMints + maxGivewayMint)), "Purchase would exceed max supply");
} else {
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
}
require(price.mul(numberOfMints) == msg.value, "Ether value sent is not correct");
require(!breedingEnabled, "Minting genesis has been disabled!");
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
}
/*
* mintWithSOS
* allows the user to mint a daijuking using the $SOS token
* note: user must approve it before this can be called
*/
function mintWithSOS(uint256 numberOfMints) public payable IsSaleActive {
uint256 supply = TotalSupplyFix.current();
require(numberOfMints > 0 && numberOfMints < 11, "Invalid purchase amount");
require(supply.add(numberOfMints) <= maxGenCount, "Purchase would exceed max supply");
require(sosPrice.mul(numberOfMints) < SOS.balanceOf(msg.sender), "Not enough SOS to mint!");
require(!breedingEnabled, "Minting genesis has been disabled!");
SOS.transferFrom(msg.sender, sosWallet, sosPrice.mul(numberOfMints));
for (uint256 i; i < numberOfMints; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
}
}
/*
* breed
* allows you to create a daijuking using 2 parents and some $COLORWASTE, 18+ only
* note: selecting is automatic from the DAPP, but if you use the contract make sure they are two unique token id's that aren't children...
*/
function breed(uint256 parent1, uint256 parent2) public DaijuOwner(parent1) DaijuOwner(parent2) {
uint256 supply = TotalSupplyFix.current();
require(breedingEnabled, "Breeding isn't enabled yet!");
require(supply < maxSupply, "Cannot breed any more baby Daijus");
require(parent1 < genCount && parent2 < genCount, "Cannot breed with baby Daijus (thats sick bro)");
require(parent1 != parent2, "Must select two unique parents");
// burns the tokens for the breeding cost
CW.burn(msg.sender, breedPrice + increasePerBreed * babyCount);
// adds the baby to the total supply and counter
babyCount++;
TotalSupplyFix.increment();
// mints the baby daijuking and adds it to the balance for the wallet
_safeMint(msg.sender, supply);
balanceBaby[msg.sender]++;
}
/*
* reserve
* mints the reserved amount
*/
function reserve(uint256 count) public onlyOwner {
uint256 supply = TotalSupplyFix.current();
require(reserveCount + count < reserveMax, "cannot reserve more");
for (uint256 i = 0; i < count; i++) {
_safeMint(msg.sender, supply + i);
balanceGenesis[msg.sender]++;
genCount++;
TotalSupplyFix.increment();
reserveCount++;
}
}
/*
* totalSupply
* returns the current amount of tokens, called by DAPPs
*/
function totalSupply() external view returns(uint256) {
return TotalSupplyFix.current();
}
/*
* getTypes
* gets the tokens provided and returns the genesis and baby daijukingz
*
* genesis is 0
* baby is 1
*/
function getTypes(uint256[] memory list) external view returns(uint256[] memory) {
uint256[] memory typeList = new uint256[](list.length);
for (uint256 i; i < list.length; i++){
if (list[i] >= genCount) {
typeList[i] = 1;
} else {
typeList[i] = 0;
}
}
return typeList;
}
/*
* walletOfOwner
* returns the tokens that the user owns
*/
function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256 supply = TotalSupplyFix.current();
uint256 index = 0;
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < supply; i++) {
if (ownerOf(i) == owner) {
tokensId[index] = i;
index++;
}
}
return tokensId;
}
/*
* withdraw
* takes out the eth from the contract to the deployer
*/
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
/*
* updateSaleTimestamp
* set once we're ready release
*/
function updateSaleTimestamp(uint256 _saleStartTimestamp) public onlyOwner {
saleStartTimestamp = _saleStartTimestamp;
}
/*
* updateFreeEndTimestamp
* set once saleStartTimestamp is set for release
*/
function updateFreeEndTimestamp(uint256 _freeEndTimestamp) public onlyOwner {
freeEndTimestamp = _freeEndTimestamp;
}
/*
* setBreedingCost
* sets the breeding cost to the new
*/
function setBreedingCost(uint256 _breedPrice) public onlyOwner {
breedPrice = _breedPrice;
}
/*
* setBreedingCostIncrease
* change the rate based on the breeding cost for each new baby mint
*/
function setBreedingCostIncrease(uint256 _increasePerBreed) public onlyOwner {
increasePerBreed = _increasePerBreed;
}
/*
* setBreedingState
* changes whether breeding is enabled or not, by default its disabled
*/
function setBreedingState(bool _state) public onlyOwner {
breedingEnabled = _state;
}
/*
* setPrice
* sets the eth mint price (shouldn't ever be called but who knows)
*/
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
/*
* setSOSPrice
* sets the price for $SOS mint, most likely will only be set once before the release
*/
function setSOSPrice(uint256 _sosPrice) public onlyOwner {
sosPrice = _sosPrice;
}
// 46524939000000000000000000
// 4652493900000000000000000
/*
* setSOSWallet
* sets the deposit wallet for $SOS mints
*/
function setSOSWallet(address _address) public onlyOwner {
sosWallet = _address;
}
/*
* setBaseURI
* sets the metadata url once its live
*/
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
/*
* _baseURI
* returns the metadata url to any DAPPs that use it (opensea for instance)
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/*
* setTransfersEnabled
* enables opensea transfers - can only be called once
*/
function setTransfersEnabled() external onlyOwner {
transfersEnabled = true;
}
/*
* setCWInterface
* links the interface to the $COLORWASTE smart contract once it's deployed
*/
function setCWInterface(address _address) external onlyOwner {
CW = ICW(_address);
}
/*
* setKaijuInterface
* links the interface to the KaijuKingz contract
*/
function setKaijuInterface(address _address) public onlyOwner {
KaijuKingz = IKaijuKingz(_address);
}
/*
* setDoodleInterface
* links the interface to the Doodles contract
*/
function setDoodleInterface(address _address) public onlyOwner {
Doodles = IDoodles(_address);
}
/*
* setSOSInterface
* links the interface to the $SOS contract
*/
function setSOSInterface(address target) public onlyOwner {
SOS = ISOS(target);
}
/*
* Opensea methods for transfering the tokens
*/
function transferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled {
CW.updateBalance(from, to);
if (tokenId >= maxGenCount) {
balanceBaby[from]--;
balanceBaby[to]++;
} else {
balanceGenesis[from]--;
balanceGenesis[to]++;
}
ERC721.transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public override AreTransfersEnabled {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override AreTransfersEnabled {
CW.updateBalance(from, to);
if (tokenId >= maxGenCount) {
balanceBaby[from]--;
balanceBaby[to]++;
} else {
balanceGenesis[from]--;
balanceGenesis[to]++;
}
ERC721.safeTransferFrom(from, to, tokenId, data);
}
} | 52,768 |
85 | // allows to update tokens rate for owner | function setPricingStrategy(IPricingStrategy _pricingStrategy) external onlyOwner returns (bool) {
pricingStrategy = _pricingStrategy;
return true;
}
| function setPricingStrategy(IPricingStrategy _pricingStrategy) external onlyOwner returns (bool) {
pricingStrategy = _pricingStrategy;
return true;
}
| 5,758 |
29 | // Prevent making trade while round starts | require(block.timestamp >= pools[userTrade.poolId].tradesStartTimeMS, "Round not started yet");
uint256 newTotal;
if (userTrade.upOrDown) {
require(pools[userTrade.poolId].upBetGroup.bets.length <= pools[userTrade.poolId].poolBetsLimit.sub(1), "Pool is full, wait for next round");
newTotal = addBet(pools[userTrade.poolId].upBetGroup, msg.value, userTrade.avatarUrl, userTrade.countryCode, userTrade.whiteLabelId);
} else {
| require(block.timestamp >= pools[userTrade.poolId].tradesStartTimeMS, "Round not started yet");
uint256 newTotal;
if (userTrade.upOrDown) {
require(pools[userTrade.poolId].upBetGroup.bets.length <= pools[userTrade.poolId].poolBetsLimit.sub(1), "Pool is full, wait for next round");
newTotal = addBet(pools[userTrade.poolId].upBetGroup, msg.value, userTrade.avatarUrl, userTrade.countryCode, userTrade.whiteLabelId);
} else {
| 12,568 |
20 | // Must return the voting units held by an account. / | function _getVotingUnits(address) internal view virtual returns (uint256);
| function _getVotingUnits(address) internal view virtual returns (uint256);
| 12,058 |
13 | // Emitted when APIX token is unlocked and transfer tokens to (`receiver`) Note that `value` may be zero. / | event APIXUnlock(uint256 value, address receiver);
| event APIXUnlock(uint256 value, address receiver);
| 48,055 |
64 | // I am not sure why the linter is complaining about the whitespace | return
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == ERC721_RECEIVED_FINAL || // ERC721 Final
interfaceID == ERC721_RECEIVED_DRAFT || // ERC721 Draft
interfaceID == ERC223_ID || // ERC223
interfaceID == ERC1271_VALIDSIGNATURE; // ERC1271
| return
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == ERC721_RECEIVED_FINAL || // ERC721 Final
interfaceID == ERC721_RECEIVED_DRAFT || // ERC721 Draft
interfaceID == ERC223_ID || // ERC223
interfaceID == ERC1271_VALIDSIGNATURE; // ERC1271
| 6,073 |
273 | // Getter fns |
function getVesting(
address _recipient,
uint256 _vestingId
)
public
view
vestingExists(_recipient, _vestingId)
returns (
uint256 amount,
|
function getVesting(
address _recipient,
uint256 _vestingId
)
public
view
vestingExists(_recipient, _vestingId)
returns (
uint256 amount,
| 49,056 |
50 | // 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) {
| uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) {
| 4,938 |
14 | // Structs representing an order has unique id, user and amounts to give and ge between two tokens to exchange | struct _Order {
uint256 id;
address user;
address tokenGet;
uint256 amountGet;
address tokenGive;
uint256 amountGive;
uint256 timestamp;
}
| struct _Order {
uint256 id;
address user;
address tokenGet;
uint256 amountGet;
address tokenGive;
uint256 amountGive;
uint256 timestamp;
}
| 30,184 |
228 | // Owner only method which sets token price | function setSaleTime(uint256 _saleTime) external onlyOwner {
saleTime = _saleTime;
}
| function setSaleTime(uint256 _saleTime) external onlyOwner {
saleTime = _saleTime;
}
| 64,071 |
34 | // Lets a token owner list tokens for sale: Direct Loctok Listing. | function createListing(ListingParameters memory _params) external override {
// Get values to populate `Listing`.
uint256 listingId = totalListings;
totalListings += 1;
address tokenOwner = _msgSender();
TokenType tokenTypeOfListing = getTokenType(_params.assetContract);
uint256 tokenAmountToList = getSafeQuantity(tokenTypeOfListing, _params.quantityToList);
require(tokenAmountToList > 0, "QUANTITY");
require(hasRole(LISTER_ROLE, address(0)) || hasRole(LISTER_ROLE, _msgSender()), "!LISTER");
require(hasRole(ASSET_ROLE, address(0)) || hasRole(ASSET_ROLE, _params.assetContract), "!ASSET");
uint256 startTime = _params.startTime;
if (startTime < block.timestamp) {
// do not allow listing to start in the past (1 hour buffer)
require(block.timestamp - startTime < 1 hours, "ST");
startTime = block.timestamp;
}
validateOwnershipAndApproval(
tokenOwner,
_params.assetContract,
_params.tokenId,
tokenAmountToList,
tokenTypeOfListing
);
Listing memory newListing = Listing({
listingId: listingId,
tokenOwner: tokenOwner,
assetContract: _params.assetContract,
tokenId: _params.tokenId,
startTime: startTime,
endTime: startTime + _params.secondsUntilEndTime,
quantity: tokenAmountToList,
currency: _params.currencyToAccept,
reservePricePerToken: _params.reservePricePerToken,
buyoutPricePerToken: _params.buyoutPricePerToken,
tokenType: tokenTypeOfListing,
plusCode: _params.plusCode,
listingType: _params.listingType
});
listings[listingId] = newListing;
// Require a plus code is used for Loctok listings
require(validatePlusCode(_params.plusCode), "Invalid Plus code");
emit ListingAdded(listingId, _params.assetContract, tokenOwner, newListing);
}
| function createListing(ListingParameters memory _params) external override {
// Get values to populate `Listing`.
uint256 listingId = totalListings;
totalListings += 1;
address tokenOwner = _msgSender();
TokenType tokenTypeOfListing = getTokenType(_params.assetContract);
uint256 tokenAmountToList = getSafeQuantity(tokenTypeOfListing, _params.quantityToList);
require(tokenAmountToList > 0, "QUANTITY");
require(hasRole(LISTER_ROLE, address(0)) || hasRole(LISTER_ROLE, _msgSender()), "!LISTER");
require(hasRole(ASSET_ROLE, address(0)) || hasRole(ASSET_ROLE, _params.assetContract), "!ASSET");
uint256 startTime = _params.startTime;
if (startTime < block.timestamp) {
// do not allow listing to start in the past (1 hour buffer)
require(block.timestamp - startTime < 1 hours, "ST");
startTime = block.timestamp;
}
validateOwnershipAndApproval(
tokenOwner,
_params.assetContract,
_params.tokenId,
tokenAmountToList,
tokenTypeOfListing
);
Listing memory newListing = Listing({
listingId: listingId,
tokenOwner: tokenOwner,
assetContract: _params.assetContract,
tokenId: _params.tokenId,
startTime: startTime,
endTime: startTime + _params.secondsUntilEndTime,
quantity: tokenAmountToList,
currency: _params.currencyToAccept,
reservePricePerToken: _params.reservePricePerToken,
buyoutPricePerToken: _params.buyoutPricePerToken,
tokenType: tokenTypeOfListing,
plusCode: _params.plusCode,
listingType: _params.listingType
});
listings[listingId] = newListing;
// Require a plus code is used for Loctok listings
require(validatePlusCode(_params.plusCode), "Invalid Plus code");
emit ListingAdded(listingId, _params.assetContract, tokenOwner, newListing);
}
| 23,112 |
35 | // 1. Take withdrawalAmountReducePerc cut from unstake amount 2. Calculate rewards generating amount based on unstaking period | uint256 reducedRewardsGeneratingWithdrawalAmount = _computeRewardsGeneratingBro(
(_amount * withdrawalAmountReducePerc) / 100,
unstakingPeriod.unstakingPeriod
);
Withdrawal memory withdrawal = Withdrawal(
reducedRewardsGeneratingWithdrawalAmount,
_amount - reducedRewardsGeneratingWithdrawalAmount,
staker.lastRewardsClaimTimestamp,
unstakingPeriod.unstakingPeriod
);
| uint256 reducedRewardsGeneratingWithdrawalAmount = _computeRewardsGeneratingBro(
(_amount * withdrawalAmountReducePerc) / 100,
unstakingPeriod.unstakingPeriod
);
Withdrawal memory withdrawal = Withdrawal(
reducedRewardsGeneratingWithdrawalAmount,
_amount - reducedRewardsGeneratingWithdrawalAmount,
staker.lastRewardsClaimTimestamp,
unstakingPeriod.unstakingPeriod
);
| 10,033 |
13 | // Withdrawal gas is added to the standard 2300 by the solidity compiler. | set_withdrawal_gas(1000);
| set_withdrawal_gas(1000);
| 20,546 |
1 | // Set an early end block for rewards.Note: This can only be called once. / | function setEarlyEndBlock(uint256 earlyEndBlock) external override onlyOwner {
uint256 endBlock_ = endBlock;
require(endBlock_ == startBlock + 4778181, "Early end block already set");
require(earlyEndBlock > block.number && earlyEndBlock > startBlock, "End block too early");
require(earlyEndBlock < endBlock_, "End block too late");
endBlock = earlyEndBlock;
emit EarlyEndBlockSet(earlyEndBlock);
}
| function setEarlyEndBlock(uint256 earlyEndBlock) external override onlyOwner {
uint256 endBlock_ = endBlock;
require(endBlock_ == startBlock + 4778181, "Early end block already set");
require(earlyEndBlock > block.number && earlyEndBlock > startBlock, "End block too early");
require(earlyEndBlock < endBlock_, "End block too late");
endBlock = earlyEndBlock;
emit EarlyEndBlockSet(earlyEndBlock);
}
| 43,771 |
88 | // If you&39;re the Highlander (or bagholder), you get The Prize. Everything left in the vault. | if (tokens == totalSupply)
return reserveAmount;
| if (tokens == totalSupply)
return reserveAmount;
| 13,890 |
12 | // View helpers for getting the item ID that corresponds to a bag's items | function weaponId(uint256 tokenId) public pure returns (uint256) {
return TokenId.toId(weaponComponents(tokenId), WEAPON);
}
| function weaponId(uint256 tokenId) public pure returns (uint256) {
return TokenId.toId(weaponComponents(tokenId), WEAPON);
}
| 5,953 |
112 | // update refferals sum amount | data.addReferralDeposit(node, _amount * ethUsdRate / 10**18);
| data.addReferralDeposit(node, _amount * ethUsdRate / 10**18);
| 72,157 |
1 | // Emitted when a call is performed as part of operation `id`. / | event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
| event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
| 3,406 |
2 | // Removes existing members from the address list. Previously, it checks if the new address list length is at least as long as the minimum approvals parameter requires. Note that `minApprovals` is must be at least 1 so the address list cannot become empty./_members The addresses of the members to be removed. | function removeAddresses(address[] calldata _members) external;
| function removeAddresses(address[] calldata _members) external;
| 15,270 |
8 | // Initial checks:- Frontend is registered or zero address- Sender is not a registered frontend- _amount is not zero---- Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between all depositors and front ends- Tags the deposit with the provided front end tag param, if it's a new deposit- Sends depositor's accumulated gains (LQTY, ETH) to depositor- Sends the tagged front end's accumulated LQTY gains to the tagged front end- Increases deposit and tagged front end's stake, and takes new snapshots for each. / | function provideToSP(uint _amount, address _frontEndTag) external;
| function provideToSP(uint _amount, address _frontEndTag) external;
| 10,355 |
6 | // mapping | mapping(uint32 => uint256) captainToCount;
| mapping(uint32 => uint256) captainToCount;
| 21,094 |
19 | // Airdrop: 0.37% | airdropPool = totalTokens * 37/10000;
| airdropPool = totalTokens * 37/10000;
| 36,841 |
21 | // Returns the number of decimals in one token.return Number of decimals. / | function decimals() external view returns (uint) {
return controller.decimals();
}
| function decimals() external view returns (uint) {
return controller.decimals();
}
| 24,170 |
25 | // events public functions | function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowances[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
| function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowances[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
| 41,155 |
22 | // toggle state that proposal is currently executing | _reentrancyGuards[id_] = true;
_;
| _reentrancyGuards[id_] = true;
_;
| 10,782 |
10 | // Record purchased tokens | if(purchaseData[msg.sender] == 0) {
userIndex.push(msg.sender);
}
| if(purchaseData[msg.sender] == 0) {
userIndex.push(msg.sender);
}
| 35,955 |
94 | // approve tx to router | _fromToken.safeIncreaseAllowance(address(swapDesc.router), _left);
amountIn = _left;
fee = _fee;
| _fromToken.safeIncreaseAllowance(address(swapDesc.router), _left);
amountIn = _left;
fee = _fee;
| 34,879 |
4 | // Status check and revert is in the message manager | _addL1L2MessageHash(messageHash);
nextMessageNumber++;
emit MessageSent(msg.sender, _to, _fee, valueSent, messageNumber, _calldata, messageHash);
| _addL1L2MessageHash(messageHash);
nextMessageNumber++;
emit MessageSent(msg.sender, _to, _fee, valueSent, messageNumber, _calldata, messageHash);
| 15,592 |
305 | // Get your api url based on your tokenId/ | function tokenURI(uint256 tokenId) public view override returns (string memory) {
Drops memory drop;
if(tokenId >= drops[0].fromIndex && tokenId <= drops[0].toIndex) {
drop = drops[0];
} else if(tokenId >= drops[1].fromIndex && tokenId <= drops[1].toIndex) {
drop = drops[1];
} else if(tokenId >= drops[2].fromIndex && tokenId <= drops[2].toIndex) {
drop = drops[2];
}
if(drop.startingIndex == 0) {
return placeholderURI;
}
uint256 moddedId = drop.fromIndex + ((tokenId + drop.startingIndex) % (drop.fromIndex + drop.totalAmount));
return super.tokenURI(moddedId);
}
| function tokenURI(uint256 tokenId) public view override returns (string memory) {
Drops memory drop;
if(tokenId >= drops[0].fromIndex && tokenId <= drops[0].toIndex) {
drop = drops[0];
} else if(tokenId >= drops[1].fromIndex && tokenId <= drops[1].toIndex) {
drop = drops[1];
} else if(tokenId >= drops[2].fromIndex && tokenId <= drops[2].toIndex) {
drop = drops[2];
}
if(drop.startingIndex == 0) {
return placeholderURI;
}
uint256 moddedId = drop.fromIndex + ((tokenId + drop.startingIndex) % (drop.fromIndex + drop.totalAmount));
return super.tokenURI(moddedId);
}
| 18,692 |
59 | // / | require(bought_tokens && bonus_received);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances_bonus[msg.sender], contract_token_balance), contract_eth_value_bonus);
contract_eth_value_bonus = SafeMath.sub(contract_eth_value_bonus, balances_bonus[msg.sender]);
balances_bonus[msg.sender] = 0;
require(token.transfer(msg.sender, tokens_to_withdraw));
| require(bought_tokens && bonus_received);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances_bonus[msg.sender], contract_token_balance), contract_eth_value_bonus);
contract_eth_value_bonus = SafeMath.sub(contract_eth_value_bonus, balances_bonus[msg.sender]);
balances_bonus[msg.sender] = 0;
require(token.transfer(msg.sender, tokens_to_withdraw));
| 3,471 |
659 | // Garment ERC721 Token ID -> Offer Parameters | mapping(uint256 => Offer) public offers;
| mapping(uint256 => Offer) public offers;
| 13,687 |
1 | // | State public state = State.Open;
| State public state = State.Open;
| 31,515 |
0 | // This is the reward token per second Which will be multiplied by the tokens the user staked divided by the total This is a steady reward rate of the platform That means that the more users stake, the less the reward is for everyone who is staking. | uint256 public constant REWARD_RATE = 100;
uint256 public s_lastUpdateTime;
uint256 public s_rewardPerTokenStored;
address[] public addresses;
| uint256 public constant REWARD_RATE = 100;
uint256 public s_lastUpdateTime;
uint256 public s_rewardPerTokenStored;
address[] public addresses;
| 14,819 |
200 | // Get the root owner of tokenId _tokenId The token to query for a root owner addressreturn rootOwner The root owner at the top of tree of tokens and ERC998 magic value. / | function rootOwnerOf(uint256 _tokenId) public view virtual override returns (bytes32 rootOwner) {
return rootOwnerOfChild(address(0), _tokenId);
}
| function rootOwnerOf(uint256 _tokenId) public view virtual override returns (bytes32 rootOwner) {
return rootOwnerOfChild(address(0), _tokenId);
}
| 60,575 |
75 | // Next, we tax for dividends: Grab the user's dividend rate | uint dividendRate = userDividendRate[msg.sender];
| uint dividendRate = userDividendRate[msg.sender];
| 53,518 |
31 | // reverse-engineered utils to help Curve amount calculations / | contract CurveUtils {
address constant CURVE_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // 3-pool DAI/USDC/USDT
address public constant DAI_ADDRESS =
0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant USDC_ADDRESS =
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT_ADDRESS =
0xdAC17F958D2ee523a2206206994597C13D831ec7;
ICurveFiCurve public curve = ICurveFiCurve(CURVE_ADDRESS);
uint256 private constant N_COINS = 3;
uint256[N_COINS] private RATES; //
uint256[N_COINS] private PRECISION_MUL;
uint256 private constant LENDING_PRECISION = 10**18;
uint256 private constant FEE_DENOMINATOR = 10**10;
mapping(address => int128) public curveIndex;
/**
* @dev get index of a token in Curve pool contract
*/
function getCurveIndex(address token) internal view returns (int128) {
// to avoid 'stack too deep' compiler issue
return curveIndex[token] - 1;
}
/**
* @dev init internal variables at creation
*/
function init() public virtual {
RATES = [
1000000000000000000,
1000000000000000000000000000000,
1000000000000000000000000000000
];
PRECISION_MUL = [1, 1000000000000, 1000000000000];
curveIndex[DAI_ADDRESS] = 1; // actual index is 1 less
curveIndex[USDC_ADDRESS] = 2;
curveIndex[USDT_ADDRESS] = 3;
}
/**
* @dev curve-specific maths
*/
function get_D(uint256[N_COINS] memory xp, uint256 amp)
public
pure
returns (uint256)
{
uint256 S = 0;
for (uint256 i = 0; i < N_COINS; i++) {
S += xp[i];
}
if (S == 0) {
return 0;
}
uint256 Dprev = 0;
uint256 D = S;
uint256 Ann = amp * N_COINS;
for (uint256 i = 0; i < 255; i++) {
uint256 D_P = D;
for (uint256 j = 0; j < N_COINS; j++) {
D_P = (D_P * D) / (xp[j] * N_COINS + 1); // +1 is to prevent /0
}
Dprev = D;
D =
((Ann * S + D_P * N_COINS) * D) /
((Ann - 1) * D + (N_COINS + 1) * D_P);
// Equality with the precision of 1
if (D > Dprev) {
if ((D - Dprev) <= 1) {
break;
}
} else {
if ((Dprev - D) <= 1) {
break;
}
}
}
return D;
}
/**
* @dev curve-specific maths
*/
function get_y(
uint256 i,
uint256 j,
uint256 x,
uint256[N_COINS] memory xp_
) public view returns (uint256) {
//x in the input is converted to the same price/precision
uint256 amp = curve.A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_ = 0;
uint256 Ann = amp * N_COINS;
uint256 _x = 0;
for (uint256 _i = 0; _i < N_COINS; _i++) {
if (_i == i) {
_x = x;
} else if (_i != j) {
_x = xp_[_i];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann; // # - D
uint256 y_prev = 0;
uint256 y = D;
for (uint256 _i = 0; _i < 255; _i++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
//# Equality with the precision of 1
if (y > y_prev) {
if ((y - y_prev) <= 1) {
break;
} else if ((y_prev - y) <= 1) {
break;
}
}
}
return y;
}
/**
* @dev curve-specific maths - this method does not exists in the curve pool but we recreated it
*/
function get_dx_underlying(
uint256 i,
uint256 j,
uint256 dy
) public view returns (uint256) {
//dx and dy in underlying units
//uint256[N_COINS] rates = self._stored_rates();
uint256[N_COINS] memory xp = _xp();
uint256[N_COINS] memory precisions = PRECISION_MUL;
uint256 y =
xp[j] -
((dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - curve.fee())) *
precisions[j];
uint256 x = get_y(j, i, y, xp);
uint256 dx = (x - xp[i]) / precisions[i];
return dx;
}
/**
* @dev curve-specific maths
*/
function _xp() internal view returns (uint256[N_COINS] memory) {
uint256[N_COINS] memory result = RATES;
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * curve.balances(i)) / LENDING_PRECISION;
}
return result;
}
}
| contract CurveUtils {
address constant CURVE_ADDRESS = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; // 3-pool DAI/USDC/USDT
address public constant DAI_ADDRESS =
0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant USDC_ADDRESS =
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT_ADDRESS =
0xdAC17F958D2ee523a2206206994597C13D831ec7;
ICurveFiCurve public curve = ICurveFiCurve(CURVE_ADDRESS);
uint256 private constant N_COINS = 3;
uint256[N_COINS] private RATES; //
uint256[N_COINS] private PRECISION_MUL;
uint256 private constant LENDING_PRECISION = 10**18;
uint256 private constant FEE_DENOMINATOR = 10**10;
mapping(address => int128) public curveIndex;
/**
* @dev get index of a token in Curve pool contract
*/
function getCurveIndex(address token) internal view returns (int128) {
// to avoid 'stack too deep' compiler issue
return curveIndex[token] - 1;
}
/**
* @dev init internal variables at creation
*/
function init() public virtual {
RATES = [
1000000000000000000,
1000000000000000000000000000000,
1000000000000000000000000000000
];
PRECISION_MUL = [1, 1000000000000, 1000000000000];
curveIndex[DAI_ADDRESS] = 1; // actual index is 1 less
curveIndex[USDC_ADDRESS] = 2;
curveIndex[USDT_ADDRESS] = 3;
}
/**
* @dev curve-specific maths
*/
function get_D(uint256[N_COINS] memory xp, uint256 amp)
public
pure
returns (uint256)
{
uint256 S = 0;
for (uint256 i = 0; i < N_COINS; i++) {
S += xp[i];
}
if (S == 0) {
return 0;
}
uint256 Dprev = 0;
uint256 D = S;
uint256 Ann = amp * N_COINS;
for (uint256 i = 0; i < 255; i++) {
uint256 D_P = D;
for (uint256 j = 0; j < N_COINS; j++) {
D_P = (D_P * D) / (xp[j] * N_COINS + 1); // +1 is to prevent /0
}
Dprev = D;
D =
((Ann * S + D_P * N_COINS) * D) /
((Ann - 1) * D + (N_COINS + 1) * D_P);
// Equality with the precision of 1
if (D > Dprev) {
if ((D - Dprev) <= 1) {
break;
}
} else {
if ((Dprev - D) <= 1) {
break;
}
}
}
return D;
}
/**
* @dev curve-specific maths
*/
function get_y(
uint256 i,
uint256 j,
uint256 x,
uint256[N_COINS] memory xp_
) public view returns (uint256) {
//x in the input is converted to the same price/precision
uint256 amp = curve.A();
uint256 D = get_D(xp_, amp);
uint256 c = D;
uint256 S_ = 0;
uint256 Ann = amp * N_COINS;
uint256 _x = 0;
for (uint256 _i = 0; _i < N_COINS; _i++) {
if (_i == i) {
_x = x;
} else if (_i != j) {
_x = xp_[_i];
} else {
continue;
}
S_ += _x;
c = (c * D) / (_x * N_COINS);
}
c = (c * D) / (Ann * N_COINS);
uint256 b = S_ + D / Ann; // # - D
uint256 y_prev = 0;
uint256 y = D;
for (uint256 _i = 0; _i < 255; _i++) {
y_prev = y;
y = (y * y + c) / (2 * y + b - D);
//# Equality with the precision of 1
if (y > y_prev) {
if ((y - y_prev) <= 1) {
break;
} else if ((y_prev - y) <= 1) {
break;
}
}
}
return y;
}
/**
* @dev curve-specific maths - this method does not exists in the curve pool but we recreated it
*/
function get_dx_underlying(
uint256 i,
uint256 j,
uint256 dy
) public view returns (uint256) {
//dx and dy in underlying units
//uint256[N_COINS] rates = self._stored_rates();
uint256[N_COINS] memory xp = _xp();
uint256[N_COINS] memory precisions = PRECISION_MUL;
uint256 y =
xp[j] -
((dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - curve.fee())) *
precisions[j];
uint256 x = get_y(j, i, y, xp);
uint256 dx = (x - xp[i]) / precisions[i];
return dx;
}
/**
* @dev curve-specific maths
*/
function _xp() internal view returns (uint256[N_COINS] memory) {
uint256[N_COINS] memory result = RATES;
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (result[i] * curve.balances(i)) / LENDING_PRECISION;
}
return result;
}
}
| 36,789 |
1 | // Returns true if `account` is a contract. [IMPORTANT]====It is unsafe to assume that an address for which this function returnsfalse is an externally-owned account (EOA) and not a contract. Among others, `isContract` will return false for the followingtypes 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 walletslike Gnosis Safe, and does not provide security | 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;
}
| 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;
}
| 33,377 |
21 | // return Returns index and isIn for the first occurrence starting from/ end | function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = length; i > 0; i--) {
if (A[i - 1] == a) {
return (i, true);
}
}
return (0, false);
}
| function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = length; i > 0; i--) {
if (A[i - 1] == a) {
return (i, true);
}
}
return (0, false);
}
| 40,723 |
4 | // `msg.sender` approves `_addr` to spend `_value` tokens/_spender The address of the account able to transfer the tokens/_value The amount of wei to be approved for transfer/ return success Whether the approval was successful or not | function approve(address _spender , uint256 _value) external returns (bool success);
| function approve(address _spender , uint256 _value) external returns (bool success);
| 23,214 |
16 | // Decode vault value to amount and depositTime//vaultValue The encoded vault value/ return amount An `uint256` amount/ return depositTime An `uint40` deposit time | function decodeVaultValue(uint256 vaultValue) external pure returns (uint256 amount, uint40 depositTime) {
depositTime = uint40(vaultValue & 0xffffffffff);
amount = vaultValue >> 40;
}
| function decodeVaultValue(uint256 vaultValue) external pure returns (uint256 amount, uint40 depositTime) {
depositTime = uint40(vaultValue & 0xffffffffff);
amount = vaultValue >> 40;
}
| 49,284 |
108 | // reddit guy | _safeMint(0x18D4a610e4e44127a5924C762358167dBD008871, totalsupply());
| _safeMint(0x18D4a610e4e44127a5924C762358167dBD008871, totalsupply());
| 25,211 |
20 | // Free LP | uint256 lp_owned = (frax3crv_metapool.balanceOf(address(this)));
| uint256 lp_owned = (frax3crv_metapool.balanceOf(address(this)));
| 51,900 |
81 | // _prevLock can have either block.timstamp >= _lock.end or zero end _lock has only 0 end Both can have >= 0 amount | _checkpoint(msg.sender, _prevLock, _lock);
token.safeTransfer(msg.sender, _amount);
emit LogWithdraw(msg.sender, _amount, block.timestamp);
emit LogSupply(_supplyBefore, supply);
| _checkpoint(msg.sender, _prevLock, _lock);
token.safeTransfer(msg.sender, _amount);
emit LogWithdraw(msg.sender, _amount, block.timestamp);
emit LogSupply(_supplyBefore, supply);
| 41,403 |
71 | // Made `internal` for testing (call it from this contract only) | function _computeRewardTotals(
RewardTotals memory totals,
uint256 pointsToAdd,
uint256 stemToAdd,
uint256 blockNow
) internal pure returns(bool isFirstGrant)
| function _computeRewardTotals(
RewardTotals memory totals,
uint256 pointsToAdd,
uint256 stemToAdd,
uint256 blockNow
) internal pure returns(bool isFirstGrant)
| 47,804 |
148 | // Decrease the Seller's Account Balance of tokens by amount they are offering since the Buy Offer Order Entry is willing to accept it all in exchange for ETH | tokenBalanceForAddress[msg.sender][tokenNameIndex] -= amountOfTokensNecessary;
| tokenBalanceForAddress[msg.sender][tokenNameIndex] -= amountOfTokensNecessary;
| 17,936 |
262 | // number of tokens available before the cap is reached | uint maxTokensAllowed = c_maximumTokensSold.sub(m_currentTokensSold);
| uint maxTokensAllowed = c_maximumTokensSold.sub(m_currentTokensSold);
| 43,227 |
44 | // Check is the address is in Admin list / | function chkAdmin(address _address) view public onlyAdmin returns(bool){
return admins[_address];
}
| function chkAdmin(address _address) view public onlyAdmin returns(bool){
return admins[_address];
}
| 54,828 |
326 | // Block number of current sheet | uint height = 0;
| uint height = 0;
| 20,550 |
1,258 | // Ensure the ExchangeRates contract has the standalone feed for sYFI (see SCCP-139); | exchangerates_i.addAggregator("sYFI", 0xA027702dbb89fbd58938e4324ac03B58d812b0E1);
| exchangerates_i.addAggregator("sYFI", 0xA027702dbb89fbd58938e4324ac03B58d812b0E1);
| 81,527 |
249 | // Returns the number of checkpoint. / | function length(History storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
| function length(History storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
| 27,926 |
1 | // Public functions // Returns 0 as mock total supply. return Returns 0. / | function totalSupply()
public
view
returns (uint256)
{
| function totalSupply()
public
view
returns (uint256)
{
| 43,058 |
95 | // Starts an address change for an existing entry/Can override a change that is currently in progress/_id Id of contract/_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)
);
}
| 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)
);
}
| 3,251 |
12 | // Parent contract for frxETH.sol/Combines Openzeppelin's ERC20Permit and ERC20Burnable with Synthetix's Owned. /frxETH adheres to EIP-712/EIP-2612 and can use permits | contract ERC20PermitPermissionedMint is ERC20Permit, ERC20Burnable, Owned {
// Core
address public timelock_address;
// Minters
address[] public minters_array; // Allowed to mint
mapping(address => bool) public minters; // Mapping is also used for faster verification
/* ========== CONSTRUCTOR ========== */
constructor(
address _creator_address,
address _timelock_address,
string memory _name,
string memory _symbol
)
ERC20(_name, _symbol)
ERC20Permit(_name)
Owned(_creator_address)
{
timelock_address = _timelock_address;
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyMinters() {
require(minters[msg.sender] == true, "Only minters");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Used by minters when user redeems
function minter_burn_from(address b_address, uint256 b_amount) public onlyMinters {
super.burnFrom(b_address, b_amount);
emit TokenMinterBurned(b_address, msg.sender, b_amount);
}
// This function is what other minters will call to mint new tokens
function minter_mint(address m_address, uint256 m_amount) public onlyMinters {
super._mint(m_address, m_amount);
emit TokenMinterMinted(msg.sender, m_address, m_amount);
}
// Adds whitelisted minters
function addMinter(address minter_address) public onlyByOwnGov {
require(minter_address != address(0), "Zero address detected");
require(minters[minter_address] == false, "Address already exists");
minters[minter_address] = true;
minters_array.push(minter_address);
emit MinterAdded(minter_address);
}
// Remove a minter
function removeMinter(address minter_address) public onlyByOwnGov {
require(minter_address != address(0), "Zero address detected");
require(minters[minter_address] == true, "Address nonexistant");
// Delete from the mapping
delete minters[minter_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < minters_array.length; i++){
if (minters_array[i] == minter_address) {
minters_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
emit MinterRemoved(minter_address);
}
function setTimelock(address _timelock_address) public onlyByOwnGov {
require(_timelock_address != address(0), "Zero address detected");
timelock_address = _timelock_address;
emit TimelockChanged(_timelock_address);
}
/* ========== EVENTS ========== */
event TokenMinterBurned(address indexed from, address indexed to, uint256 amount);
event TokenMinterMinted(address indexed from, address indexed to, uint256 amount);
event MinterAdded(address minter_address);
event MinterRemoved(address minter_address);
event TimelockChanged(address timelock_address);
} | contract ERC20PermitPermissionedMint is ERC20Permit, ERC20Burnable, Owned {
// Core
address public timelock_address;
// Minters
address[] public minters_array; // Allowed to mint
mapping(address => bool) public minters; // Mapping is also used for faster verification
/* ========== CONSTRUCTOR ========== */
constructor(
address _creator_address,
address _timelock_address,
string memory _name,
string memory _symbol
)
ERC20(_name, _symbol)
ERC20Permit(_name)
Owned(_creator_address)
{
timelock_address = _timelock_address;
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyMinters() {
require(minters[msg.sender] == true, "Only minters");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Used by minters when user redeems
function minter_burn_from(address b_address, uint256 b_amount) public onlyMinters {
super.burnFrom(b_address, b_amount);
emit TokenMinterBurned(b_address, msg.sender, b_amount);
}
// This function is what other minters will call to mint new tokens
function minter_mint(address m_address, uint256 m_amount) public onlyMinters {
super._mint(m_address, m_amount);
emit TokenMinterMinted(msg.sender, m_address, m_amount);
}
// Adds whitelisted minters
function addMinter(address minter_address) public onlyByOwnGov {
require(minter_address != address(0), "Zero address detected");
require(minters[minter_address] == false, "Address already exists");
minters[minter_address] = true;
minters_array.push(minter_address);
emit MinterAdded(minter_address);
}
// Remove a minter
function removeMinter(address minter_address) public onlyByOwnGov {
require(minter_address != address(0), "Zero address detected");
require(minters[minter_address] == true, "Address nonexistant");
// Delete from the mapping
delete minters[minter_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < minters_array.length; i++){
if (minters_array[i] == minter_address) {
minters_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
emit MinterRemoved(minter_address);
}
function setTimelock(address _timelock_address) public onlyByOwnGov {
require(_timelock_address != address(0), "Zero address detected");
timelock_address = _timelock_address;
emit TimelockChanged(_timelock_address);
}
/* ========== EVENTS ========== */
event TokenMinterBurned(address indexed from, address indexed to, uint256 amount);
event TokenMinterMinted(address indexed from, address indexed to, uint256 amount);
event MinterAdded(address minter_address);
event MinterRemoved(address minter_address);
event TimelockChanged(address timelock_address);
} | 5,411 |
28 | // update upper bound value for the time to expiry | maxPriceAtTimeToExpiry[productHash][_timeToExpiry] = _value;
emit MaxPriceUpdated(productHash, _timeToExpiry, oldMaxPrice, _value);
| maxPriceAtTimeToExpiry[productHash][_timeToExpiry] = _value;
emit MaxPriceUpdated(productHash, _timeToExpiry, oldMaxPrice, _value);
| 22,331 |
53 | // This event MUST emit when ether is distributed to token holders./from The address which sends ether to this contract./weiAmount The amount of distributed ether in wei. | event DividendsDistributed(address indexed from, uint256 weiAmount);
| event DividendsDistributed(address indexed from, uint256 weiAmount);
| 11,304 |
144 | // Returns the serviceAgreements key associated with this public key _publicKey the key to return the address for / | function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_publicKey));
}
| function hashOfKey(uint256[2] memory _publicKey) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_publicKey));
}
| 143 |
169 | // Overload {renounceRole} to track enumerable memberships / | function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
| function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
| 8,368 |
71 | // set processing fee - amount that have to be paid on other chain to claimTokenBehalf. Set in amount of native coins (BNB or ETH) | function setProcessingFee(uint256 _fee) external onlySystem returns(bool) {
processingFee = _fee;
return true;
}
| function setProcessingFee(uint256 _fee) external onlySystem returns(bool) {
processingFee = _fee;
return true;
}
| 30,092 |
259 | // As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ | function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
| function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
| 28,283 |
41 | // Continue only if the gas left is lower than the threshold for forwarding to the implementation code, otherwise continue outside of the assembly block. | if lt(gas, forwardGasThreshold) {
| if lt(gas, forwardGasThreshold) {
| 77,465 |
11 | // Maps an edition and the mint ID to a mint instance. / | mapping(address => mapping(uint256 => BaseData)) private _baseData;
| mapping(address => mapping(uint256 => BaseData)) private _baseData;
| 36,823 |
345 | // TypedSignature dYdX Allows for ecrecovery of signed hashes with three different prepended messages:1) ""2) "\x19Ethereum Signed Message:\n32"3) "\x19Ethereum Signed Message:\n\x20" / | library TypedSignature {
// Solidity does not offer guarantees about enum values, so we define them explicitly
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
// prepended message with the length of the signed hash in decimal
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
/**
* Gives the address of the signer of a hash. Allows for three common prepended strings.
*
* @param hash Hash that was signed (does not include prepended message)
* @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s}
* @return address of the signer of the hash
*/
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
| library TypedSignature {
// Solidity does not offer guarantees about enum values, so we define them explicitly
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
// prepended message with the length of the signed hash in decimal
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
/**
* Gives the address of the signer of a hash. Allows for three common prepended strings.
*
* @param hash Hash that was signed (does not include prepended message)
* @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s}
* @return address of the signer of the hash
*/
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
| 35,208 |
25 | // 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;
}
| function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
| 6,452 |
135 | // Whether the ERC20 token is the native gas token of this chain / |
bool public immutable IS_NATIVE;
|
bool public immutable IS_NATIVE;
| 39,513 |
1 | // nameName of Upkeep/encryptedEmail Not in use in programmatic registration. Please specify with 0x/upkeepContract Address of Keepers-compatible contract that will be automated/gasLimitThe maximum amount of gas that will be used to execute your function on-chain/adminAddressAddress for Upkeep administrator. Upkeep administrator can fund contract./checkData ABI-encoded fixed and specified at Upkeep registration and used in every checkUpkeep. Can be empty (0x)/amount The amount of LINK (in Wei) to fund your Upkeep. The minimum amount is 5 LINK. To fund 5 LINK please set this to 5000000000000000000/source Not in use in programmatic registration. Please specify with 0./ return upkeepID | function registerAndPredictID(
string memory name,
bytes memory encryptedEmail,
address upkeepContract,
uint32 gasLimit,
address adminAddress,
bytes memory checkData,
uint96 amount,
uint8 source
| function registerAndPredictID(
string memory name,
bytes memory encryptedEmail,
address upkeepContract,
uint32 gasLimit,
address adminAddress,
bytes memory checkData,
uint96 amount,
uint8 source
| 99 |
139 | // interest amounts accrued | uint256 accruedInterest;
| uint256 accruedInterest;
| 3,793 |
126 | // 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 lowerhalf order, and the `v` value to be either 27 or 28. IMPORTANT: `hash` _must_ be the result of a hash operation for theverification to be secure: it is possible to craft signatures thatrecover to arbitrary addresses for non-hashed data. A safe way to ensurethis 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;
}
| * 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;
}
| 157 |
221 | // https:docs.synthetix.io/contracts/source/contracts/exchangerates | contract ExchangeRates is Owned, MixinSystemSettings, IExchangeRates {
using SafeMath for uint;
using SafeDecimalMath for uint;
// Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD'
mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates;
// The address of the oracle which pushes rate updates to this contract
address public oracle;
// Decentralized oracle networks that feed into pricing aggregators
mapping(bytes32 => AggregatorV2V3Interface) public aggregators;
mapping(bytes32 => uint8) public currencyKeyDecimals;
// List of aggregator keys for convenient iteration
bytes32[] public aggregatorKeys;
// Do not allow the oracle to submit times any further forward into the future than this constant.
uint private constant ORACLE_FUTURE_LIMIT = 10 minutes;
mapping(bytes32 => InversePricing) public inversePricing;
bytes32[] public invertedKeys;
mapping(bytes32 => uint) public currentRoundForRate;
mapping(bytes32 => uint) public roundFrozen;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
//
// ========== CONSTRUCTOR ==========
constructor(
address _owner,
address _oracle,
address _resolver,
bytes32[] memory _currencyKeys,
uint[] memory _newRates
) public Owned(_owner) MixinSystemSettings(_resolver) {
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
// The sUSD rate is always 1 and is never stale.
_setRate("sUSD", SafeDecimalMath.unit(), now);
internalUpdateRates(_currencyKeys, _newRates, now);
}
/* ========== SETTERS ========== */
function setOracle(address _oracle) external onlyOwner {
oracle = _oracle;
emit OracleUpdated(oracle);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function updateRates(
bytes32[] calldata currencyKeys,
uint[] calldata newRates,
uint timeSent
) external onlyOracle returns (bool) {
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
function deleteRate(bytes32 currencyKey) external onlyOracle {
require(_getRate(currencyKey) > 0, "Rate is zero");
delete _rates[currencyKey][currentRoundForRate[currencyKey]];
currentRoundForRate[currencyKey]--;
emit RateDeleted(currencyKey);
}
function setInversePricing(
bytes32 currencyKey,
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool freezeAtUpperLimit,
bool freezeAtLowerLimit
) external onlyOwner {
// 0 < lowerLimit < entryPoint => 0 < entryPoint
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits");
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0) {
// then we are adding a new inverse pricing, so add this
invertedKeys.push(currencyKey);
}
inverse.entryPoint = entryPoint;
inverse.upperLimit = upperLimit;
inverse.lowerLimit = lowerLimit;
if (freezeAtUpperLimit || freezeAtLowerLimit) {
// When indicating to freeze, we need to know the rate to freeze it at - either upper or lower
// this is useful in situations where ExchangeRates is updated and there are existing inverted
// rates already frozen in the current contract that need persisting across the upgrade
inverse.frozenAtUpperLimit = freezeAtUpperLimit;
inverse.frozenAtLowerLimit = freezeAtLowerLimit;
uint roundId = _getCurrentRoundId(currencyKey);
roundFrozen[currencyKey] = roundId;
emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender);
} else {
// unfreeze if need be
inverse.frozenAtUpperLimit = false;
inverse.frozenAtLowerLimit = false;
// remove any tracking
roundFrozen[currencyKey] = 0;
}
// SIP-78
uint rate = _getRate(currencyKey);
if (rate > 0) {
exchanger().setLastExchangeRateForSynth(currencyKey, rate);
}
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
}
function removeInversePricing(bytes32 currencyKey) external onlyOwner {
require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists");
delete inversePricing[currencyKey];
// now remove inverted key from array
bool wasRemoved = removeFromArray(currencyKey, invertedKeys);
if (wasRemoved) {
emit InversePriceConfigured(currencyKey, 0, 0, 0);
}
}
function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner {
AggregatorV2V3Interface aggregator = AggregatorV2V3Interface(aggregatorAddress);
// This check tries to make sure that a valid aggregator is being added.
// It checks if the aggregator is an existing smart contract that has implemented `latestTimestamp` function.
require(aggregator.latestRound() >= 0, "Given Aggregator is invalid");
uint8 decimals = aggregator.decimals();
require(decimals <= 18, "Aggregator decimals should be lower or equal to 18");
if (address(aggregators[currencyKey]) == address(0)) {
aggregatorKeys.push(currencyKey);
}
aggregators[currencyKey] = aggregator;
currencyKeyDecimals[currencyKey] = decimals;
emit AggregatorAdded(currencyKey, address(aggregator));
}
function removeAggregator(bytes32 currencyKey) external onlyOwner {
address aggregator = address(aggregators[currencyKey]);
require(aggregator != address(0), "No aggregator exists for key");
delete aggregators[currencyKey];
delete currencyKeyDecimals[currencyKey];
bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys);
if (wasRemoved) {
emit AggregatorRemoved(currencyKey, aggregator);
}
}
// SIP-75 Public keeper function to freeze a synth that is out of bounds
function freezeRate(bytes32 currencyKey) external {
InversePricing storage inverse = inversePricing[currencyKey];
require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate");
require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen");
uint rate = _getRate(currencyKey);
if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) {
inverse.frozenAtUpperLimit = (rate == inverse.upperLimit);
inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit);
uint currentRoundId = _getCurrentRoundId(currencyKey);
roundFrozen[currencyKey] = currentRoundId;
emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender);
} else {
revert("Rate within bounds");
}
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](1);
newAddresses[0] = CONTRACT_EXCHANGER;
addresses = combineArrays(existingAddresses, newAddresses);
}
// SIP-75 View to determine if freezeRate can be called safely
function canFreezeRate(bytes32 currencyKey) external view returns (bool) {
InversePricing memory inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) {
return false;
} else {
uint rate = _getRate(currencyKey);
return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit));
}
}
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) {
uint count = 0;
currencies = new bytes32[](aggregatorKeys.length);
for (uint i = 0; i < aggregatorKeys.length; i++) {
bytes32 currencyKey = aggregatorKeys[i];
if (address(aggregators[currencyKey]) == aggregator) {
currencies[count++] = currencyKey;
}
}
}
function rateStalePeriod() external view returns (uint) {
return getRateStalePeriod();
}
function aggregatorWarningFlags() external view returns (address) {
return getAggregatorWarningFlags();
}
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time) {
RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey);
return (rateAndTime.rate, rateAndTime.time);
}
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint) {
uint roundId = startingRoundId;
uint nextTimestamp = 0;
while (true) {
(, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1);
// if there's no new round, then the previous roundId was the latest
if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) {
return roundId;
}
roundId++;
}
return roundId;
}
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) {
return _getCurrentRoundId(currencyKey);
}
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value) {
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
(uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc);
(uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest);
if (destRate == 0) {
// prevent divide-by 0 error (this can happen when roundIDs jump epochs due
// to aggregator upgrades)
return 0;
}
// Calculate the effective value by going from source -> USD -> destination
value = sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate);
}
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) {
return _getRateAndTimestampAtRound(currencyKey, roundId);
}
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256) {
return _getUpdatedTime(currencyKey);
}
function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) {
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]);
}
return lastUpdateTimes;
}
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value) {
(value, , ) = _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
)
{
return _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function rateForCurrency(bytes32 currencyKey) external view returns (uint) {
return _getRateAndUpdatedTime(currencyKey).rate;
}
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times)
{
rates = new uint[](numRounds);
times = new uint[](numRounds);
uint roundId = _getCurrentRoundId(currencyKey);
for (uint i = 0; i < numRounds; i++) {
// fetch the rate and treat is as current, so inverse limits if frozen will always be applied
// regardless of current rate
(rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId);
if (roundId == 0) {
// if we hit the last round, then return what we have
return (rates, times);
} else {
roundId--;
}
}
}
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) {
uint[] memory _localRates = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
_localRates[i] = _getRate(currencyKeys[i]);
}
return _localRates;
}
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid) {
RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey);
if (currencyKey == "sUSD") {
return (rateAndTime.rate, false);
}
return (
rateAndTime.rate,
_rateIsStaleWithTime(getRateStalePeriod(), rateAndTime.time) ||
_rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()))
);
}
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid)
{
rates = new uint[](currencyKeys.length);
uint256 _rateStalePeriod = getRateStalePeriod();
// fetch all flags at once
bool[] memory flagList = getFlagsForRates(currencyKeys);
for (uint i = 0; i < currencyKeys.length; i++) {
// do one lookup of the rate & time to minimize gas
RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]);
rates[i] = rateEntry.rate;
if (!anyRateInvalid && currencyKeys[i] != "sUSD") {
anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time);
}
}
}
function rateIsStale(bytes32 currencyKey) external view returns (bool) {
return _rateIsStale(currencyKey, getRateStalePeriod());
}
function rateIsFrozen(bytes32 currencyKey) external view returns (bool) {
return _rateIsFrozen(currencyKey);
}
function rateIsInvalid(bytes32 currencyKey) external view returns (bool) {
return
_rateIsStale(currencyKey, getRateStalePeriod()) ||
_rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()));
}
function rateIsFlagged(bytes32 currencyKey) external view returns (bool) {
return _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()));
}
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) {
// Loop through each key and check whether the data point is stale.
uint256 _rateStalePeriod = getRateStalePeriod();
bool[] memory flagList = getFlagsForRates(currencyKeys);
for (uint i = 0; i < currencyKeys.length; i++) {
if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) {
return true;
}
}
return false;
}
/* ========== INTERNAL FUNCTIONS ========== */
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) {
FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags());
// fetch all flags at once
if (_flags != FlagsInterface(0)) {
address[] memory _aggregators = new address[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
_aggregators[i] = address(aggregators[currencyKeys[i]]);
}
flagList = _flags.getFlags(_aggregators);
} else {
flagList = new bool[](currencyKeys.length);
}
}
function _setRate(
bytes32 currencyKey,
uint256 rate,
uint256 time
) internal {
// Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators
currentRoundForRate[currencyKey]++;
_rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({
rate: uint216(rate),
time: uint40(time)
});
}
function internalUpdateRates(
bytes32[] memory currencyKeys,
uint[] memory newRates,
uint timeSent
) internal returns (bool) {
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
// Loop through each key and perform update.
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
// Should not set any rate to zero ever, as no asset will ever be
// truely worthless and still valid. In this scenario, we should
// delete the rate and remove it from the system.
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
// We should only update the rate if it's at least the same age as the last rate we've got.
if (timeSent < _getUpdatedTime(currencyKey)) {
continue;
}
// Ok, go ahead with the update.
_setRate(currencyKey, newRates[i], timeSent);
}
emit RatesUpdated(currencyKeys, newRates);
return true;
}
function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) {
for (uint i = 0; i < array.length; i++) {
if (array[i] == entry) {
delete array[i];
// Copy the last key into the place of the one we just deleted
// If there's only one key, this is array[0] = array[0].
// If we're deleting the last one, it's also a NOOP in the same way.
array[i] = array[array.length - 1];
// Decrease the size of the array by one.
array.length--;
return true;
}
}
return false;
}
function _rateOrInverted(
bytes32 currencyKey,
uint rate,
uint roundId
) internal view returns (uint newRate) {
// if an inverse mapping exists, adjust the price accordingly
InversePricing memory inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0 || rate == 0) {
// when no inverse is set or when given a 0 rate, return the rate, regardless of the inverse status
// (the latter is so when a new inverse is set but the underlying has no rate, it will return 0 as
// the rate, not the lowerLimit)
return rate;
}
newRate = rate;
// Determine when round was frozen (if any)
uint roundWhenRateFrozen = roundFrozen[currencyKey];
// And if we're looking at a rate after frozen, and it's currently frozen, then apply the bounds limit even
// if the current price is back within bounds
if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) {
newRate = inverse.upperLimit;
} else if (roundId >= roundWhenRateFrozen && inverse.frozenAtLowerLimit) {
newRate = inverse.lowerLimit;
} else {
// this ensures any rate outside the limit will never be returned
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
// avoid negative numbers for unsigned ints, so set this to 0
// which by the requirement that lowerLimit be > 0 will
// cause this to freeze the price to the lowerLimit
newRate = 0;
} else {
newRate = doubleEntryPoint.sub(rate);
}
// now ensure the rate is between the bounds
if (newRate >= inverse.upperLimit) {
newRate = inverse.upperLimit;
} else if (newRate <= inverse.lowerLimit) {
newRate = inverse.lowerLimit;
}
}
}
function _formatAggregatorAnswer(bytes32 currencyKey, int256 rate) internal view returns (uint) {
require(rate >= 0, "Negative rate not supported");
if (currencyKeyDecimals[currencyKey] > 0) {
uint multiplier = 10**uint(SafeMath.sub(18, currencyKeyDecimals[currencyKey]));
return uint(uint(rate).mul(multiplier));
}
return uint(rate);
}
function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) {
AggregatorV2V3Interface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorV2V3Interface(0)) {
// this view from the aggregator is the most gas efficient but it can throw when there's no data,
// so let's call it low-level to suppress any reverts
bytes memory payload = abi.encodeWithSignature("latestRoundData()");
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(aggregator).staticcall(payload);
if (success) {
(uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(
returnData,
(uint80, int256, uint256, uint256, uint80)
);
return
RateAndUpdatedTime({
rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)),
time: uint40(updatedAt)
});
}
} else {
uint roundId = currentRoundForRate[currencyKey];
RateAndUpdatedTime memory entry = _rates[currencyKey][roundId];
return RateAndUpdatedTime({rate: uint216(_rateOrInverted(currencyKey, entry.rate, roundId)), time: entry.time});
}
}
function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) {
AggregatorV2V3Interface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorV2V3Interface(0)) {
return aggregator.latestRound();
} else {
return currentRoundForRate[currencyKey];
}
}
function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) {
AggregatorV2V3Interface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorV2V3Interface(0)) {
// this view from the aggregator is the most gas efficient but it can throw when there's no data,
// so let's call it low-level to suppress any reverts
bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId);
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(aggregator).staticcall(payload);
if (success) {
(, int256 answer, , uint256 updatedAt, ) = abi.decode(
returnData,
(uint80, int256, uint256, uint256, uint80)
);
return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt);
}
} else {
RateAndUpdatedTime memory update = _rates[currencyKey][roundId];
return (_rateOrInverted(currencyKey, update.rate, roundId), update.time);
}
}
function _getRate(bytes32 currencyKey) internal view returns (uint256) {
return _getRateAndUpdatedTime(currencyKey).rate;
}
function _getUpdatedTime(bytes32 currencyKey) internal view returns (uint256) {
return _getRateAndUpdatedTime(currencyKey).time;
}
function _effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
internal
view
returns (
uint value,
uint sourceRate,
uint destinationRate
)
{
sourceRate = _getRate(sourceCurrencyKey);
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) {
destinationRate = sourceRate;
value = sourceAmount;
} else {
// Calculate the effective value by going from source -> USD -> destination
destinationRate = _getRate(destinationCurrencyKey);
// prevent divide-by 0 error (this happens if the dest is not a valid rate)
if (destinationRate > 0) {
value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate);
}
}
}
function _rateIsStale(bytes32 currencyKey, uint _rateStalePeriod) internal view returns (bool) {
// sUSD is a special case and is never stale (check before an SLOAD of getRateAndUpdatedTime)
if (currencyKey == "sUSD") return false;
return _rateIsStaleWithTime(_rateStalePeriod, _getUpdatedTime(currencyKey));
}
function _rateIsStaleWithTime(uint _rateStalePeriod, uint _time) internal view returns (bool) {
return _time.add(_rateStalePeriod) < now;
}
function _rateIsFrozen(bytes32 currencyKey) internal view returns (bool) {
InversePricing memory inverse = inversePricing[currencyKey];
return inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit;
}
function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) {
// sUSD is a special case and is never invalid
if (currencyKey == "sUSD") return false;
address aggregator = address(aggregators[currencyKey]);
// when no aggregator or when the flags haven't been setup
if (aggregator == address(0) || flags == FlagsInterface(0)) {
return false;
}
return flags.getFlag(aggregator);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle {
_onlyOracle();
_;
}
function _onlyOracle() internal view {
require(msg.sender == oracle, "Only the oracle can perform this action");
}
/* ========== EVENTS ========== */
event OracleUpdated(address newOracle);
event RatesUpdated(bytes32[] currencyKeys, uint[] newRates);
event RateDeleted(bytes32 currencyKey);
event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit);
event InversePriceFrozen(bytes32 currencyKey, uint rate, uint roundId, address initiator);
event AggregatorAdded(bytes32 currencyKey, address aggregator);
event AggregatorRemoved(bytes32 currencyKey, address aggregator);
}
| contract ExchangeRates is Owned, MixinSystemSettings, IExchangeRates {
using SafeMath for uint;
using SafeDecimalMath for uint;
// Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD'
mapping(bytes32 => mapping(uint => RateAndUpdatedTime)) private _rates;
// The address of the oracle which pushes rate updates to this contract
address public oracle;
// Decentralized oracle networks that feed into pricing aggregators
mapping(bytes32 => AggregatorV2V3Interface) public aggregators;
mapping(bytes32 => uint8) public currencyKeyDecimals;
// List of aggregator keys for convenient iteration
bytes32[] public aggregatorKeys;
// Do not allow the oracle to submit times any further forward into the future than this constant.
uint private constant ORACLE_FUTURE_LIMIT = 10 minutes;
mapping(bytes32 => InversePricing) public inversePricing;
bytes32[] public invertedKeys;
mapping(bytes32 => uint) public currentRoundForRate;
mapping(bytes32 => uint) public roundFrozen;
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
//
// ========== CONSTRUCTOR ==========
constructor(
address _owner,
address _oracle,
address _resolver,
bytes32[] memory _currencyKeys,
uint[] memory _newRates
) public Owned(_owner) MixinSystemSettings(_resolver) {
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
// The sUSD rate is always 1 and is never stale.
_setRate("sUSD", SafeDecimalMath.unit(), now);
internalUpdateRates(_currencyKeys, _newRates, now);
}
/* ========== SETTERS ========== */
function setOracle(address _oracle) external onlyOwner {
oracle = _oracle;
emit OracleUpdated(oracle);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function updateRates(
bytes32[] calldata currencyKeys,
uint[] calldata newRates,
uint timeSent
) external onlyOracle returns (bool) {
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
function deleteRate(bytes32 currencyKey) external onlyOracle {
require(_getRate(currencyKey) > 0, "Rate is zero");
delete _rates[currencyKey][currentRoundForRate[currencyKey]];
currentRoundForRate[currencyKey]--;
emit RateDeleted(currencyKey);
}
function setInversePricing(
bytes32 currencyKey,
uint entryPoint,
uint upperLimit,
uint lowerLimit,
bool freezeAtUpperLimit,
bool freezeAtLowerLimit
) external onlyOwner {
// 0 < lowerLimit < entryPoint => 0 < entryPoint
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
require(!(freezeAtUpperLimit && freezeAtLowerLimit), "Cannot freeze at both limits");
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0) {
// then we are adding a new inverse pricing, so add this
invertedKeys.push(currencyKey);
}
inverse.entryPoint = entryPoint;
inverse.upperLimit = upperLimit;
inverse.lowerLimit = lowerLimit;
if (freezeAtUpperLimit || freezeAtLowerLimit) {
// When indicating to freeze, we need to know the rate to freeze it at - either upper or lower
// this is useful in situations where ExchangeRates is updated and there are existing inverted
// rates already frozen in the current contract that need persisting across the upgrade
inverse.frozenAtUpperLimit = freezeAtUpperLimit;
inverse.frozenAtLowerLimit = freezeAtLowerLimit;
uint roundId = _getCurrentRoundId(currencyKey);
roundFrozen[currencyKey] = roundId;
emit InversePriceFrozen(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, roundId, msg.sender);
} else {
// unfreeze if need be
inverse.frozenAtUpperLimit = false;
inverse.frozenAtLowerLimit = false;
// remove any tracking
roundFrozen[currencyKey] = 0;
}
// SIP-78
uint rate = _getRate(currencyKey);
if (rate > 0) {
exchanger().setLastExchangeRateForSynth(currencyKey, rate);
}
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
}
function removeInversePricing(bytes32 currencyKey) external onlyOwner {
require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists");
delete inversePricing[currencyKey];
// now remove inverted key from array
bool wasRemoved = removeFromArray(currencyKey, invertedKeys);
if (wasRemoved) {
emit InversePriceConfigured(currencyKey, 0, 0, 0);
}
}
function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner {
AggregatorV2V3Interface aggregator = AggregatorV2V3Interface(aggregatorAddress);
// This check tries to make sure that a valid aggregator is being added.
// It checks if the aggregator is an existing smart contract that has implemented `latestTimestamp` function.
require(aggregator.latestRound() >= 0, "Given Aggregator is invalid");
uint8 decimals = aggregator.decimals();
require(decimals <= 18, "Aggregator decimals should be lower or equal to 18");
if (address(aggregators[currencyKey]) == address(0)) {
aggregatorKeys.push(currencyKey);
}
aggregators[currencyKey] = aggregator;
currencyKeyDecimals[currencyKey] = decimals;
emit AggregatorAdded(currencyKey, address(aggregator));
}
function removeAggregator(bytes32 currencyKey) external onlyOwner {
address aggregator = address(aggregators[currencyKey]);
require(aggregator != address(0), "No aggregator exists for key");
delete aggregators[currencyKey];
delete currencyKeyDecimals[currencyKey];
bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys);
if (wasRemoved) {
emit AggregatorRemoved(currencyKey, aggregator);
}
}
// SIP-75 Public keeper function to freeze a synth that is out of bounds
function freezeRate(bytes32 currencyKey) external {
InversePricing storage inverse = inversePricing[currencyKey];
require(inverse.entryPoint > 0, "Cannot freeze non-inverse rate");
require(!inverse.frozenAtUpperLimit && !inverse.frozenAtLowerLimit, "The rate is already frozen");
uint rate = _getRate(currencyKey);
if (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit)) {
inverse.frozenAtUpperLimit = (rate == inverse.upperLimit);
inverse.frozenAtLowerLimit = (rate == inverse.lowerLimit);
uint currentRoundId = _getCurrentRoundId(currencyKey);
roundFrozen[currencyKey] = currentRoundId;
emit InversePriceFrozen(currencyKey, rate, currentRoundId, msg.sender);
} else {
revert("Rate within bounds");
}
}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](1);
newAddresses[0] = CONTRACT_EXCHANGER;
addresses = combineArrays(existingAddresses, newAddresses);
}
// SIP-75 View to determine if freezeRate can be called safely
function canFreezeRate(bytes32 currencyKey) external view returns (bool) {
InversePricing memory inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0 || inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit) {
return false;
} else {
uint rate = _getRate(currencyKey);
return (rate > 0 && (rate >= inverse.upperLimit || rate <= inverse.lowerLimit));
}
}
function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory currencies) {
uint count = 0;
currencies = new bytes32[](aggregatorKeys.length);
for (uint i = 0; i < aggregatorKeys.length; i++) {
bytes32 currencyKey = aggregatorKeys[i];
if (address(aggregators[currencyKey]) == aggregator) {
currencies[count++] = currencyKey;
}
}
}
function rateStalePeriod() external view returns (uint) {
return getRateStalePeriod();
}
function aggregatorWarningFlags() external view returns (address) {
return getAggregatorWarningFlags();
}
function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time) {
RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey);
return (rateAndTime.rate, rateAndTime.time);
}
function getLastRoundIdBeforeElapsedSecs(
bytes32 currencyKey,
uint startingRoundId,
uint startingTimestamp,
uint timediff
) external view returns (uint) {
uint roundId = startingRoundId;
uint nextTimestamp = 0;
while (true) {
(, nextTimestamp) = _getRateAndTimestampAtRound(currencyKey, roundId + 1);
// if there's no new round, then the previous roundId was the latest
if (nextTimestamp == 0 || nextTimestamp > startingTimestamp + timediff) {
return roundId;
}
roundId++;
}
return roundId;
}
function getCurrentRoundId(bytes32 currencyKey) external view returns (uint) {
return _getCurrentRoundId(currencyKey);
}
function effectiveValueAtRound(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) external view returns (uint value) {
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
(uint srcRate, ) = _getRateAndTimestampAtRound(sourceCurrencyKey, roundIdForSrc);
(uint destRate, ) = _getRateAndTimestampAtRound(destinationCurrencyKey, roundIdForDest);
if (destRate == 0) {
// prevent divide-by 0 error (this can happen when roundIDs jump epochs due
// to aggregator upgrades)
return 0;
}
// Calculate the effective value by going from source -> USD -> destination
value = sourceAmount.multiplyDecimalRound(srcRate).divideDecimalRound(destRate);
}
function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time) {
return _getRateAndTimestampAtRound(currencyKey, roundId);
}
function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256) {
return _getUpdatedTime(currencyKey);
}
function lastRateUpdateTimesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) {
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = _getUpdatedTime(currencyKeys[i]);
}
return lastUpdateTimes;
}
function effectiveValue(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external view returns (uint value) {
(value, , ) = _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint value,
uint sourceRate,
uint destinationRate
)
{
return _effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function rateForCurrency(bytes32 currencyKey) external view returns (uint) {
return _getRateAndUpdatedTime(currencyKey).rate;
}
function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds)
external
view
returns (uint[] memory rates, uint[] memory times)
{
rates = new uint[](numRounds);
times = new uint[](numRounds);
uint roundId = _getCurrentRoundId(currencyKey);
for (uint i = 0; i < numRounds; i++) {
// fetch the rate and treat is as current, so inverse limits if frozen will always be applied
// regardless of current rate
(rates[i], times[i]) = _getRateAndTimestampAtRound(currencyKey, roundId);
if (roundId == 0) {
// if we hit the last round, then return what we have
return (rates, times);
} else {
roundId--;
}
}
}
function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory) {
uint[] memory _localRates = new uint[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
_localRates[i] = _getRate(currencyKeys[i]);
}
return _localRates;
}
function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid) {
RateAndUpdatedTime memory rateAndTime = _getRateAndUpdatedTime(currencyKey);
if (currencyKey == "sUSD") {
return (rateAndTime.rate, false);
}
return (
rateAndTime.rate,
_rateIsStaleWithTime(getRateStalePeriod(), rateAndTime.time) ||
_rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()))
);
}
function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys)
external
view
returns (uint[] memory rates, bool anyRateInvalid)
{
rates = new uint[](currencyKeys.length);
uint256 _rateStalePeriod = getRateStalePeriod();
// fetch all flags at once
bool[] memory flagList = getFlagsForRates(currencyKeys);
for (uint i = 0; i < currencyKeys.length; i++) {
// do one lookup of the rate & time to minimize gas
RateAndUpdatedTime memory rateEntry = _getRateAndUpdatedTime(currencyKeys[i]);
rates[i] = rateEntry.rate;
if (!anyRateInvalid && currencyKeys[i] != "sUSD") {
anyRateInvalid = flagList[i] || _rateIsStaleWithTime(_rateStalePeriod, rateEntry.time);
}
}
}
function rateIsStale(bytes32 currencyKey) external view returns (bool) {
return _rateIsStale(currencyKey, getRateStalePeriod());
}
function rateIsFrozen(bytes32 currencyKey) external view returns (bool) {
return _rateIsFrozen(currencyKey);
}
function rateIsInvalid(bytes32 currencyKey) external view returns (bool) {
return
_rateIsStale(currencyKey, getRateStalePeriod()) ||
_rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()));
}
function rateIsFlagged(bytes32 currencyKey) external view returns (bool) {
return _rateIsFlagged(currencyKey, FlagsInterface(getAggregatorWarningFlags()));
}
function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool) {
// Loop through each key and check whether the data point is stale.
uint256 _rateStalePeriod = getRateStalePeriod();
bool[] memory flagList = getFlagsForRates(currencyKeys);
for (uint i = 0; i < currencyKeys.length; i++) {
if (flagList[i] || _rateIsStale(currencyKeys[i], _rateStalePeriod)) {
return true;
}
}
return false;
}
/* ========== INTERNAL FUNCTIONS ========== */
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function getFlagsForRates(bytes32[] memory currencyKeys) internal view returns (bool[] memory flagList) {
FlagsInterface _flags = FlagsInterface(getAggregatorWarningFlags());
// fetch all flags at once
if (_flags != FlagsInterface(0)) {
address[] memory _aggregators = new address[](currencyKeys.length);
for (uint i = 0; i < currencyKeys.length; i++) {
_aggregators[i] = address(aggregators[currencyKeys[i]]);
}
flagList = _flags.getFlags(_aggregators);
} else {
flagList = new bool[](currencyKeys.length);
}
}
function _setRate(
bytes32 currencyKey,
uint256 rate,
uint256 time
) internal {
// Note: this will effectively start the rounds at 1, which matches Chainlink's Agggregators
currentRoundForRate[currencyKey]++;
_rates[currencyKey][currentRoundForRate[currencyKey]] = RateAndUpdatedTime({
rate: uint216(rate),
time: uint40(time)
});
}
function internalUpdateRates(
bytes32[] memory currencyKeys,
uint[] memory newRates,
uint timeSent
) internal returns (bool) {
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
// Loop through each key and perform update.
for (uint i = 0; i < currencyKeys.length; i++) {
bytes32 currencyKey = currencyKeys[i];
// Should not set any rate to zero ever, as no asset will ever be
// truely worthless and still valid. In this scenario, we should
// delete the rate and remove it from the system.
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
// We should only update the rate if it's at least the same age as the last rate we've got.
if (timeSent < _getUpdatedTime(currencyKey)) {
continue;
}
// Ok, go ahead with the update.
_setRate(currencyKey, newRates[i], timeSent);
}
emit RatesUpdated(currencyKeys, newRates);
return true;
}
function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) {
for (uint i = 0; i < array.length; i++) {
if (array[i] == entry) {
delete array[i];
// Copy the last key into the place of the one we just deleted
// If there's only one key, this is array[0] = array[0].
// If we're deleting the last one, it's also a NOOP in the same way.
array[i] = array[array.length - 1];
// Decrease the size of the array by one.
array.length--;
return true;
}
}
return false;
}
function _rateOrInverted(
bytes32 currencyKey,
uint rate,
uint roundId
) internal view returns (uint newRate) {
// if an inverse mapping exists, adjust the price accordingly
InversePricing memory inverse = inversePricing[currencyKey];
if (inverse.entryPoint == 0 || rate == 0) {
// when no inverse is set or when given a 0 rate, return the rate, regardless of the inverse status
// (the latter is so when a new inverse is set but the underlying has no rate, it will return 0 as
// the rate, not the lowerLimit)
return rate;
}
newRate = rate;
// Determine when round was frozen (if any)
uint roundWhenRateFrozen = roundFrozen[currencyKey];
// And if we're looking at a rate after frozen, and it's currently frozen, then apply the bounds limit even
// if the current price is back within bounds
if (roundId >= roundWhenRateFrozen && inverse.frozenAtUpperLimit) {
newRate = inverse.upperLimit;
} else if (roundId >= roundWhenRateFrozen && inverse.frozenAtLowerLimit) {
newRate = inverse.lowerLimit;
} else {
// this ensures any rate outside the limit will never be returned
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
// avoid negative numbers for unsigned ints, so set this to 0
// which by the requirement that lowerLimit be > 0 will
// cause this to freeze the price to the lowerLimit
newRate = 0;
} else {
newRate = doubleEntryPoint.sub(rate);
}
// now ensure the rate is between the bounds
if (newRate >= inverse.upperLimit) {
newRate = inverse.upperLimit;
} else if (newRate <= inverse.lowerLimit) {
newRate = inverse.lowerLimit;
}
}
}
function _formatAggregatorAnswer(bytes32 currencyKey, int256 rate) internal view returns (uint) {
require(rate >= 0, "Negative rate not supported");
if (currencyKeyDecimals[currencyKey] > 0) {
uint multiplier = 10**uint(SafeMath.sub(18, currencyKeyDecimals[currencyKey]));
return uint(uint(rate).mul(multiplier));
}
return uint(rate);
}
function _getRateAndUpdatedTime(bytes32 currencyKey) internal view returns (RateAndUpdatedTime memory) {
AggregatorV2V3Interface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorV2V3Interface(0)) {
// this view from the aggregator is the most gas efficient but it can throw when there's no data,
// so let's call it low-level to suppress any reverts
bytes memory payload = abi.encodeWithSignature("latestRoundData()");
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(aggregator).staticcall(payload);
if (success) {
(uint80 roundId, int256 answer, , uint256 updatedAt, ) = abi.decode(
returnData,
(uint80, int256, uint256, uint256, uint80)
);
return
RateAndUpdatedTime({
rate: uint216(_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId)),
time: uint40(updatedAt)
});
}
} else {
uint roundId = currentRoundForRate[currencyKey];
RateAndUpdatedTime memory entry = _rates[currencyKey][roundId];
return RateAndUpdatedTime({rate: uint216(_rateOrInverted(currencyKey, entry.rate, roundId)), time: entry.time});
}
}
function _getCurrentRoundId(bytes32 currencyKey) internal view returns (uint) {
AggregatorV2V3Interface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorV2V3Interface(0)) {
return aggregator.latestRound();
} else {
return currentRoundForRate[currencyKey];
}
}
function _getRateAndTimestampAtRound(bytes32 currencyKey, uint roundId) internal view returns (uint rate, uint time) {
AggregatorV2V3Interface aggregator = aggregators[currencyKey];
if (aggregator != AggregatorV2V3Interface(0)) {
// this view from the aggregator is the most gas efficient but it can throw when there's no data,
// so let's call it low-level to suppress any reverts
bytes memory payload = abi.encodeWithSignature("getRoundData(uint80)", roundId);
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnData) = address(aggregator).staticcall(payload);
if (success) {
(, int256 answer, , uint256 updatedAt, ) = abi.decode(
returnData,
(uint80, int256, uint256, uint256, uint80)
);
return (_rateOrInverted(currencyKey, _formatAggregatorAnswer(currencyKey, answer), roundId), updatedAt);
}
} else {
RateAndUpdatedTime memory update = _rates[currencyKey][roundId];
return (_rateOrInverted(currencyKey, update.rate, roundId), update.time);
}
}
function _getRate(bytes32 currencyKey) internal view returns (uint256) {
return _getRateAndUpdatedTime(currencyKey).rate;
}
function _getUpdatedTime(bytes32 currencyKey) internal view returns (uint256) {
return _getRateAndUpdatedTime(currencyKey).time;
}
function _effectiveValueAndRates(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
)
internal
view
returns (
uint value,
uint sourceRate,
uint destinationRate
)
{
sourceRate = _getRate(sourceCurrencyKey);
// If there's no change in the currency, then just return the amount they gave us
if (sourceCurrencyKey == destinationCurrencyKey) {
destinationRate = sourceRate;
value = sourceAmount;
} else {
// Calculate the effective value by going from source -> USD -> destination
destinationRate = _getRate(destinationCurrencyKey);
// prevent divide-by 0 error (this happens if the dest is not a valid rate)
if (destinationRate > 0) {
value = sourceAmount.multiplyDecimalRound(sourceRate).divideDecimalRound(destinationRate);
}
}
}
function _rateIsStale(bytes32 currencyKey, uint _rateStalePeriod) internal view returns (bool) {
// sUSD is a special case and is never stale (check before an SLOAD of getRateAndUpdatedTime)
if (currencyKey == "sUSD") return false;
return _rateIsStaleWithTime(_rateStalePeriod, _getUpdatedTime(currencyKey));
}
function _rateIsStaleWithTime(uint _rateStalePeriod, uint _time) internal view returns (bool) {
return _time.add(_rateStalePeriod) < now;
}
function _rateIsFrozen(bytes32 currencyKey) internal view returns (bool) {
InversePricing memory inverse = inversePricing[currencyKey];
return inverse.frozenAtUpperLimit || inverse.frozenAtLowerLimit;
}
function _rateIsFlagged(bytes32 currencyKey, FlagsInterface flags) internal view returns (bool) {
// sUSD is a special case and is never invalid
if (currencyKey == "sUSD") return false;
address aggregator = address(aggregators[currencyKey]);
// when no aggregator or when the flags haven't been setup
if (aggregator == address(0) || flags == FlagsInterface(0)) {
return false;
}
return flags.getFlag(aggregator);
}
/* ========== MODIFIERS ========== */
modifier onlyOracle {
_onlyOracle();
_;
}
function _onlyOracle() internal view {
require(msg.sender == oracle, "Only the oracle can perform this action");
}
/* ========== EVENTS ========== */
event OracleUpdated(address newOracle);
event RatesUpdated(bytes32[] currencyKeys, uint[] newRates);
event RateDeleted(bytes32 currencyKey);
event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit);
event InversePriceFrozen(bytes32 currencyKey, uint rate, uint roundId, address initiator);
event AggregatorAdded(bytes32 currencyKey, address aggregator);
event AggregatorRemoved(bytes32 currencyKey, address aggregator);
}
| 36,106 |
14 | // Restake rewards generated by delegation to a multiple validators.validatorContractAddresses List of validator contract address. / | function restakeMultiple(
IValidatorShareProxy[] memory validatorContractAddresses
| function restakeMultiple(
IValidatorShareProxy[] memory validatorContractAddresses
| 33,635 |
40 | // no overflow in `_a + _b` | uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
uint256 y = _scale - x;
return (x, y);
| uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
uint256 y = _scale - x;
return (x, y);
| 85,013 |
1 | // @inheritdoc IYumyumSwapPoolDeployer | Parameters public override parameters;
| Parameters public override parameters;
| 16,415 |
91 | // uint[] memory output = IUniswapV2Router02(rout).swapExactTokensForTokens(in_amount, minOut, path, receiver, deadline); | IUniswapV2Router02(rout).swapExactTokensForTokensSupportingFeeOnTransferTokens(in_amount, minOut, path, receiver, deadline);
IERC20(path[0]).safeDecreaseAllowance(rout, IERC20(path[0]).allowance(address(this), rout));
| IUniswapV2Router02(rout).swapExactTokensForTokensSupportingFeeOnTransferTokens(in_amount, minOut, path, receiver, deadline);
IERC20(path[0]).safeDecreaseAllowance(rout, IERC20(path[0]).allowance(address(this), rout));
| 21,915 |
152 | // 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
}
| 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
}
| 52,341 |
148 | // Deposit Fee address | address public feeAddress;
| address public feeAddress;
| 40,903 |
94 | // TransferFrom recipient recives amount, sender's account is debited amount + fee | function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
uint256 burnAmount = burnFee.mul(amount).div(10000);
uint256 charityAmount = charityFee.mul(amount).div(10000);
uint256 taxAmount = burnAmount.add(charityAmount);
uint256 transferAmount = amount.sub(taxAmount);
// Burn and Charity cut
_burn(sender, burnAmount);
_transfer(sender, charityWallet, charityAmount);
// Transfer
_transfer(sender, recipient, transferAmount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
uint256 burnAmount = burnFee.mul(amount).div(10000);
uint256 charityAmount = charityFee.mul(amount).div(10000);
uint256 taxAmount = burnAmount.add(charityAmount);
uint256 transferAmount = amount.sub(taxAmount);
// Burn and Charity cut
_burn(sender, burnAmount);
_transfer(sender, charityWallet, charityAmount);
// Transfer
_transfer(sender, recipient, transferAmount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| 82,364 |
33 | // burn token | if(burnAmount>0){
_burn(sender,burnAmount);
}
| if(burnAmount>0){
_burn(sender,burnAmount);
}
| 39,200 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.