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
|
---|---|---|---|---|
4 | // The JOY Token | IERC20Upgradeable public govToken;
| IERC20Upgradeable public govToken;
| 65,681 |
683 | // Get numerator | uint256 numerator = block.timestamp <= numeratorSwapTime ? 4 : 6;
| uint256 numerator = block.timestamp <= numeratorSwapTime ? 4 : 6;
| 49,467 |
20 | // approved beneficiary flag defines whether someone can recieve | if (_value > 0) {
attributes[_account] |= LIQUIDATOR_CAN_RECEIVE;
} else {
| if (_value > 0) {
attributes[_account] |= LIQUIDATOR_CAN_RECEIVE;
} else {
| 34,866 |
132 | // USDC/Compound | pool = ISaffronPool(pools[12]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[12]) > 0) pool.hourly_strategy(adapters[4]);
| pool = ISaffronPool(pools[12]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[12]) > 0) pool.hourly_strategy(adapters[4]);
| 19,423 |
100 | // Throws if called by any account other than the Admin. / | modifier onlyAdmin() {
require(
_admins[_msgSender()] || _msgSender() == owner(),
"Caller does not have Admin Access"
);
_;
}
| modifier onlyAdmin() {
require(
_admins[_msgSender()] || _msgSender() == owner(),
"Caller does not have Admin Access"
);
_;
}
| 24,561 |
210 | // oldDescriptionURI | _getBaseDescriptionURI(),
| _getBaseDescriptionURI(),
| 19,919 |
64 | // Calculate and mint the amount of xRigel the Rigel is worth. The ratio will change overtime, as xRigel is burned/minted and Rigel deposited + gained from fees / withdrawn. | else {
uint256 what = _amount.mul(totalShares).div(totalRigel);
_mint(msg.sender, what);
}
| else {
uint256 what = _amount.mul(totalShares).div(totalRigel);
_mint(msg.sender, what);
}
| 25,277 |
38 | // Transfers the LP tokens out | IERC20Upgradeable(_lps[i]).safeTransfer(msg.sender, _lpAmounts[i]);
| IERC20Upgradeable(_lps[i]).safeTransfer(msg.sender, _lpAmounts[i]);
| 5,515 |
187 | // Performs a Solidity function call using a low level `call`. Aplain `call` is an unsafe replacement for a function call: use thisfunction instead. If `target` reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract.- calling `target` with `data` must not revert. _Available since v3.1._ / | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| 144 |
6 | // Mapping of messageId to gas limit | mapping(bytes32 => uint256) public messageGasLimit;
| mapping(bytes32 => uint256) public messageGasLimit;
| 32,537 |
233 | // Interface for REWARDS_VAULTINHERITANCE: / | interface REWARDS_VAULT_Interface {
function payRewards(uint256 _tokenId, uint256 _amount) external;
}
| interface REWARDS_VAULT_Interface {
function payRewards(uint256 _tokenId, uint256 _amount) external;
}
| 32,850 |
213 | // See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``'s tokens of at least`amount`. / | function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
| function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
| 52,596 |
121 | // Update pool infos with old reward rate before setting new one first | for (uint i = 0; i < poolInfo.length; i++) {
PoolInfo storage pool = poolInfo[i];
if (block.number <= pool.lastRewardBlock) {
continue;
}
| for (uint i = 0; i < poolInfo.length; i++) {
PoolInfo storage pool = poolInfo[i];
if (block.number <= pool.lastRewardBlock) {
continue;
}
| 34,747 |
242 | // Pull the Collateral Asset from the CollateralLocker, swap to the Liquidity Asset, and hold custody of the resulting Liquidity Asset in the Loan. | (amountLiquidated, amountRecovered) = LoanLib.liquidateCollateral(collateralAsset, address(liquidityAsset), superFactory, collateralLocker);
_emitBalanceUpdateEventForCollateralLocker();
| (amountLiquidated, amountRecovered) = LoanLib.liquidateCollateral(collateralAsset, address(liquidityAsset), superFactory, collateralLocker);
_emitBalanceUpdateEventForCollateralLocker();
| 6,419 |
393 | // Emitted when ARTT is distributed to a supplier | event DistributedSupplierArtem(AToken indexed aToken, address indexed supplier, uint artemDelta, uint artemSupplyIndex);
| event DistributedSupplierArtem(AToken indexed aToken, address indexed supplier, uint artemDelta, uint artemSupplyIndex);
| 17,047 |
0 | // Possible states for an operation in this timelock contract | enum OperationState {
Unknown,
Scheduled,
ReadyForExecution,
Executed
}
| enum OperationState {
Unknown,
Scheduled,
ReadyForExecution,
Executed
}
| 1,696 |
0 | // constructor(<other arguments>, address _vrfCoordinator, address _link) | * @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
| * @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
| 34,542 |
9 | // Panic strategy | function panic() external;
| function panic() external;
| 36,448 |
380 | // Allows the sender to purchase tokens by providing payment tokens. paymentToken_ The address of the payment token. quantity_ The quantity of tokens to purchase. / | function buy(address paymentToken_, uint256 quantity_) external payable override nonReentrant {
address sender = _msgSender();
uint256 amount = _paymentAmount[paymentToken_];
uint256 tokenId = _idCounter;
unchecked {
if (tokenId + quantity_ - 1 > MAX_SUPLLY) revert BoiChillClub__ExceedLimit();
}
uint256 total = amount * quantity_;
if (total == 0) revert BoiChillClub__ZeroValue();
if (paymentToken_ == address(0)) {
if (msg.value < total) revert BoiChillClub__InsufficientBalance();
SafeTransferLib.safeTransferETH(_recipient, total);
} else {
SafeTransferLib.safeTransferFrom(paymentToken_, sender, _recipient, total);
}
emit BatchMint(sender, tokenId, quantity_);
_batchMint(sender, tokenId, quantity_);
}
| function buy(address paymentToken_, uint256 quantity_) external payable override nonReentrant {
address sender = _msgSender();
uint256 amount = _paymentAmount[paymentToken_];
uint256 tokenId = _idCounter;
unchecked {
if (tokenId + quantity_ - 1 > MAX_SUPLLY) revert BoiChillClub__ExceedLimit();
}
uint256 total = amount * quantity_;
if (total == 0) revert BoiChillClub__ZeroValue();
if (paymentToken_ == address(0)) {
if (msg.value < total) revert BoiChillClub__InsufficientBalance();
SafeTransferLib.safeTransferETH(_recipient, total);
} else {
SafeTransferLib.safeTransferFrom(paymentToken_, sender, _recipient, total);
}
emit BatchMint(sender, tokenId, quantity_);
_batchMint(sender, tokenId, quantity_);
}
| 40,035 |
25 | // Approve a new miner split minerAddress Address of miner splitTo Address that receives split splitPct % of tip that splitTo receives salt salt / | function approveNewMinerSplit(
address minerAddress,
address splitTo,
uint32 splitPct,
bytes32 salt
| function approveNewMinerSplit(
address minerAddress,
address splitTo,
uint32 splitPct,
bytes32 salt
| 43,711 |
4 | // Sends multiple tokens to a single address _tokenID The address to receive the tokens _address The address to receive the tokens _quantity How many to send she receiver / | function batchMint(
uint256 _tokenID,
address _address,
uint256 _quantity
| function batchMint(
uint256 _tokenID,
address _address,
uint256 _quantity
| 23,337 |
16 | // calculate the original amount of tokens this account got | uint256 userOriginalBalance = _securityToken
.balanceOfByPartition(partition, from)
| uint256 userOriginalBalance = _securityToken
.balanceOfByPartition(partition, from)
| 33,172 |
6 | // Updates the liquidity cumulative index and the variable borrow index. reserve the reserve object / | function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt =
IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =
_updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex
);
}
| function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt =
IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =
_updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex
);
}
| 33,949 |
22 | // according to AssetToken's total supply, never overflow here | if (balanceOf[msg.sender] >= _amount
&& _amount > 0) {
balanceOf[msg.sender] -= uint112(_amount);
balanceOf[_to] = _amount.add(balanceOf[_to]).toUINT112();
soldToken = _amount.add(soldToken).toUINT112();
Transfer(msg.sender, _to, _amount);
return true;
} else {
| if (balanceOf[msg.sender] >= _amount
&& _amount > 0) {
balanceOf[msg.sender] -= uint112(_amount);
balanceOf[_to] = _amount.add(balanceOf[_to]).toUINT112();
soldToken = _amount.add(soldToken).toUINT112();
Transfer(msg.sender, _to, _amount);
return true;
} else {
| 26,450 |
2 | // Struct for storing cached currency whitelist. | struct WhitelistedCurrency {
bool isWhitelisted; // True if the currency is whitelisted.
uint256 finalFee; // Final fee of the currency.
}
| struct WhitelistedCurrency {
bool isWhitelisted; // True if the currency is whitelisted.
uint256 finalFee; // Final fee of the currency.
}
| 30,340 |
41 | // calculate reward | uint256 reward = PRBMathUD60x18.mul(percentOfTotal, _lastTaxPool);
| uint256 reward = PRBMathUD60x18.mul(percentOfTotal, _lastTaxPool);
| 12,764 |
25 | // Transfer token for a specified address_to The address to transfer to._value The amount to be transferred./ | function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
checkUsers(msg.sender, _to);
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
if (_to == dex) {
BulDex(dex).exchange(msg.sender, _value);
}
return true;
}
| function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
checkUsers(msg.sender, _to);
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
if (_to == dex) {
BulDex(dex).exchange(msg.sender, _value);
}
return true;
}
| 9,474 |
0 | // Define the Turk token contract | constructor(IERC20 _turk) public {
turk = _turk;
}
| constructor(IERC20 _turk) public {
turk = _turk;
}
| 42,222 |
51 | // constants defining roles for access control | string public constant ROLE_ADMIN = "admin";
string public constant ROLE_BACKEND = "backend";
string public constant ROLE_KYC_VERIFIED_INVESTOR = "kycVerified";
| string public constant ROLE_ADMIN = "admin";
string public constant ROLE_BACKEND = "backend";
string public constant ROLE_KYC_VERIFIED_INVESTOR = "kycVerified";
| 57,868 |
55 | // If execution failed, | require(success, 'Execution failed');
| require(success, 'Execution failed');
| 72,177 |
113 | // return the amount of wei raised. / | function weiRaised() public view returns (uint256) {
return _weiRaised;
}
| function weiRaised() public view returns (uint256) {
return _weiRaised;
}
| 12,288 |
34 | // sets crowdsale address | function setFront ( address _front ) onlyOwner {
front = _front;
}
| function setFront ( address _front ) onlyOwner {
front = _front;
}
| 39,847 |
17 | // address => boolean to check if the address is a minter | mapping(address => bool) public isMinter;
mapping(address => bool) public isRouter;
event Minted(address to, uint256 amount);
event TaxFeeChanged(uint96 taxFee);
event CooldownTimeChanged(uint256 cooldownTime);
event StageChanged(Stages stage);
event CooldownSet(address addr, uint256 cooldown);
event TransferWithTax(
address sender,
| mapping(address => bool) public isMinter;
mapping(address => bool) public isRouter;
event Minted(address to, uint256 amount);
event TaxFeeChanged(uint96 taxFee);
event CooldownTimeChanged(uint256 cooldownTime);
event StageChanged(Stages stage);
event CooldownSet(address addr, uint256 cooldown);
event TransferWithTax(
address sender,
| 26,547 |
6 | // Check _pooledTokens and precisions parameter | require(numPooledTokens > Constants.MINIMUM_POOLED_TOKENS - 1, "_pooledTokens.length insufficient");
require(numPooledTokens < Constants.MAXIMUM_POOLED_TOKENS + 1, "_pooledTokens.length too large");
require(numPooledTokens == decimals.length, "_pooledTokens decimals mismatch");
uint256[] memory precisionMultipliers = new uint256[](decimals.length);
for (uint256 i = 0; i < numPooledTokens; ) {
if (i != 0) {
| require(numPooledTokens > Constants.MINIMUM_POOLED_TOKENS - 1, "_pooledTokens.length insufficient");
require(numPooledTokens < Constants.MAXIMUM_POOLED_TOKENS + 1, "_pooledTokens.length too large");
require(numPooledTokens == decimals.length, "_pooledTokens decimals mismatch");
uint256[] memory precisionMultipliers = new uint256[](decimals.length);
for (uint256 i = 0; i < numPooledTokens; ) {
if (i != 0) {
| 20,939 |
124 | // Check for zero transfer, and make sure it returns true to returnValue | function verifyTokenComplianceInternal(address token) internal {
bool returnValue = IERC20(token).transfer(msg.sender, 0);
require(returnValue, "ERR_NONCONFORMING_TOKEN");
}
| function verifyTokenComplianceInternal(address token) internal {
bool returnValue = IERC20(token).transfer(msg.sender, 0);
require(returnValue, "ERR_NONCONFORMING_TOKEN");
}
| 9,219 |
65 | // prelim. parameter checks | require(amount != 0, "Invalid amount");
| require(amount != 0, "Invalid amount");
| 41,225 |
15 | // Prevent the user from submitting the same bet again Send `_commission` to `owner` from the winner's prize_better The address of the sender _matchId The matchId to find the msg.sender's betting info _bettingPrice The betting price to find the msg.sender's betting info / | function checkDuplicateMatchId(address _better, uint256 _matchId, uint _bettingPrice) public view returns (bool) {
uint numOfBetterBettingInfo = betterBettingInfo[_better].length;
for (uint i = 0; i < numOfBetterBettingInfo; i++) {
if (betterBettingInfo[_better][i].matchId == _matchId && betterBettingInfo[_better][i].bettingPrice == _bettingPrice) {
return true;
}
}
return false;
}
| function checkDuplicateMatchId(address _better, uint256 _matchId, uint _bettingPrice) public view returns (bool) {
uint numOfBetterBettingInfo = betterBettingInfo[_better].length;
for (uint i = 0; i < numOfBetterBettingInfo; i++) {
if (betterBettingInfo[_better][i].matchId == _matchId && betterBettingInfo[_better][i].bettingPrice == _bettingPrice) {
return true;
}
}
return false;
}
| 24,463 |
0 | // ================================= only people with tokens | modifier onlybelievers () {
require(myTokens() > 0);
_;
}
| modifier onlybelievers () {
require(myTokens() > 0);
_;
}
| 38,182 |
131 | // Chances out of 1000 to mint a particular map piece. | uint[] public PIECES_CHANCES = [1, 5, 25, 40, 60, 80, 100, 150, 160, 180, 200];
uint constant public MAX_PIECES_PER_MINT = 20;
uint constant public MAX_TOTAL_SUPPLY = 10000;
uint constant public MAX_REDEEMS = 40;
uint constant public PRICE_PER_PIECE = 0.05 ether;
uint constant public TREASURE = 10 ether;
uint public treasuresRedeemed;
bool public saleStarted = false;
| uint[] public PIECES_CHANCES = [1, 5, 25, 40, 60, 80, 100, 150, 160, 180, 200];
uint constant public MAX_PIECES_PER_MINT = 20;
uint constant public MAX_TOTAL_SUPPLY = 10000;
uint constant public MAX_REDEEMS = 40;
uint constant public PRICE_PER_PIECE = 0.05 ether;
uint constant public TREASURE = 10 ether;
uint public treasuresRedeemed;
bool public saleStarted = false;
| 56,062 |
35 | // Token decimals | uint8 public constant DECIMALS = 18;
| uint8 public constant DECIMALS = 18;
| 22,664 |
3 | // 出于安全考虑,当调用到本合约中没有出现的 ACL Method 都会被拒绝 | revert("Unauthorized access");
| revert("Unauthorized access");
| 39,968 |
5 | // Set the allowance to the exact amount the user wants to transfer | require(token.approve(address(this), amount), "Token approval failed");
| require(token.approve(address(this), amount), "Token approval failed");
| 12,464 |
2 | // Rating supplied by the buyer (Step 3, optional). | uint ratingValue; // Seller rating supplied by buyer.
string ratingComment; // Comment on this transaction supplied by the buyer.
bool rated; // Flag that states this transaction has already been rated.
| uint ratingValue; // Seller rating supplied by buyer.
string ratingComment; // Comment on this transaction supplied by the buyer.
bool rated; // Flag that states this transaction has already been rated.
| 17,252 |
8 | // distribute 20% on TGE | amount = amount.add(vestingAmount.div(5));
| amount = amount.add(vestingAmount.div(5));
| 30,989 |
11 | // --- CALLER CONTRACT --- Contract stores the functions that interact with the protocols of MakerDao and Uniswap | contract CallerContract is HelperContract {
// Build DS Proxy for the CallerContract
function buildProxy() public NoExistingProxy {
prl.build();
proxy = prl.proxies(address(this)); // Safe proxy address to state variable
}
// Open CDP, lock some Eth and draw Dai
function openLockETHAndDraw(uint256 input, uint256 drawAmount)
public
payable
onlyMyself
NoExistingCDP
{
bytes memory payload =
abi.encodeWithSignature(
"openLockETHAndDraw(address,address,address,address,bytes32,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
ilk,
drawAmount
);
(bool success, ) =
proxy.call{value: input}(
abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions,
payload
)
);
cdpi = dcml.first(proxy);
MCD_UrnHandler = dcml.urns(cdpi);
}
// Lock some Eth and draw Dai
function lockETHAndDraw(uint256 input, uint256 drawAmount)
public
payable
onlyMyself
{
bytes memory payload =
abi.encodeWithSignature(
"lockETHAndDraw(address,address,address,address,uint256,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
cdpi,
drawAmount
);
(bool success, ) =
proxy.call{value: input}(
abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions,
payload
)
);
}
// Approve Uniswap to take Dai tokens
function approveUNIRouter(uint256 value) public onlyMyself {
bool success = dai.approve(UNI_Router, value);
require(success);
}
// Execute Swap from Dai to Weth on Uniswap
function swapDAItoETH(uint256 value_in, uint256 value_out)
public
onlyMyself
returns (uint256[] memory amounts)
{
address[] memory path = new address[](2);
path[0] = address(DAI_TOKEN);
path[1] = url.WETH();
// IN and OUT amounts
uint256 amount_in = value_in;
uint256 amount_out = value_out;
amounts = url.swapExactTokensForETH(
amount_in,
amount_out,
path,
address(this),
block.timestamp + 60
);
return amounts;
}
// Swap WETH to ETH
function wethToEthSwap() public onlyMyself {
weth.withdraw(wethBalance());
}
// Pay back contract's ether to owner
function payBack() public onlyMyself {
owner.transfer(address(this).balance);
}
fallback() external payable {}
receive() external payable {}
}
| contract CallerContract is HelperContract {
// Build DS Proxy for the CallerContract
function buildProxy() public NoExistingProxy {
prl.build();
proxy = prl.proxies(address(this)); // Safe proxy address to state variable
}
// Open CDP, lock some Eth and draw Dai
function openLockETHAndDraw(uint256 input, uint256 drawAmount)
public
payable
onlyMyself
NoExistingCDP
{
bytes memory payload =
abi.encodeWithSignature(
"openLockETHAndDraw(address,address,address,address,bytes32,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
ilk,
drawAmount
);
(bool success, ) =
proxy.call{value: input}(
abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions,
payload
)
);
cdpi = dcml.first(proxy);
MCD_UrnHandler = dcml.urns(cdpi);
}
// Lock some Eth and draw Dai
function lockETHAndDraw(uint256 input, uint256 drawAmount)
public
payable
onlyMyself
{
bytes memory payload =
abi.encodeWithSignature(
"lockETHAndDraw(address,address,address,address,uint256,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
cdpi,
drawAmount
);
(bool success, ) =
proxy.call{value: input}(
abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions,
payload
)
);
}
// Approve Uniswap to take Dai tokens
function approveUNIRouter(uint256 value) public onlyMyself {
bool success = dai.approve(UNI_Router, value);
require(success);
}
// Execute Swap from Dai to Weth on Uniswap
function swapDAItoETH(uint256 value_in, uint256 value_out)
public
onlyMyself
returns (uint256[] memory amounts)
{
address[] memory path = new address[](2);
path[0] = address(DAI_TOKEN);
path[1] = url.WETH();
// IN and OUT amounts
uint256 amount_in = value_in;
uint256 amount_out = value_out;
amounts = url.swapExactTokensForETH(
amount_in,
amount_out,
path,
address(this),
block.timestamp + 60
);
return amounts;
}
// Swap WETH to ETH
function wethToEthSwap() public onlyMyself {
weth.withdraw(wethBalance());
}
// Pay back contract's ether to owner
function payBack() public onlyMyself {
owner.transfer(address(this).balance);
}
fallback() external payable {}
receive() external payable {}
}
| 18,263 |
8 | // collaboration of update / consult | function expectedPrice(address token, uint256 amountIn)
external
view
returns (uint224 amountOut)
| function expectedPrice(address token, uint256 amountIn)
external
view
returns (uint224 amountOut)
| 27,837 |
43 | // A simple holder of tokens.This is a simple contract to hold tokens. It's useful in the case where a separate contractneeds to hold multiple distinct pools of the same token. / | contract TokenPool is Ownable {
IERC20 public token;
constructor(IERC20 _token) public {
token = _token;
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function transfer(address to, uint256 value) external onlyOwner returns (bool) {
return token.transfer(to, value);
}
}
| contract TokenPool is Ownable {
IERC20 public token;
constructor(IERC20 _token) public {
token = _token;
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function transfer(address to, uint256 value) external onlyOwner returns (bool) {
return token.transfer(to, value);
}
}
| 30,376 |
32 | // Stores STAKE ACCOUNT details of the USER | struct StakeAccount {
uint256 stakedAmount;
uint256 time;
uint256 interestRate;
bool unstaked;
}
| struct StakeAccount {
uint256 stakedAmount;
uint256 time;
uint256 interestRate;
bool unstaked;
}
| 11,122 |
50 | // WARNING //THIS CONTRACT IS UPGRADEABLE!//---------------------------------------------------------------------------------------------//Do NOT change the order of or PREPEND any storage variables to this or new versions of this//contract as this will cause the the storage slots to be overwritten on the proxy contract!!// //more information.// / | contract Settings is SettingsInterface, TInitializable, Pausable, BaseUpgradeable {
using AddressLib for address;
using Address for address;
using AssetSettingsLib for AssetSettingsLib.AssetSettings;
using AddressArrayLib for address[];
using PlatformSettingsLib for PlatformSettingsLib.PlatformSetting;
/** Constants */
/**
@notice The asset setting name for the maximum loan amount settings.
*/
bytes32 public constant MAX_LOAN_AMOUNT_ASSET_SETTING = "MaxLoanAmount";
/**
@notice The asset setting name for cToken address settings.
*/
bytes32 public constant CTOKEN_ADDRESS_ASSET_SETTING = "CTokenAddress";
/**
@notice It defines the constant address to represent ETHER.
*/
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/* State Variables */
/**
@notice It represents a mapping to identify the lending pools paused and not paused.
i.e.: address(lending pool) => true or false.
*/
mapping(address => bool) public lendingPoolPaused;
/**
@notice It represents a mapping to configure the asset settings.
@notice The key belongs to the asset address. Example: address(DAI) or address(USDC).
@notice The value has the asset settings.
Examples:
address(DAI) => {
cTokenAddress = 0x1234...890
maxLoanAmount = 1000 DAI (max)
}
address(USDC) => {
cTokenAddress = 0x2345...901
maxLoanAmount = 500 USDC (max)
}
*/
mapping(address => AssetSettingsLib.AssetSettings) public assetSettings;
/**
@notice It contains all the current assets.
*/
address[] public assets;
/**
@notice This mapping represents the platform settings where:
- The key is the platform setting name.
- The value is the platform setting. It includes the value, minimum and maximum values.
*/
mapping(bytes32 => PlatformSettingsLib.PlatformSetting) public platformSettings;
/**
@notice It is the global instance of the EscrowFactory contract.
*/
EscrowFactoryInterface public escrowFactory;
/**
@notice It is the global instance of the logic versions registry contract.
*/
LogicVersionsRegistryInterface public versionsRegistry;
/**
@notice It is the global instance of the ChainlinkPairAggregatorRegistry contract.
*/
IChainlinkPairAggregatorRegistry public pairAggregatorRegistry;
/**
@notice The markets state.
*/
MarketsStateInterface public marketsState;
/**
@notice The current interest validator.
*/
InterestValidatorInterface public interestValidator;
/**
@notice The current ATM settings.
*/
IATMSettings public atmSettings;
/** Modifiers */
/* Constructor */
/** External Functions */
/**
@notice It creates a new platform setting given a setting name, value, min and max values.
@param settingName setting name to create.
@param value the initial value for the given setting name.
@param minValue the min value for the setting.
@param maxValue the max value for the setting.
*/
function createPlatformSetting(
bytes32 settingName,
uint256 value,
uint256 minValue,
uint256 maxValue
) external onlyPauser() isInitialized() {
require(settingName != "", "SETTING_NAME_MUST_BE_PROVIDED");
platformSettings[settingName].initialize(value, minValue, maxValue);
emit PlatformSettingCreated(settingName, msg.sender, value, minValue, maxValue);
}
/**
@notice It updates an existent platform setting given a setting name.
@notice It only allows to update the value (not the min or max values).
@notice In case you need to update the min or max values, you need to remove it, and create it again.
@param settingName setting name to update.
@param newValue the new value to set.
*/
function updatePlatformSetting(bytes32 settingName, uint256 newValue)
external
onlyPauser()
isInitialized()
{
uint256 oldValue = platformSettings[settingName].update(newValue);
emit PlatformSettingUpdated(settingName, msg.sender, oldValue, newValue);
}
/**
@notice Removes a current platform setting given a setting name.
@param settingName to remove.
*/
function removePlatformSetting(bytes32 settingName)
external
onlyPauser()
isInitialized()
{
uint256 oldValue = platformSettings[settingName].value;
platformSettings[settingName].remove();
emit PlatformSettingRemoved(settingName, oldValue, msg.sender);
}
/**
@notice It gets the current platform setting for a given setting name
@param settingName to get.
@return the current platform setting.
*/
function getPlatformSetting(bytes32 settingName)
external
view
returns (PlatformSettingsLib.PlatformSetting memory)
{
return _getPlatformSetting(settingName);
}
/**
@notice It gets the current platform setting value for a given setting name
@param settingName to get.
@return the current platform setting value.
*/
function getPlatformSettingValue(bytes32 settingName)
external
view
returns (uint256)
{
return _getPlatformSetting(settingName).value;
}
/**
@notice It tests whether a setting name is already configured.
@param settingName setting name to test.
@return true if the setting is already configured. Otherwise it returns false.
*/
function hasPlatformSetting(bytes32 settingName) external view returns (bool) {
return _getPlatformSetting(settingName).exists;
}
/**
@notice It pauses a specific lending pool.
@param lendingPoolAddress lending pool address to pause.
*/
function pauseLendingPool(address lendingPoolAddress)
external
onlyPauser()
whenNotPaused()
isInitialized()
{
lendingPoolAddress.requireNotEmpty("LENDING_POOL_IS_REQUIRED");
require(!lendingPoolPaused[lendingPoolAddress], "LENDING_POOL_ALREADY_PAUSED");
lendingPoolPaused[lendingPoolAddress] = true;
emit LendingPoolPaused(msg.sender, lendingPoolAddress);
}
/**
@notice It unpauses a specific lending pool.
@param lendingPoolAddress lending pool address to unpause.
*/
function unpauseLendingPool(address lendingPoolAddress)
external
onlyPauser()
whenNotPaused()
isInitialized()
{
lendingPoolAddress.requireNotEmpty("LENDING_POOL_IS_REQUIRED");
require(lendingPoolPaused[lendingPoolAddress], "LENDING_POOL_IS_NOT_PAUSED");
lendingPoolPaused[lendingPoolAddress] = false;
emit LendingPoolUnpaused(msg.sender, lendingPoolAddress);
}
/**
@notice It gets whether the platform is paused or not.
@return true if platform is paused. Otherwise it returns false.
*/
function isPaused() external view returns (bool) {
return paused();
}
/**
@notice It creates a new asset settings in the platform.
@param assetAddress asset address used to create the new setting.
@param cTokenAddress cToken address used to configure the asset setting.
@param maxLoanAmount the max loan amount used to configure the asset setting.
*/
function createAssetSettings(
address assetAddress,
address cTokenAddress,
uint256 maxLoanAmount
) external onlyPauser() isInitialized() {
require(assetAddress.isContract(), "ASSET_ADDRESS_MUST_BE_CONTRACT");
assetSettings[assetAddress].requireNotExists();
assetSettings[assetAddress].initialize(cTokenAddress, maxLoanAmount);
assets.add(assetAddress);
emit AssetSettingsCreated(msg.sender, assetAddress, cTokenAddress, maxLoanAmount);
}
/**
@notice It removes all the asset settings for a specific asset address.
@param assetAddress asset address used to remove the asset settings.
*/
function removeAssetSettings(address assetAddress)
external
onlyPauser()
isInitialized()
{
assetAddress.requireNotEmpty("ASSET_ADDRESS_IS_REQUIRED");
assetSettings[assetAddress].requireExists();
delete assetSettings[assetAddress];
assets.remove(assetAddress);
emit AssetSettingsRemoved(msg.sender, assetAddress);
}
/**
@notice It updates the maximum loan amount for a specific asset address.
@param assetAddress asset address to configure.
@param newMaxLoanAmount the new maximum loan amount to configure.
*/
function updateMaxLoanAmount(address assetAddress, uint256 newMaxLoanAmount)
external
onlyPauser()
isInitialized()
{
uint256 oldMaxLoanAmount = assetSettings[assetAddress].maxLoanAmount;
assetSettings[assetAddress].updateMaxLoanAmount(newMaxLoanAmount);
emit AssetSettingsUintUpdated(
MAX_LOAN_AMOUNT_ASSET_SETTING,
msg.sender,
assetAddress,
oldMaxLoanAmount,
newMaxLoanAmount
);
}
/**
@notice It updates the cToken address for a specific asset address.
@param assetAddress asset address to configure.
@param newCTokenAddress the new cToken address to configure.
*/
function updateCTokenAddress(address assetAddress, address newCTokenAddress)
external
onlyPauser()
isInitialized()
{
address oldCTokenAddress = assetSettings[assetAddress].cTokenAddress;
assetSettings[assetAddress].updateCTokenAddress(newCTokenAddress);
emit AssetSettingsAddressUpdated(
CTOKEN_ADDRESS_ASSET_SETTING,
msg.sender,
assetAddress,
oldCTokenAddress,
newCTokenAddress
);
}
/**
@notice Tests whether amount exceeds the current maximum loan amount for a specific asset settings.
@param assetAddress asset address to test the setting.
@param amount amount to test.
@return true if amount exceeds current max loan amout. Otherwise it returns false.
*/
function exceedsMaxLoanAmount(address assetAddress, uint256 amount)
external
view
returns (bool)
{
return assetSettings[assetAddress].exceedsMaxLoanAmount(amount);
}
/**
@notice Gets the current asset addresses list.
@return the asset addresses list.
*/
function getAssets() external view returns (address[] memory) {
return assets;
}
/**
@notice Get the current asset settings for a given asset address.
@param assetAddress asset address used to get the current settings.
@return the current asset settings.
*/
function getAssetSettings(address assetAddress)
external
view
returns (AssetSettingsLib.AssetSettings memory)
{
return assetSettings[assetAddress];
}
/**
@notice Tests whether an account has the pauser role.
@param account account to test.
@return true if account has the pauser role. Otherwise it returns false.
*/
function hasPauserRole(address account) public view returns (bool) {
return isPauser(account);
}
/**
@notice Requires an account to have the pauser role.
@param account account to test.
*/
function requirePauserRole(address account) public view {
require(hasPauserRole(account), "NOT_PAUSER");
}
/**
@notice It initializes this settings contract instance.
@param escrowFactoryAddress the initial escrow factory address.
@param versionsRegistryAddress the initial versions registry address.
@param pairAggregatorRegistryAddress the initial pair aggregator registry address.
@param marketsStateAddress the initial markets state address.
@param interestValidatorAddress the initial interest validator address.
@param atmSettingsAddress the initial ATM settings address.
*/
function initialize(
address escrowFactoryAddress,
address versionsRegistryAddress,
address pairAggregatorRegistryAddress,
address marketsStateAddress,
address interestValidatorAddress,
address atmSettingsAddress
) external isNotInitialized() {
require(escrowFactoryAddress.isContract(), "ESCROW_FACTORY_MUST_BE_CONTRACT");
require(versionsRegistryAddress.isContract(), "VERS_REGISTRY_MUST_BE_CONTRACT");
require(
pairAggregatorRegistryAddress.isContract(),
"AGGR_REGISTRY_MUST_BE_CONTRACT"
);
require(marketsStateAddress.isContract(), "MARKETS_STATE_MUST_BE_CONTRACT");
require(
interestValidatorAddress.isEmpty() || interestValidatorAddress.isContract(),
"INTEREST_VAL_MUST_BE_CONTRACT"
);
require(atmSettingsAddress.isContract(), "ATM_SETTINGS_MUST_BE_CONTRACT");
Pausable.initialize(msg.sender);
TInitializable._initialize();
escrowFactory = EscrowFactoryInterface(escrowFactoryAddress);
versionsRegistry = LogicVersionsRegistryInterface(versionsRegistryAddress);
pairAggregatorRegistry = IChainlinkPairAggregatorRegistry(
pairAggregatorRegistryAddress
);
marketsState = MarketsStateInterface(marketsStateAddress);
interestValidator = InterestValidatorInterface(interestValidatorAddress);
atmSettings = IATMSettings(atmSettingsAddress);
_setSettings(address(this));
}
/** Internal functions */
/**
@notice It gets the platform setting for a given setting name.
@param settingName the setting name to look for.
@return the current platform setting for the given setting name.
*/
function _getPlatformSetting(bytes32 settingName)
internal
view
returns (PlatformSettingsLib.PlatformSetting memory)
{
return platformSettings[settingName];
}
/** Private functions */
}
| contract Settings is SettingsInterface, TInitializable, Pausable, BaseUpgradeable {
using AddressLib for address;
using Address for address;
using AssetSettingsLib for AssetSettingsLib.AssetSettings;
using AddressArrayLib for address[];
using PlatformSettingsLib for PlatformSettingsLib.PlatformSetting;
/** Constants */
/**
@notice The asset setting name for the maximum loan amount settings.
*/
bytes32 public constant MAX_LOAN_AMOUNT_ASSET_SETTING = "MaxLoanAmount";
/**
@notice The asset setting name for cToken address settings.
*/
bytes32 public constant CTOKEN_ADDRESS_ASSET_SETTING = "CTokenAddress";
/**
@notice It defines the constant address to represent ETHER.
*/
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/* State Variables */
/**
@notice It represents a mapping to identify the lending pools paused and not paused.
i.e.: address(lending pool) => true or false.
*/
mapping(address => bool) public lendingPoolPaused;
/**
@notice It represents a mapping to configure the asset settings.
@notice The key belongs to the asset address. Example: address(DAI) or address(USDC).
@notice The value has the asset settings.
Examples:
address(DAI) => {
cTokenAddress = 0x1234...890
maxLoanAmount = 1000 DAI (max)
}
address(USDC) => {
cTokenAddress = 0x2345...901
maxLoanAmount = 500 USDC (max)
}
*/
mapping(address => AssetSettingsLib.AssetSettings) public assetSettings;
/**
@notice It contains all the current assets.
*/
address[] public assets;
/**
@notice This mapping represents the platform settings where:
- The key is the platform setting name.
- The value is the platform setting. It includes the value, minimum and maximum values.
*/
mapping(bytes32 => PlatformSettingsLib.PlatformSetting) public platformSettings;
/**
@notice It is the global instance of the EscrowFactory contract.
*/
EscrowFactoryInterface public escrowFactory;
/**
@notice It is the global instance of the logic versions registry contract.
*/
LogicVersionsRegistryInterface public versionsRegistry;
/**
@notice It is the global instance of the ChainlinkPairAggregatorRegistry contract.
*/
IChainlinkPairAggregatorRegistry public pairAggregatorRegistry;
/**
@notice The markets state.
*/
MarketsStateInterface public marketsState;
/**
@notice The current interest validator.
*/
InterestValidatorInterface public interestValidator;
/**
@notice The current ATM settings.
*/
IATMSettings public atmSettings;
/** Modifiers */
/* Constructor */
/** External Functions */
/**
@notice It creates a new platform setting given a setting name, value, min and max values.
@param settingName setting name to create.
@param value the initial value for the given setting name.
@param minValue the min value for the setting.
@param maxValue the max value for the setting.
*/
function createPlatformSetting(
bytes32 settingName,
uint256 value,
uint256 minValue,
uint256 maxValue
) external onlyPauser() isInitialized() {
require(settingName != "", "SETTING_NAME_MUST_BE_PROVIDED");
platformSettings[settingName].initialize(value, minValue, maxValue);
emit PlatformSettingCreated(settingName, msg.sender, value, minValue, maxValue);
}
/**
@notice It updates an existent platform setting given a setting name.
@notice It only allows to update the value (not the min or max values).
@notice In case you need to update the min or max values, you need to remove it, and create it again.
@param settingName setting name to update.
@param newValue the new value to set.
*/
function updatePlatformSetting(bytes32 settingName, uint256 newValue)
external
onlyPauser()
isInitialized()
{
uint256 oldValue = platformSettings[settingName].update(newValue);
emit PlatformSettingUpdated(settingName, msg.sender, oldValue, newValue);
}
/**
@notice Removes a current platform setting given a setting name.
@param settingName to remove.
*/
function removePlatformSetting(bytes32 settingName)
external
onlyPauser()
isInitialized()
{
uint256 oldValue = platformSettings[settingName].value;
platformSettings[settingName].remove();
emit PlatformSettingRemoved(settingName, oldValue, msg.sender);
}
/**
@notice It gets the current platform setting for a given setting name
@param settingName to get.
@return the current platform setting.
*/
function getPlatformSetting(bytes32 settingName)
external
view
returns (PlatformSettingsLib.PlatformSetting memory)
{
return _getPlatformSetting(settingName);
}
/**
@notice It gets the current platform setting value for a given setting name
@param settingName to get.
@return the current platform setting value.
*/
function getPlatformSettingValue(bytes32 settingName)
external
view
returns (uint256)
{
return _getPlatformSetting(settingName).value;
}
/**
@notice It tests whether a setting name is already configured.
@param settingName setting name to test.
@return true if the setting is already configured. Otherwise it returns false.
*/
function hasPlatformSetting(bytes32 settingName) external view returns (bool) {
return _getPlatformSetting(settingName).exists;
}
/**
@notice It pauses a specific lending pool.
@param lendingPoolAddress lending pool address to pause.
*/
function pauseLendingPool(address lendingPoolAddress)
external
onlyPauser()
whenNotPaused()
isInitialized()
{
lendingPoolAddress.requireNotEmpty("LENDING_POOL_IS_REQUIRED");
require(!lendingPoolPaused[lendingPoolAddress], "LENDING_POOL_ALREADY_PAUSED");
lendingPoolPaused[lendingPoolAddress] = true;
emit LendingPoolPaused(msg.sender, lendingPoolAddress);
}
/**
@notice It unpauses a specific lending pool.
@param lendingPoolAddress lending pool address to unpause.
*/
function unpauseLendingPool(address lendingPoolAddress)
external
onlyPauser()
whenNotPaused()
isInitialized()
{
lendingPoolAddress.requireNotEmpty("LENDING_POOL_IS_REQUIRED");
require(lendingPoolPaused[lendingPoolAddress], "LENDING_POOL_IS_NOT_PAUSED");
lendingPoolPaused[lendingPoolAddress] = false;
emit LendingPoolUnpaused(msg.sender, lendingPoolAddress);
}
/**
@notice It gets whether the platform is paused or not.
@return true if platform is paused. Otherwise it returns false.
*/
function isPaused() external view returns (bool) {
return paused();
}
/**
@notice It creates a new asset settings in the platform.
@param assetAddress asset address used to create the new setting.
@param cTokenAddress cToken address used to configure the asset setting.
@param maxLoanAmount the max loan amount used to configure the asset setting.
*/
function createAssetSettings(
address assetAddress,
address cTokenAddress,
uint256 maxLoanAmount
) external onlyPauser() isInitialized() {
require(assetAddress.isContract(), "ASSET_ADDRESS_MUST_BE_CONTRACT");
assetSettings[assetAddress].requireNotExists();
assetSettings[assetAddress].initialize(cTokenAddress, maxLoanAmount);
assets.add(assetAddress);
emit AssetSettingsCreated(msg.sender, assetAddress, cTokenAddress, maxLoanAmount);
}
/**
@notice It removes all the asset settings for a specific asset address.
@param assetAddress asset address used to remove the asset settings.
*/
function removeAssetSettings(address assetAddress)
external
onlyPauser()
isInitialized()
{
assetAddress.requireNotEmpty("ASSET_ADDRESS_IS_REQUIRED");
assetSettings[assetAddress].requireExists();
delete assetSettings[assetAddress];
assets.remove(assetAddress);
emit AssetSettingsRemoved(msg.sender, assetAddress);
}
/**
@notice It updates the maximum loan amount for a specific asset address.
@param assetAddress asset address to configure.
@param newMaxLoanAmount the new maximum loan amount to configure.
*/
function updateMaxLoanAmount(address assetAddress, uint256 newMaxLoanAmount)
external
onlyPauser()
isInitialized()
{
uint256 oldMaxLoanAmount = assetSettings[assetAddress].maxLoanAmount;
assetSettings[assetAddress].updateMaxLoanAmount(newMaxLoanAmount);
emit AssetSettingsUintUpdated(
MAX_LOAN_AMOUNT_ASSET_SETTING,
msg.sender,
assetAddress,
oldMaxLoanAmount,
newMaxLoanAmount
);
}
/**
@notice It updates the cToken address for a specific asset address.
@param assetAddress asset address to configure.
@param newCTokenAddress the new cToken address to configure.
*/
function updateCTokenAddress(address assetAddress, address newCTokenAddress)
external
onlyPauser()
isInitialized()
{
address oldCTokenAddress = assetSettings[assetAddress].cTokenAddress;
assetSettings[assetAddress].updateCTokenAddress(newCTokenAddress);
emit AssetSettingsAddressUpdated(
CTOKEN_ADDRESS_ASSET_SETTING,
msg.sender,
assetAddress,
oldCTokenAddress,
newCTokenAddress
);
}
/**
@notice Tests whether amount exceeds the current maximum loan amount for a specific asset settings.
@param assetAddress asset address to test the setting.
@param amount amount to test.
@return true if amount exceeds current max loan amout. Otherwise it returns false.
*/
function exceedsMaxLoanAmount(address assetAddress, uint256 amount)
external
view
returns (bool)
{
return assetSettings[assetAddress].exceedsMaxLoanAmount(amount);
}
/**
@notice Gets the current asset addresses list.
@return the asset addresses list.
*/
function getAssets() external view returns (address[] memory) {
return assets;
}
/**
@notice Get the current asset settings for a given asset address.
@param assetAddress asset address used to get the current settings.
@return the current asset settings.
*/
function getAssetSettings(address assetAddress)
external
view
returns (AssetSettingsLib.AssetSettings memory)
{
return assetSettings[assetAddress];
}
/**
@notice Tests whether an account has the pauser role.
@param account account to test.
@return true if account has the pauser role. Otherwise it returns false.
*/
function hasPauserRole(address account) public view returns (bool) {
return isPauser(account);
}
/**
@notice Requires an account to have the pauser role.
@param account account to test.
*/
function requirePauserRole(address account) public view {
require(hasPauserRole(account), "NOT_PAUSER");
}
/**
@notice It initializes this settings contract instance.
@param escrowFactoryAddress the initial escrow factory address.
@param versionsRegistryAddress the initial versions registry address.
@param pairAggregatorRegistryAddress the initial pair aggregator registry address.
@param marketsStateAddress the initial markets state address.
@param interestValidatorAddress the initial interest validator address.
@param atmSettingsAddress the initial ATM settings address.
*/
function initialize(
address escrowFactoryAddress,
address versionsRegistryAddress,
address pairAggregatorRegistryAddress,
address marketsStateAddress,
address interestValidatorAddress,
address atmSettingsAddress
) external isNotInitialized() {
require(escrowFactoryAddress.isContract(), "ESCROW_FACTORY_MUST_BE_CONTRACT");
require(versionsRegistryAddress.isContract(), "VERS_REGISTRY_MUST_BE_CONTRACT");
require(
pairAggregatorRegistryAddress.isContract(),
"AGGR_REGISTRY_MUST_BE_CONTRACT"
);
require(marketsStateAddress.isContract(), "MARKETS_STATE_MUST_BE_CONTRACT");
require(
interestValidatorAddress.isEmpty() || interestValidatorAddress.isContract(),
"INTEREST_VAL_MUST_BE_CONTRACT"
);
require(atmSettingsAddress.isContract(), "ATM_SETTINGS_MUST_BE_CONTRACT");
Pausable.initialize(msg.sender);
TInitializable._initialize();
escrowFactory = EscrowFactoryInterface(escrowFactoryAddress);
versionsRegistry = LogicVersionsRegistryInterface(versionsRegistryAddress);
pairAggregatorRegistry = IChainlinkPairAggregatorRegistry(
pairAggregatorRegistryAddress
);
marketsState = MarketsStateInterface(marketsStateAddress);
interestValidator = InterestValidatorInterface(interestValidatorAddress);
atmSettings = IATMSettings(atmSettingsAddress);
_setSettings(address(this));
}
/** Internal functions */
/**
@notice It gets the platform setting for a given setting name.
@param settingName the setting name to look for.
@return the current platform setting for the given setting name.
*/
function _getPlatformSetting(bytes32 settingName)
internal
view
returns (PlatformSettingsLib.PlatformSetting memory)
{
return platformSettings[settingName];
}
/** Private functions */
}
| 11,664 |
148 | // Adds a key-value pair to a map, or updates the value for an existingkey. O(1). Returns true if the key was added to the map, that is if it was notalready present. / | function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
| function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
| 6,973 |
85 | // So indexers can keep track of this | event Harvested(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding
);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
| event Harvested(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding
);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
| 13,541 |
30 | // EternalStorageProxy This proxy holds the storage of the token contract and delegates every call to the current implementation set.Besides, it allows to upgrade the token's behaviour towards further implementations, and provides basicauthorization control functionalities / | contract EternalStorageProxy is EternalStorage, OwnedUpgradeabilityProxy {}
// File: contracts/DetailedToken.sol
contract DetailedToken{
string public name;
string public symbol;
uint8 public decimals;
}
| contract EternalStorageProxy is EternalStorage, OwnedUpgradeabilityProxy {}
// File: contracts/DetailedToken.sol
contract DetailedToken{
string public name;
string public symbol;
uint8 public decimals;
}
| 66,458 |
5 | // Create a new instance of an app linked to this kernelCreate a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`_appId Identifier for app_appBase Address of the app's base implementation return AppProxy instance/ | function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
| function newAppInstance(bytes32 _appId, address _appBase)
public
auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId))
returns (ERCProxy appProxy)
| 23,308 |
50 | // Fiefdoms/steviep.eth, julien.eth/ERC721 collection contract where ownership of a token grants the tooken holder ownership over a Fiefdom contract | contract Fiefdoms is ERC721, Ownable {
/// @notice License of Fiefdoms parent project - Does not pertain to the license of any tokens minted by Fiefdom contracts
string public license = 'CC0';
/// @notice Address that is permissioned to mint new tokens
address public minter;
/// @notice Address of the default tokenURI contract used by fiefdoms for mint 0
address public fiefdomArchetype;
/// @notice Address of the default tokenURI contract used by fiefdoms for mint 0
address public defaultTokenURIContract;
/// @notice True when only operators on the allow list may be approved
bool public useOperatorAllowList = true;
/// @notice Max supply of collection
uint256 public constant maxSupply = 721;
/// @notice Mapping from vassal's token id to fiefdom address
mapping(uint256 => address) public tokenIdToFiefdom;
/// @notice Allow lise of all operators allowed t
mapping(address => bool) public operatorAllowList;
BaseTokenURI private _tokenURIContract;
uint256 private _totalSupply = 1;
address private _royaltyBeneficiary;
uint16 private _royaltyBasisPoints = 1000;
/// @notice Arbitrary event emitted by contract owner
/// @param poster Address of initiator
/// @param eventType Type of event
/// @param content Content of event
event ProjectEvent(address indexed poster, string indexed eventType, string content);
/// @notice Arbitrary event related to a specific token emitted by contract owner or token holder
/// @param poster Address of initiator
/// @param tokenId ID of token
/// @param eventType Type of event
/// @param content Content of event
event TokenEvent(address indexed poster, uint256 indexed tokenId, string indexed eventType, string content);
/// @notice Emitted when a range of tokens has their metadata updated
/// @param _fromTokenId The first ID of the token in the range
/// @param _toTokenId The last ID of the token in the range
/// @dev See EIP-4906: https://eips.ethereum.org/EIPS/eip-4906
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
/// @notice Emitted when a token's metadata is updated
/// @param _tokenId The ID of the updated token
/// @dev See EIP-4906: https://eips.ethereum.org/EIPS/eip-4906
event MetadataUpdate(uint256 _tokenId);
/// @notice Emitted when a fiefdom is first activated
/// @param fiefdom The ID of the fiefdom being activated
event Activation(uint256 fiefdom);
// SETUP
/// @dev Sets base variables, mints token #0 to the deployer, and publishes the FiefdomArchetype contract
constructor() ERC721('Fiefdoms', 'FIEF') {
minter = msg.sender;
_royaltyBeneficiary = msg.sender;
_tokenURIContract = new BaseTokenURI();
defaultTokenURIContract = address(new DefaultTokenURI());
// Publish an archetype contract. All proxy contracts will derive its functionality from this
fiefdomArchetype = address(new FiefdomArchetype());
// Token 0 will use the archetype contract directly instead of a proxy
_mint(msg.sender, 0);
tokenIdToFiefdom[0] = fiefdomArchetype;
}
// BASE FUNCTIONALITY
/// @notice Current total supply of collection
/// @return Total supply
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/// @notice Checks if given token ID exists
/// @param tokenId Token to run existence check on
/// @return True if token exists
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
/// @notice Alias of Fiefdoms contract owner
function overlord() external view returns (address) {
return owner();
}
/// @dev Override's the default _transfer function to also transfer ownership over the corresponding fiefdom
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
// When this token is transferred, also transfer ownership over its fiefdom
FiefdomArchetype(tokenIdToFiefdom[tokenId]).transferOwnership(from, to);
return super._transfer(from, to, tokenId);
}
/// @notice Emits Activation and MetadataUpdate events upon fiefdom activation
/// @param tokenId Token Id of fiefdom being activated
/// @dev This can only be called by the fiefdom upon its activation
function activation(uint256 tokenId) external {
require(tokenIdToFiefdom[tokenId] == msg.sender);
emit MetadataUpdate(tokenId);
emit Activation(tokenId);
}
// MINTING
/// @notice Mints a new token
/// @param to Address to receive new token
function mint(address to) external {
require(minter == msg.sender, 'Caller is not the minting address');
require(_totalSupply < maxSupply, 'Cannot create more fiefdoms');
_mint(to, _totalSupply);
// Publish a new proxy contract for this token
FiefdomProxy proxy = new FiefdomProxy();
tokenIdToFiefdom[_totalSupply] = address(proxy);
_totalSupply += 1;
}
/// @notice Mints a batch of new tokens to a single address
/// @param to Address to receive all new tokens
/// @param amount Amount of tokens to mint
function mintBatch(address to, uint256 amount) external {
require(minter == msg.sender, 'Caller is not the minting address');
require(_totalSupply + amount <= maxSupply, 'Cannot create more fiefdoms');
for (uint256 i; i < amount; i++) {
_mint(to, _totalSupply);
FiefdomProxy proxy = new FiefdomProxy();
tokenIdToFiefdom[_totalSupply] = address(proxy);
_totalSupply++;
}
}
/// @notice Reassigns the minter permission
/// @param newMinter Address of new minter
function setMinter(address newMinter) external onlyOwner {
minter = newMinter;
}
// ROYALTIES
// Fiefdoms may collect their own royalties without restriction, but must follow the rules of the broader kingdom
/// @notice Override the standard approve function to revert if approving an un-ALed operator
/// @param to Address of operator
/// @param tokenId Id of token to approve
function approve(address to, uint256 tokenId) public virtual override {
if (useOperatorAllowList) require(operatorAllowList[to], 'Operator must be on Allow List');
super.approve(to, tokenId);
}
/// @notice Override the standard setApprovalForAll function to revert if approving an un-ALed operator
/// @param operator Address of operator
/// @param approved Approval status of operator
function setApprovalForAll(address operator, bool approved) public virtual override {
if (useOperatorAllowList && approved) require(operatorAllowList[operator], 'Operator must be on Allow List');
super.setApprovalForAll(operator, approved);
}
/// @notice Override the standard getApproved function to return false for un-ALed operators
/// @param tokenId Id of token
function getApproved(uint256 tokenId) public view virtual override returns (address) {
address operator = super.getApproved(tokenId);
if (useOperatorAllowList) {
return operatorAllowList[operator] ? operator : address(0);
} else {
return operator;
}
}
/// @notice Override the standard isApprovedForAll function to return false for un-ALed operators
/// @param owner Address of owner
/// @param operator Address of operator
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
if (useOperatorAllowList && !operatorAllowList[operator]) {
return false;
} else {
return super.isApprovedForAll(owner, operator);
}
}
/// @notice Denotes whether an operator allow list should be used
/// @param _useOperatorAllowList New useOperatorAllowList value
function updateUseOperatorAllowList(bool _useOperatorAllowList) external onlyOwner {
useOperatorAllowList = _useOperatorAllowList;
}
/// @notice Update the allow list status of a single operator
/// @param operator Address of operator
/// @param allowListStatus New allow list status
function updateOperatorAllowList(address operator, bool allowListStatus) external onlyOwner {
operatorAllowList[operator] = allowListStatus;
}
/// @notice Sets royalty info for the collection
/// @param royaltyBeneficiary Address to receive royalties
/// @param royaltyBasisPoints Basis points of royalty commission
/// @dev See EIP-2981: https://eips.ethereum.org/EIPS/eip-2981
function setRoyaltyInfo(
address royaltyBeneficiary,
uint16 royaltyBasisPoints
) external onlyOwner {
_royaltyBeneficiary = royaltyBeneficiary;
_royaltyBasisPoints = royaltyBasisPoints;
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param (unused)
/// @param _salePrice The sale price of the NFT asset specified by _tokenId
/// @return receiver Address of who should be sent the royalty payment
/// @return royaltyAmount The royalty payment amount for _salePrice
/// @dev See EIP-2981: https://eips.ethereum.org/EIPS/eip-2981
function royaltyInfo(uint256, uint256 _salePrice) external view returns (address, uint256) {
return (_royaltyBeneficiary, _salePrice * _royaltyBasisPoints / 10000);
}
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @return `true` if the contract implements `interfaceId` and
/// `interfaceId` is not 0xffffffff, `false` otherwise
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas. See: https://eips.ethereum.org/EIPS/eip-165
/// See EIP-2981: https://eips.ethereum.org/EIPS/eip-2981
/// See EIP-4906: https://eips.ethereum.org/EIPS/eip-4906
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) {
// ERC2981 & ERC4906
return interfaceId == bytes4(0x2a55205a) || interfaceId == bytes4(0x49064906) || super.supportsInterface(interfaceId);
}
// TOKEN URI
/// @notice Token URI
/// @param tokenId Token ID to look up URI of
/// @return Token URI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
return _tokenURIContract.tokenURI(tokenId);
}
/// @notice Set the Token URI contract for Vassal tokens
/// @param _tokenURIAddress New address of Token URI contract
function setTokenURIContract(address _tokenURIAddress) external onlyOwner {
_tokenURIContract = BaseTokenURI(_tokenURIAddress);
emit BatchMetadataUpdate(0, _totalSupply);
}
/// @notice Set the default Token URI contract for all Fiefdoms in the Kingdom
/// @param newDefault Address of the new default Token URI contract
function setDefaultTokenURIContract(address newDefault) external onlyOwner {
defaultTokenURIContract = newDefault;
}
/// @notice Address of Token URI contract
/// @return Address of the Token URI contract
function tokenURIContract() external view returns (address) {
return address(_tokenURIContract);
}
// EVENTS
/// @notice Emit an arbitrary event related to a token
/// @param tokenId ID of the token this event is related to
/// @param eventType Type of event to emit
/// @param content Text to be included in event
/// @dev Can be called either by contract owner or token holder
function emitTokenEvent(uint256 tokenId, string calldata eventType, string calldata content) external {
require(
owner() == msg.sender || ERC721.ownerOf(tokenId) == msg.sender,
'Only project or token owner can emit token event'
);
emit TokenEvent(msg.sender, tokenId, eventType, content);
}
/// @notice Emit an arbitrary event related to the project
/// @param eventType Type of event to emit
/// @param content Text to be included in event
/// @dev Can only be called either by contract owner
function emitProjectEvent(string calldata eventType, string calldata content) external onlyOwner {
emit ProjectEvent(msg.sender, eventType, content);
}
}
| contract Fiefdoms is ERC721, Ownable {
/// @notice License of Fiefdoms parent project - Does not pertain to the license of any tokens minted by Fiefdom contracts
string public license = 'CC0';
/// @notice Address that is permissioned to mint new tokens
address public minter;
/// @notice Address of the default tokenURI contract used by fiefdoms for mint 0
address public fiefdomArchetype;
/// @notice Address of the default tokenURI contract used by fiefdoms for mint 0
address public defaultTokenURIContract;
/// @notice True when only operators on the allow list may be approved
bool public useOperatorAllowList = true;
/// @notice Max supply of collection
uint256 public constant maxSupply = 721;
/// @notice Mapping from vassal's token id to fiefdom address
mapping(uint256 => address) public tokenIdToFiefdom;
/// @notice Allow lise of all operators allowed t
mapping(address => bool) public operatorAllowList;
BaseTokenURI private _tokenURIContract;
uint256 private _totalSupply = 1;
address private _royaltyBeneficiary;
uint16 private _royaltyBasisPoints = 1000;
/// @notice Arbitrary event emitted by contract owner
/// @param poster Address of initiator
/// @param eventType Type of event
/// @param content Content of event
event ProjectEvent(address indexed poster, string indexed eventType, string content);
/// @notice Arbitrary event related to a specific token emitted by contract owner or token holder
/// @param poster Address of initiator
/// @param tokenId ID of token
/// @param eventType Type of event
/// @param content Content of event
event TokenEvent(address indexed poster, uint256 indexed tokenId, string indexed eventType, string content);
/// @notice Emitted when a range of tokens has their metadata updated
/// @param _fromTokenId The first ID of the token in the range
/// @param _toTokenId The last ID of the token in the range
/// @dev See EIP-4906: https://eips.ethereum.org/EIPS/eip-4906
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
/// @notice Emitted when a token's metadata is updated
/// @param _tokenId The ID of the updated token
/// @dev See EIP-4906: https://eips.ethereum.org/EIPS/eip-4906
event MetadataUpdate(uint256 _tokenId);
/// @notice Emitted when a fiefdom is first activated
/// @param fiefdom The ID of the fiefdom being activated
event Activation(uint256 fiefdom);
// SETUP
/// @dev Sets base variables, mints token #0 to the deployer, and publishes the FiefdomArchetype contract
constructor() ERC721('Fiefdoms', 'FIEF') {
minter = msg.sender;
_royaltyBeneficiary = msg.sender;
_tokenURIContract = new BaseTokenURI();
defaultTokenURIContract = address(new DefaultTokenURI());
// Publish an archetype contract. All proxy contracts will derive its functionality from this
fiefdomArchetype = address(new FiefdomArchetype());
// Token 0 will use the archetype contract directly instead of a proxy
_mint(msg.sender, 0);
tokenIdToFiefdom[0] = fiefdomArchetype;
}
// BASE FUNCTIONALITY
/// @notice Current total supply of collection
/// @return Total supply
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/// @notice Checks if given token ID exists
/// @param tokenId Token to run existence check on
/// @return True if token exists
function exists(uint256 tokenId) external view returns (bool) {
return _exists(tokenId);
}
/// @notice Alias of Fiefdoms contract owner
function overlord() external view returns (address) {
return owner();
}
/// @dev Override's the default _transfer function to also transfer ownership over the corresponding fiefdom
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
// When this token is transferred, also transfer ownership over its fiefdom
FiefdomArchetype(tokenIdToFiefdom[tokenId]).transferOwnership(from, to);
return super._transfer(from, to, tokenId);
}
/// @notice Emits Activation and MetadataUpdate events upon fiefdom activation
/// @param tokenId Token Id of fiefdom being activated
/// @dev This can only be called by the fiefdom upon its activation
function activation(uint256 tokenId) external {
require(tokenIdToFiefdom[tokenId] == msg.sender);
emit MetadataUpdate(tokenId);
emit Activation(tokenId);
}
// MINTING
/// @notice Mints a new token
/// @param to Address to receive new token
function mint(address to) external {
require(minter == msg.sender, 'Caller is not the minting address');
require(_totalSupply < maxSupply, 'Cannot create more fiefdoms');
_mint(to, _totalSupply);
// Publish a new proxy contract for this token
FiefdomProxy proxy = new FiefdomProxy();
tokenIdToFiefdom[_totalSupply] = address(proxy);
_totalSupply += 1;
}
/// @notice Mints a batch of new tokens to a single address
/// @param to Address to receive all new tokens
/// @param amount Amount of tokens to mint
function mintBatch(address to, uint256 amount) external {
require(minter == msg.sender, 'Caller is not the minting address');
require(_totalSupply + amount <= maxSupply, 'Cannot create more fiefdoms');
for (uint256 i; i < amount; i++) {
_mint(to, _totalSupply);
FiefdomProxy proxy = new FiefdomProxy();
tokenIdToFiefdom[_totalSupply] = address(proxy);
_totalSupply++;
}
}
/// @notice Reassigns the minter permission
/// @param newMinter Address of new minter
function setMinter(address newMinter) external onlyOwner {
minter = newMinter;
}
// ROYALTIES
// Fiefdoms may collect their own royalties without restriction, but must follow the rules of the broader kingdom
/// @notice Override the standard approve function to revert if approving an un-ALed operator
/// @param to Address of operator
/// @param tokenId Id of token to approve
function approve(address to, uint256 tokenId) public virtual override {
if (useOperatorAllowList) require(operatorAllowList[to], 'Operator must be on Allow List');
super.approve(to, tokenId);
}
/// @notice Override the standard setApprovalForAll function to revert if approving an un-ALed operator
/// @param operator Address of operator
/// @param approved Approval status of operator
function setApprovalForAll(address operator, bool approved) public virtual override {
if (useOperatorAllowList && approved) require(operatorAllowList[operator], 'Operator must be on Allow List');
super.setApprovalForAll(operator, approved);
}
/// @notice Override the standard getApproved function to return false for un-ALed operators
/// @param tokenId Id of token
function getApproved(uint256 tokenId) public view virtual override returns (address) {
address operator = super.getApproved(tokenId);
if (useOperatorAllowList) {
return operatorAllowList[operator] ? operator : address(0);
} else {
return operator;
}
}
/// @notice Override the standard isApprovedForAll function to return false for un-ALed operators
/// @param owner Address of owner
/// @param operator Address of operator
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
if (useOperatorAllowList && !operatorAllowList[operator]) {
return false;
} else {
return super.isApprovedForAll(owner, operator);
}
}
/// @notice Denotes whether an operator allow list should be used
/// @param _useOperatorAllowList New useOperatorAllowList value
function updateUseOperatorAllowList(bool _useOperatorAllowList) external onlyOwner {
useOperatorAllowList = _useOperatorAllowList;
}
/// @notice Update the allow list status of a single operator
/// @param operator Address of operator
/// @param allowListStatus New allow list status
function updateOperatorAllowList(address operator, bool allowListStatus) external onlyOwner {
operatorAllowList[operator] = allowListStatus;
}
/// @notice Sets royalty info for the collection
/// @param royaltyBeneficiary Address to receive royalties
/// @param royaltyBasisPoints Basis points of royalty commission
/// @dev See EIP-2981: https://eips.ethereum.org/EIPS/eip-2981
function setRoyaltyInfo(
address royaltyBeneficiary,
uint16 royaltyBasisPoints
) external onlyOwner {
_royaltyBeneficiary = royaltyBeneficiary;
_royaltyBasisPoints = royaltyBasisPoints;
}
/// @notice Called with the sale price to determine how much royalty is owed and to whom.
/// @param (unused)
/// @param _salePrice The sale price of the NFT asset specified by _tokenId
/// @return receiver Address of who should be sent the royalty payment
/// @return royaltyAmount The royalty payment amount for _salePrice
/// @dev See EIP-2981: https://eips.ethereum.org/EIPS/eip-2981
function royaltyInfo(uint256, uint256 _salePrice) external view returns (address, uint256) {
return (_royaltyBeneficiary, _salePrice * _royaltyBasisPoints / 10000);
}
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @return `true` if the contract implements `interfaceId` and
/// `interfaceId` is not 0xffffffff, `false` otherwise
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas. See: https://eips.ethereum.org/EIPS/eip-165
/// See EIP-2981: https://eips.ethereum.org/EIPS/eip-2981
/// See EIP-4906: https://eips.ethereum.org/EIPS/eip-4906
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721) returns (bool) {
// ERC2981 & ERC4906
return interfaceId == bytes4(0x2a55205a) || interfaceId == bytes4(0x49064906) || super.supportsInterface(interfaceId);
}
// TOKEN URI
/// @notice Token URI
/// @param tokenId Token ID to look up URI of
/// @return Token URI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
return _tokenURIContract.tokenURI(tokenId);
}
/// @notice Set the Token URI contract for Vassal tokens
/// @param _tokenURIAddress New address of Token URI contract
function setTokenURIContract(address _tokenURIAddress) external onlyOwner {
_tokenURIContract = BaseTokenURI(_tokenURIAddress);
emit BatchMetadataUpdate(0, _totalSupply);
}
/// @notice Set the default Token URI contract for all Fiefdoms in the Kingdom
/// @param newDefault Address of the new default Token URI contract
function setDefaultTokenURIContract(address newDefault) external onlyOwner {
defaultTokenURIContract = newDefault;
}
/// @notice Address of Token URI contract
/// @return Address of the Token URI contract
function tokenURIContract() external view returns (address) {
return address(_tokenURIContract);
}
// EVENTS
/// @notice Emit an arbitrary event related to a token
/// @param tokenId ID of the token this event is related to
/// @param eventType Type of event to emit
/// @param content Text to be included in event
/// @dev Can be called either by contract owner or token holder
function emitTokenEvent(uint256 tokenId, string calldata eventType, string calldata content) external {
require(
owner() == msg.sender || ERC721.ownerOf(tokenId) == msg.sender,
'Only project or token owner can emit token event'
);
emit TokenEvent(msg.sender, tokenId, eventType, content);
}
/// @notice Emit an arbitrary event related to the project
/// @param eventType Type of event to emit
/// @param content Text to be included in event
/// @dev Can only be called either by contract owner
function emitProjectEvent(string calldata eventType, string calldata content) external onlyOwner {
emit ProjectEvent(msg.sender, eventType, content);
}
}
| 7,869 |
23 | // Changes Oracle variables. Admin role only. chainlinkToken_Address of Chainlink Token. oracle_Address of Oracle. jobId_Bytes32 representing Job ID. oraclePayment_Amount of LINK to be paid per request. / | function setupOracle(
address chainlinkToken_,
address oracle_,
bytes32 jobId_,
uint256 oraclePayment_
| function setupOracle(
address chainlinkToken_,
address oracle_,
bytes32 jobId_,
uint256 oraclePayment_
| 3,087 |
53 | // this function makes it so one can easily identify whether this contract has been deployed or not.deployment of this factory is done deterministically, so it will live at a well known address on every chain but the user may need to check whether or not this contract has been deployed yet on a given chain | function exists() public pure returns (bytes32) { //inject PUBLIC FUNC TO EXTERNAL
return 0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef;
}
| function exists() public pure returns (bytes32) { //inject PUBLIC FUNC TO EXTERNAL
return 0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef;
}
| 32,992 |
6 | // Claim rewards on behalf of a user and send them to a receiver Only callable by if sender is onBehalfOf or sender is approved claimer onBehalfOf The address to claim on behalf of receiver The address to receive the rewards forceUpdate Flag to retrieve latest rewards from `INCENTIVES_CONTROLLER` / | function claimRewardsOnBehalf(
| function claimRewardsOnBehalf(
| 9,171 |
20 | // Serializes a Token ID struct _tokenId The token id structreturn The formatted Token ID / | function formatTokenId(TokenId memory _tokenId)
internal
pure
returns (bytes29)
| function formatTokenId(TokenId memory _tokenId)
internal
pure
returns (bytes29)
| 33,509 |
52 | // Check that the target is a valid contract. | if (target.code.length == 0) {
revert PRBProxy__TargetInvalid(target);
}
| if (target.code.length == 0) {
revert PRBProxy__TargetInvalid(target);
}
| 21,697 |
16 | // Constant for locked guard state | uint private constant REENTRANCY_GUARD_LOCKED = 2;
| uint private constant REENTRANCY_GUARD_LOCKED = 2;
| 50,647 |
18 | // init | Bid storage bid = _bids[auctionId];
bid.auction.id = auctionId;
bid.auction.auctioneer = auctioneer;
bid.auction.startTime = startTime;
bid.auction.endTime = endTime;
bid.auction.reservePrice = reservePrice;
bid.symmetricKey = symmetricKey;
| Bid storage bid = _bids[auctionId];
bid.auction.id = auctionId;
bid.auction.auctioneer = auctioneer;
bid.auction.startTime = startTime;
bid.auction.endTime = endTime;
bid.auction.reservePrice = reservePrice;
bid.symmetricKey = symmetricKey;
| 25,058 |
63 | // Returns an array of currency codes currently accepted for deposits. / | function getAcceptedCurrencies() external view returns (string[] memory) {
uint256 arrayLength = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) arrayLength++;
string[] memory acceptedCurrencies = new string[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) {
acceptedCurrencies[index] = _supportedCurrencies[i];
index++;
}
return acceptedCurrencies;
}
| function getAcceptedCurrencies() external view returns (string[] memory) {
uint256 arrayLength = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) arrayLength++;
string[] memory acceptedCurrencies = new string[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) {
acceptedCurrencies[index] = _supportedCurrencies[i];
index++;
}
return acceptedCurrencies;
}
| 12,089 |
4 | // Minimum lock for each sponsor | uint64 public constant MIN_SPONSOR_LOCK_DURATION = 2 weeks;
| uint64 public constant MIN_SPONSOR_LOCK_DURATION = 2 weeks;
| 37,352 |
199 | // This event is emitted when overnight fee payed/blockNumber the block number when overnight Fee payed/longPositionsSize the long Position size when overnight Fee payed/shortPositionSize the short Position size when overnight Fee payed/overnightFee the total overinight fee this time | event OvernightFeePayed(
uint256 blockNumber,
uint256 longPositionsSize,
uint256 shortPositionSize,
uint256 overnightFee
);
| event OvernightFeePayed(
uint256 blockNumber,
uint256 longPositionsSize,
uint256 shortPositionSize,
uint256 overnightFee
);
| 36,009 |
67 | // Internal call to process wearer status from the eligibility module/Burns the wearer's Hat token if _eligible is false, and updates badStandings/ state if necessary/_hatId The id of the Hat to revoke/_wearer The address of the wearer in question/_eligible Whether _wearer is eligible for the Hat (if false, this function/ will revoke their Hat)/_standing Whether _wearer is in good standing (to be recorded in storage)/ return updated Whether the wearer standing was updated | function _processHatWearerStatus(uint256 _hatId, address _wearer, bool _eligible, bool _standing)
internal
returns (bool updated)
| function _processHatWearerStatus(uint256 _hatId, address _wearer, bool _eligible, bool _standing)
internal
returns (bool updated)
| 21,969 |
191 | // Recoverable feature should _only_ be used with contracts that should not store assets,but instead interacted with value so there is potential to lose assets. / | abstract contract Recoverable is AccessControl {
using SafeERC20 for IERC20;
using Address for address payable;
/* ========== CONSTANTS ========== */
bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE");
/* ============ Events ============ */
event Recovered(address onBehalfOf, address tokenAddress, uint256 amount);
/* ========== MODIFIERS ========== */
modifier isRecoverer {
require(hasRole(RECOVER_ROLE, _msgSender()), "Recoverable/RecoverRole");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- RECOVER_ROLE ----- */
/**
* @notice Provide accidental token retrieval.
* @dev Sourced from synthetix/contracts/StakingRewards.sol
*/
function recoverERC20(
address to,
address tokenAddress,
uint256 tokenAmount
) external isRecoverer {
emit Recovered(to, tokenAddress, tokenAmount);
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
}
/**
* @notice Provide accidental ETH retrieval.
*/
function recoverETH(address to) external isRecoverer {
uint256 contractBalance = address(this).balance;
emit Recovered(to, address(0), contractBalance);
payable(to).sendValue(contractBalance);
}
}
| abstract contract Recoverable is AccessControl {
using SafeERC20 for IERC20;
using Address for address payable;
/* ========== CONSTANTS ========== */
bytes32 public constant RECOVER_ROLE = keccak256("RECOVER_ROLE");
/* ============ Events ============ */
event Recovered(address onBehalfOf, address tokenAddress, uint256 amount);
/* ========== MODIFIERS ========== */
modifier isRecoverer {
require(hasRole(RECOVER_ROLE, _msgSender()), "Recoverable/RecoverRole");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/* ----- RECOVER_ROLE ----- */
/**
* @notice Provide accidental token retrieval.
* @dev Sourced from synthetix/contracts/StakingRewards.sol
*/
function recoverERC20(
address to,
address tokenAddress,
uint256 tokenAmount
) external isRecoverer {
emit Recovered(to, tokenAddress, tokenAmount);
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
}
/**
* @notice Provide accidental ETH retrieval.
*/
function recoverETH(address to) external isRecoverer {
uint256 contractBalance = address(this).balance;
emit Recovered(to, address(0), contractBalance);
payable(to).sendValue(contractBalance);
}
}
| 30,083 |
303 | // Lockup dates are the same end time, slope delta is the same | newSlopeDelta = oldSlopeDelta;
| newSlopeDelta = oldSlopeDelta;
| 16,765 |
21 | // Function called by `mintWhitelist` and `mint`./ Performs common checks and mints `amount` of NFTs./account The account to mint the NFTs to./amount The amount of NFTs to mint. | function _mintInternal(address account, uint256 amount) internal {
require(amount != 0, "INVALID_AMOUNT");
uint256 mintedWallet = mintedAmount[account] + amount;
require(mintedWallet <= MAX_PER_WALLET, "WALLET_LIMIT_EXCEEDED");
uint256 currentPointer = publicPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_PUBLIC, "SALE_LIMIT_EXCEEDED");
require(amount * MINT_PRICE == msg.value, "WRONG_ETH_VALUE");
publicPointer = newPointer;
mintedAmount[account] = mintedWallet;
for (uint256 i = 0; i < amount; i++) {
_safeMint(account, currentPointer + i);
}
}
| function _mintInternal(address account, uint256 amount) internal {
require(amount != 0, "INVALID_AMOUNT");
uint256 mintedWallet = mintedAmount[account] + amount;
require(mintedWallet <= MAX_PER_WALLET, "WALLET_LIMIT_EXCEEDED");
uint256 currentPointer = publicPointer;
uint256 newPointer = currentPointer + amount;
require(newPointer - 1 <= HIGHEST_PUBLIC, "SALE_LIMIT_EXCEEDED");
require(amount * MINT_PRICE == msg.value, "WRONG_ETH_VALUE");
publicPointer = newPointer;
mintedAmount[account] = mintedWallet;
for (uint256 i = 0; i < amount; i++) {
_safeMint(account, currentPointer + i);
}
}
| 53,887 |
538 | // Updates RGT distribution speeds for each pool given one `pool` whose balance should be refreshed. pool The pool whose balance should be refreshed. / | function refreshDistributionSpeeds(RariPool pool) external;
| function refreshDistributionSpeeds(RariPool pool) external;
| 28,845 |
1,036 | // 520 | entry "coercibly" : ENG_ADVERB
| entry "coercibly" : ENG_ADVERB
| 21,356 |
182 | // @custom:error (NX4) - Non-existent role to CA | require(roles[_CAs[i]][_role], 'NX4');
roles[_CAs[i]][_role] = false;
emit RoleRemoved(_CAs[i], _role);
| require(roles[_CAs[i]][_role], 'NX4');
roles[_CAs[i]][_role] = false;
emit RoleRemoved(_CAs[i], _role);
| 67,013 |
134 | // Determine whether the address is an already added address / | modifier onlyJoined(address addr) {
require(accounts[addr].id > 0, "ANR");
_;
}
| modifier onlyJoined(address addr) {
require(accounts[addr].id > 0, "ANR");
_;
}
| 61,092 |
358 | // CurrentCollateralizationRatio = deposited ETH in USD / debt in USD | uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt);
| uint256 collateralizationRatio = _collateralValue.wadDiv(_vaultDebt);
| 30,691 |
59 | // Rebased ERC20 token Rebased is based on the uFragments Ideal Money protocol. uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and combining tokens proportionally across all wallets.uFragment balances are internally represented with a hidden denomination, 'gons'. We support splitting the currency in expansion and combining the currency on contraction by changing the exchange rate between the hidden 'gons' and the public 'fragments'. / | contract Rebased is ERC20Detailed {
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 25 * 10**5 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Fragments, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
constructor(address _monetaryPolicy)
ERC20Detailed("Rebased", "REB", uint8(DECIMALS))
public
{
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[msg.sender] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
monetaryPolicy = _monetaryPolicy;
emit Transfer(address(0x0), msg.sender, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
external
override
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
override
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
override
validRecipient(to)
returns (bool)
{
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
override
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
override
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
override
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
} | contract Rebased is ERC20Detailed {
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 25 * 10**5 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Fragments, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
constructor(address _monetaryPolicy)
ERC20Detailed("Rebased", "REB", uint8(DECIMALS))
public
{
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[msg.sender] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
monetaryPolicy = _monetaryPolicy;
emit Transfer(address(0x0), msg.sender, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
external
override
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
override
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
override
validRecipient(to)
returns (bool)
{
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
override
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
override
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
override
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
} | 50,136 |
5 | // Check the proper ether is sent | require(msg.value == BET_AMOUNT, "Not enough ETH");
| require(msg.value == BET_AMOUNT, "Not enough ETH");
| 11,238 |
28 | // Increase the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by. / | function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
| function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
| 1,515 |
59 | // Tellor TransferContais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol reference this library for function's logic./ | library TellorTransfer {
| library TellorTransfer {
| 8,723 |
308 | // Auction contract checks input sizes If Dog is already on any auction, this will throw because it will be owned by the auction contract. | require(_owns(msg.sender, _dogId) || _approvedFor(msg.sender, _dogId));
| require(_owns(msg.sender, _dogId) || _approvedFor(msg.sender, _dogId));
| 15,250 |
27 | // change status of Request | accessControlRequests[id].status = AccessStatus.Verified;
| accessControlRequests[id].status = AccessStatus.Verified;
| 20,625 |
8 | // Bigger length than default | model.modelSetOutputLength(0xec5b4d3b, 96);
Assert.equal(int(model.modelGetOutputLength(0xec5b4d3b)), 96, "Length is now 44");
(mr0, mr1, mr2) = rawInput.solidityReturnBytes32(0x1111111111111111111111111111111111111111111111111111111111111111, 0x2222222222222222222222222222222222222222222222222222222222222222);
equal(mr0, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Length is 96");
equal(mr1, 0xec5b4d3b11111111111111111111111111111111111111111111111111111111, "Length is 96");
equal(mr2, 0x1111111122222222222222222222222222222222222222222222222222222222, "Length is 96");
equal(
callAndReturn(model, hex"ec5b4d3b11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222", 97),
hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec5b4d3b11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222200",
| model.modelSetOutputLength(0xec5b4d3b, 96);
Assert.equal(int(model.modelGetOutputLength(0xec5b4d3b)), 96, "Length is now 44");
(mr0, mr1, mr2) = rawInput.solidityReturnBytes32(0x1111111111111111111111111111111111111111111111111111111111111111, 0x2222222222222222222222222222222222222222222222222222222222222222);
equal(mr0, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Length is 96");
equal(mr1, 0xec5b4d3b11111111111111111111111111111111111111111111111111111111, "Length is 96");
equal(mr2, 0x1111111122222222222222222222222222222222222222222222222222222222, "Length is 96");
equal(
callAndReturn(model, hex"ec5b4d3b11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222", 97),
hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec5b4d3b11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222200",
| 2,052 |
55 | // 觸發事件:符合租客資格 | emit TenantQualified(
block.timestamp,
_tenantAddress,
_rentAmount,
_depositAmount
);
| emit TenantQualified(
block.timestamp,
_tenantAddress,
_rentAmount,
_depositAmount
);
| 20,070 |
120 | // Unrevelead URI. | string public unrevealedURI;
| string public unrevealedURI;
| 24,694 |
50 | // essentially the same as buy, but instead of you sending ether from your wallet, it uses your unwithdrawn earnings.-functionhash- 0x349cdcac (using ID for affiliate)-functionhash- 0x82bfc739 (using address for affiliate)-functionhash- 0x079ce327 (using name for affiliate) _affCode the ID/address/name of the player who gets the affiliate fee _team what team is the player playing for? _eth amount of earnings to use (remainder returned to gen vault) / | function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
| function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
| 7,631 |
9 | // Set [addresses] to be enabled on the precompile contract. | function setEnabled(address precompileContract, address[] calldata addresses) external onlyOwner {
validate(addresses);
uint index = 0;
for (index = 0; index < addresses.length; index++) {
IAllowList(precompileContract).setEnabled(addresses[index]);
}
}
| function setEnabled(address precompileContract, address[] calldata addresses) external onlyOwner {
validate(addresses);
uint index = 0;
for (index = 0; index < addresses.length; index++) {
IAllowList(precompileContract).setEnabled(addresses[index]);
}
}
| 16,343 |
38 | // 13 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT |
string inPI_edit_13 = " une première phrase " ;
|
string inPI_edit_13 = " une première phrase " ;
| 35,653 |
0 | // Guillaume Gonnaud 2019/Auction House Header/Contain all the events emitted by the Auction House | contract AuctionHouseHeaderV1 {
// Deposit: Event emitted whenever money is made available for withdrawal in the Auction House
// amount: Amount of money being deposited
// beneficiary: Account that will be able to withdraw the money
// contributor: Which user wallet initially contributed the received money
// origin: Which smart contract sent the money
event Deposit(uint256 indexed amount, address indexed beneficiary, address indexed contributor, address origin);
// Withdrawal: event emitted whenever a user withdraw his Eth on the auction house smart contract
// amount: total amount of money withdrawn
// account: address of user withdrawing his money
event UserWithdrawal(uint256 indexed amount, address indexed account);
// Bid: event emitted whenever a user submit a new bid to an auction
// auction: the address of the auction
// bidValue: the eth value of the new standing bid
// bidder: the address of the user who just bid
event UserBid(address indexed auction, uint256 indexed bidValue, address indexed bidder);
// CancelBid: event emitted whenever a user manually cancel a bid
// auction: the address of the auction
// bidder: the address of the user who just cancelled his bid
event UserCancelledBid(address indexed auction, address indexed bidder);
// Win: event emitted whenever a user win an auction
// auction: the address of the auction
// bidValue: the eth value of the winning bid
// bidder: the address of the user who just won the auction his bid
event UserWin(address indexed auction, uint256 indexed bidValue, address indexed bidder);
// UserSell: event emitted whenever a user trigger a sale at an auction
// auction: the address of the auction
event UserSell(address indexed auction);
// UserSellingPriceAdjust: event emitted whenever a user adjust the selling price of an auction
// auction: the address of the auction
// value : the new adjusted price. 0 for disabled
event UserSellingPriceAdjust(address indexed auction, uint256 indexed value);
}
| contract AuctionHouseHeaderV1 {
// Deposit: Event emitted whenever money is made available for withdrawal in the Auction House
// amount: Amount of money being deposited
// beneficiary: Account that will be able to withdraw the money
// contributor: Which user wallet initially contributed the received money
// origin: Which smart contract sent the money
event Deposit(uint256 indexed amount, address indexed beneficiary, address indexed contributor, address origin);
// Withdrawal: event emitted whenever a user withdraw his Eth on the auction house smart contract
// amount: total amount of money withdrawn
// account: address of user withdrawing his money
event UserWithdrawal(uint256 indexed amount, address indexed account);
// Bid: event emitted whenever a user submit a new bid to an auction
// auction: the address of the auction
// bidValue: the eth value of the new standing bid
// bidder: the address of the user who just bid
event UserBid(address indexed auction, uint256 indexed bidValue, address indexed bidder);
// CancelBid: event emitted whenever a user manually cancel a bid
// auction: the address of the auction
// bidder: the address of the user who just cancelled his bid
event UserCancelledBid(address indexed auction, address indexed bidder);
// Win: event emitted whenever a user win an auction
// auction: the address of the auction
// bidValue: the eth value of the winning bid
// bidder: the address of the user who just won the auction his bid
event UserWin(address indexed auction, uint256 indexed bidValue, address indexed bidder);
// UserSell: event emitted whenever a user trigger a sale at an auction
// auction: the address of the auction
event UserSell(address indexed auction);
// UserSellingPriceAdjust: event emitted whenever a user adjust the selling price of an auction
// auction: the address of the auction
// value : the new adjusted price. 0 for disabled
event UserSellingPriceAdjust(address indexed auction, uint256 indexed value);
}
| 11,497 |
19 | // Try to deal a new market order. 'sender' pays 'inAmount' of 'inputToken', in exchange of the other token kept by this pair | function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable returns (uint);
| function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable returns (uint);
| 940 |
44 | // Transfer tokens from the caller to a new holder. Remember, there&39;s a 1% fee here as well. / | function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// liquify 1% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
| function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) {
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if (myDividends(true) > 0) {
withdraw();
}
// liquify 1% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
| 19,832 |
54 | // Internal function to invoke `onERC721Received` on a target address The call is not executed if the target address is not a contract _from address representing the previous owner of the given token ID _to target address that will receive the tokens _tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the callreturn whether the call correctly returned the expected magic value / | function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
| function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
| 14,342 |
2 | // Map containing the token Holder adresses and their balances of issued tokens // Map containing users and their approval addresses and amounts // symbol for the contract // Constructor to create the token/ | function Token() public {
totalSupplyInt = 1000;
balances[msg.sender] = 1000;
symbol = "SAT";
}
| function Token() public {
totalSupplyInt = 1000;
balances[msg.sender] = 1000;
symbol = "SAT";
}
| 30,223 |
7 | // See {IERC_N-barter} | function barter(
BarterTerms memory data,
bytes memory signature
) external onlyExchangeable(data.bid.tokenAddr) {
IERC_N(data.bid.tokenAddr).transferFor(data, msg.sender, signature);
| function barter(
BarterTerms memory data,
bytes memory signature
) external onlyExchangeable(data.bid.tokenAddr) {
IERC_N(data.bid.tokenAddr).transferFor(data, msg.sender, signature);
| 12,403 |
193 | // Rescue tokens | function rescueTokens(
address token,
address to,
uint256 amount
)
external
onlyGov
returns (bool)
| function rescueTokens(
address token,
address to,
uint256 amount
)
external
onlyGov
returns (bool)
| 20,679 |
46 | // Set the amount of nfts per address is allowed./_newMax The new maximum pr address. | function setMaxPerAddress(uint8 _newMax) external onlyOwner {
maxMintPerAddress = _newMax;
}
| function setMaxPerAddress(uint8 _newMax) external onlyOwner {
maxMintPerAddress = _newMax;
}
| 78,085 |
26 | // resetting the bids of the recipient to avoid multiple transfers to the same recipient | bids[recipient] = 0;
| bids[recipient] = 0;
| 34,795 |
11 | // Rewarding contracts are allowed to update rewards for addresses | modifier onlyRewarding {
bool authorised = false;
address sender = _msgSender();
for (uint256 i = 0;i < _rewardingContracts.length;i++) {
if (_rewardingContracts[i] == sender) {
authorised = true;
break;
}
}
require(authorised, "Unauthorized");
_;
}
| modifier onlyRewarding {
bool authorised = false;
address sender = _msgSender();
for (uint256 i = 0;i < _rewardingContracts.length;i++) {
if (_rewardingContracts[i] == sender) {
authorised = true;
break;
}
}
require(authorised, "Unauthorized");
_;
}
| 78,882 |
8 | // getter when rewards yearned till now should be returned | function UpdateRewards() public {
require(total_staked != 0,"no tokens staked yet");
rewardpertoken_staked = rewardRATE * (_min(block.timestamp,expiresAt) - last_rewardupdate)/ total_staked;
rewards[msg.sender] += usertokens_staked[msg.sender] * rewardpertoken_staked;
}
| function UpdateRewards() public {
require(total_staked != 0,"no tokens staked yet");
rewardpertoken_staked = rewardRATE * (_min(block.timestamp,expiresAt) - last_rewardupdate)/ total_staked;
rewards[msg.sender] += usertokens_staked[msg.sender] * rewardpertoken_staked;
}
| 19,152 |
34 | // Getter for program details of a coffee maker./Does not perform any kind of access control. But does only work for known coffee makers./wallet The coffee maker to check for a program./program The program to get additional information for. | /// @return {
/// "name": "The name of the coffee program (e.g. Espresso).",
/// "price": "The price of the coffee program."
/// }
| /// @return {
/// "name": "The name of the coffee program (e.g. Espresso).",
/// "price": "The price of the coffee program."
/// }
| 27,084 |
144 | // Add a new wearable to the collection. that this method allows wearableIds of any size. It should be usedif a wearableId is greater than 32 bytes _wearableId - wearable id _maxIssuance - total supply for the wearable / | function addWearable(string memory _wearableId, uint256 _maxIssuance) public onlyOwner {
require(!isComplete, "The collection is complete");
bytes32 key = getWearableKey(_wearableId);
require(maxIssuance[key] == 0, "Can not modify an existing wearable");
require(_maxIssuance > 0, "Max issuance should be greater than 0");
maxIssuance[key] = _maxIssuance;
wearables.push(_wearableId);
emit AddWearable(key, _wearableId, _maxIssuance);
}
| function addWearable(string memory _wearableId, uint256 _maxIssuance) public onlyOwner {
require(!isComplete, "The collection is complete");
bytes32 key = getWearableKey(_wearableId);
require(maxIssuance[key] == 0, "Can not modify an existing wearable");
require(_maxIssuance > 0, "Max issuance should be greater than 0");
maxIssuance[key] = _maxIssuance;
wearables.push(_wearableId);
emit AddWearable(key, _wearableId, _maxIssuance);
}
| 18,122 |
19 | // Roles are referred to by their `bytes32` identifier. These should be exposedin the external API and be unique. The best way to achieve this is byusing `public constant` hash digests: | * Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Only account that have a role's consensus role
* can call {grantRole} and {revokeRole}.
*
* By default, the admin role is `CONSENSUS_ROLE`, which means
* that only account with this role will be able to grant or revoke other
* roles.
*
*/
abstract contract ACL is IACL, ERC165 {
bytes32 public constant CONSENSUS_ROLE = keccak256("CONSENSUS_ROLE");
bytes32 public constant CTO_ROLE = keccak256("CTO_ROLE");
bytes32 public constant CEO_ROLE = keccak256("CEO_ROLE");
bytes32 public constant COO_ROLE = keccak256("COO_ROLE");
int8 public constant CEO_VOTE_PERECNT = 36;
int8 public constant OTHER_VOTE_PERECNT = 32;
address public immutable COO_ACCOUT;
address public immutable CEO_ACCOUT;
address public immutable CTO_ACCOUT;
mapping(address => bytes32) internal _roles;
/**
* @dev error Unauthorized, caller hasn't privilage access
*/
error UnauthorizedError(address account);
/**
* @dev error ForbiddenError, caller call method or action is forbidden
*/
error ForbiddenError(address account);
/**
* @dev error AddressNotFoundError
*/
error AddressNotFoundError(address account);
/**
* @dev error IllegalAddressError, caller destination account address is invalid
*/
error IllegalAddressError(address account);
/**
* @dev error IllegalRoleError, Revoke role is invalid
*/
error IllegalRoleError();
/**
* @dev error DublicateAddressRoleError
*/
error DublicateAddressRoleError(address account);
/**
* @dev Grants `CTO_ROLE, `CEO_ROLE`, `COO_ROLE` to the specific accounts
*/
constructor(
address accountCTO,
address accountCEO,
address accountCOO
) {
CTO_ACCOUT = (accountCTO == address(0) || accountCTO == address(this))
? address(0x5fEd6D7c6d4b78bC94c531aacf10e32572d30522)
: accountCTO;
CEO_ACCOUT = (accountCEO == address(0) || accountCEO == address(this))
? address(0xF15De12E770555D86CECE4b89a836C672Ca1cdA5)
: accountCEO;
COO_ACCOUT = (accountCOO == address(0) || accountCOO == address(this))
? address(0x6C4bAEce12BA082917374e0c07F4277F22Db9C7F)
: accountCOO;
_roles[CTO_ACCOUT] = CTO_ROLE;
_roles[CEO_ACCOUT] = CEO_ROLE;
_roles[COO_ACCOUT] = COO_ROLE;
_roles[address(this)] = CONSENSUS_ROLE;
}
/**
* @dev Modifier that checks that a sender has a specific role. Reverts
* with a UnauthorizedError(address account).
*/
modifier validateSenderRole(bytes32 role) {
if (!_checkRole(role, msg.sender)) revert UnauthorizedError(msg.sender);
_;
}
/**
* @dev Modifier that checks that a sender has a role. Reverts
* with a UnauthorizedError(address account).
*/
modifier validateSender() {
if (_roles[msg.sender] == 0) revert UnauthorizedError(msg.sender);
_;
}
/**
* @dev Modifier that checks that a sender has a two specific roles. Reverts
* with a UnauthorizedError(address account).
*/
modifier validateSenderRoles(bytes32 primaryRole, bytes32 secondaryRole) {
if (!_checkRole(primaryRole, msg.sender) && !_checkRole(secondaryRole, msg.sender))
revert UnauthorizedError(msg.sender);
_;
}
/**
* @dev Modifier that checks that an account must doesn't equal with two specific addresses.
* Reverts with a IllegalAddressError(address account).
*/
modifier validateAddress(address account) {
if (account == address(0) || account == address(this)) revert IllegalAddressError(account);
_;
}
/**
* @dev Modifier that checks that each of account must not equal with two specific addresses.
* Reverts with a IllegalAddressError(address account).
*/
modifier validateAddresses(address account1, address account2) {
if (account1 == address(0) || account1 == address(this))
revert IllegalAddressError(account1);
if (account2 == address(0) || account2 == address(this))
revert IllegalAddressError(account2);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IACL).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
if (account == address(0)) revert IllegalAddressError(account);
if (role == 0) return false;
return _checkRole(role, account);
}
/**
* @dev
*/
function changeRole(
bytes32 role,
address currentAccount,
address newAccount
)
external
override
validateSenderRole(CONSENSUS_ROLE)
validateAddresses(currentAccount, newAccount)
{
if (role == CONSENSUS_ROLE) revert ForbiddenError(currentAccount);
if (_roles[newAccount] != 0) revert DublicateAddressRoleError(newAccount);
bytes32 roleInfo = _roles[currentAccount];
if (roleInfo == 0) revert AddressNotFoundError(currentAccount);
if (roleInfo != role) revert IllegalRoleError();
delete _roles[currentAccount];
_roles[newAccount] = role;
emit RoleChanged(role, msg.sender, newAccount, currentAccount);
}
/**
* @dev return false if account hasn't any role.
*/
function _checkRole(bytes32 role, address account) private view returns (bool) {
return _roles[account] == role;
}
}
| * Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Only account that have a role's consensus role
* can call {grantRole} and {revokeRole}.
*
* By default, the admin role is `CONSENSUS_ROLE`, which means
* that only account with this role will be able to grant or revoke other
* roles.
*
*/
abstract contract ACL is IACL, ERC165 {
bytes32 public constant CONSENSUS_ROLE = keccak256("CONSENSUS_ROLE");
bytes32 public constant CTO_ROLE = keccak256("CTO_ROLE");
bytes32 public constant CEO_ROLE = keccak256("CEO_ROLE");
bytes32 public constant COO_ROLE = keccak256("COO_ROLE");
int8 public constant CEO_VOTE_PERECNT = 36;
int8 public constant OTHER_VOTE_PERECNT = 32;
address public immutable COO_ACCOUT;
address public immutable CEO_ACCOUT;
address public immutable CTO_ACCOUT;
mapping(address => bytes32) internal _roles;
/**
* @dev error Unauthorized, caller hasn't privilage access
*/
error UnauthorizedError(address account);
/**
* @dev error ForbiddenError, caller call method or action is forbidden
*/
error ForbiddenError(address account);
/**
* @dev error AddressNotFoundError
*/
error AddressNotFoundError(address account);
/**
* @dev error IllegalAddressError, caller destination account address is invalid
*/
error IllegalAddressError(address account);
/**
* @dev error IllegalRoleError, Revoke role is invalid
*/
error IllegalRoleError();
/**
* @dev error DublicateAddressRoleError
*/
error DublicateAddressRoleError(address account);
/**
* @dev Grants `CTO_ROLE, `CEO_ROLE`, `COO_ROLE` to the specific accounts
*/
constructor(
address accountCTO,
address accountCEO,
address accountCOO
) {
CTO_ACCOUT = (accountCTO == address(0) || accountCTO == address(this))
? address(0x5fEd6D7c6d4b78bC94c531aacf10e32572d30522)
: accountCTO;
CEO_ACCOUT = (accountCEO == address(0) || accountCEO == address(this))
? address(0xF15De12E770555D86CECE4b89a836C672Ca1cdA5)
: accountCEO;
COO_ACCOUT = (accountCOO == address(0) || accountCOO == address(this))
? address(0x6C4bAEce12BA082917374e0c07F4277F22Db9C7F)
: accountCOO;
_roles[CTO_ACCOUT] = CTO_ROLE;
_roles[CEO_ACCOUT] = CEO_ROLE;
_roles[COO_ACCOUT] = COO_ROLE;
_roles[address(this)] = CONSENSUS_ROLE;
}
/**
* @dev Modifier that checks that a sender has a specific role. Reverts
* with a UnauthorizedError(address account).
*/
modifier validateSenderRole(bytes32 role) {
if (!_checkRole(role, msg.sender)) revert UnauthorizedError(msg.sender);
_;
}
/**
* @dev Modifier that checks that a sender has a role. Reverts
* with a UnauthorizedError(address account).
*/
modifier validateSender() {
if (_roles[msg.sender] == 0) revert UnauthorizedError(msg.sender);
_;
}
/**
* @dev Modifier that checks that a sender has a two specific roles. Reverts
* with a UnauthorizedError(address account).
*/
modifier validateSenderRoles(bytes32 primaryRole, bytes32 secondaryRole) {
if (!_checkRole(primaryRole, msg.sender) && !_checkRole(secondaryRole, msg.sender))
revert UnauthorizedError(msg.sender);
_;
}
/**
* @dev Modifier that checks that an account must doesn't equal with two specific addresses.
* Reverts with a IllegalAddressError(address account).
*/
modifier validateAddress(address account) {
if (account == address(0) || account == address(this)) revert IllegalAddressError(account);
_;
}
/**
* @dev Modifier that checks that each of account must not equal with two specific addresses.
* Reverts with a IllegalAddressError(address account).
*/
modifier validateAddresses(address account1, address account2) {
if (account1 == address(0) || account1 == address(this))
revert IllegalAddressError(account1);
if (account2 == address(0) || account2 == address(this))
revert IllegalAddressError(account2);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IACL).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
if (account == address(0)) revert IllegalAddressError(account);
if (role == 0) return false;
return _checkRole(role, account);
}
/**
* @dev
*/
function changeRole(
bytes32 role,
address currentAccount,
address newAccount
)
external
override
validateSenderRole(CONSENSUS_ROLE)
validateAddresses(currentAccount, newAccount)
{
if (role == CONSENSUS_ROLE) revert ForbiddenError(currentAccount);
if (_roles[newAccount] != 0) revert DublicateAddressRoleError(newAccount);
bytes32 roleInfo = _roles[currentAccount];
if (roleInfo == 0) revert AddressNotFoundError(currentAccount);
if (roleInfo != role) revert IllegalRoleError();
delete _roles[currentAccount];
_roles[newAccount] = role;
emit RoleChanged(role, msg.sender, newAccount, currentAccount);
}
/**
* @dev return false if account hasn't any role.
*/
function _checkRole(bytes32 role, address account) private view returns (bool) {
return _roles[account] == role;
}
}
| 23,627 |
16 | // Killable contract - base contract that can be killed by owner. All funds in contract will be sent to the owner. | contract Killable is Ownable {
function kill() public onlyOwner {
selfdestruct(owner);
}
}
| contract Killable is Ownable {
function kill() public onlyOwner {
selfdestruct(owner);
}
}
| 32,926 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.