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 |
|---|---|---|---|---|
89 | // 1 | globals.lockedHaveTotal,
globals.nextStakeSharesTotal,
globals.shareRate,
globals.stakePenaltyTotal,
| globals.lockedHaveTotal,
globals.nextStakeSharesTotal,
globals.shareRate,
globals.stakePenaltyTotal,
| 11,024 |
0 | // @todo add more documentation hardcoding dai for hackathon simplicity | IERC20 public dai = IERC20(0x001B3B4d0F3714Ca98ba10F6042DaEbF0B1B7b6F);
IAToken public aToken = IAToken(0x639cB7b21ee2161DF9c882483C9D55c90c20Ca3e);
ILendingPool public aaveLendingPool = ILendingPool(0x9198F13B08E299d85E096929fA9781A1E3d5d827);
ITokenManager private tokenManager = ITokenManager(0xA6687fe9F472159be142b584D3756634C2A1883a);
IToken public token;
mapping(address => uint256) public deposits;
mapping(address => uint256) public donationPercentages;
mapping(uint256 => bool) public override donated;
| IERC20 public dai = IERC20(0x001B3B4d0F3714Ca98ba10F6042DaEbF0B1B7b6F);
IAToken public aToken = IAToken(0x639cB7b21ee2161DF9c882483C9D55c90c20Ca3e);
ILendingPool public aaveLendingPool = ILendingPool(0x9198F13B08E299d85E096929fA9781A1E3d5d827);
ITokenManager private tokenManager = ITokenManager(0xA6687fe9F472159be142b584D3756634C2A1883a);
IToken public token;
mapping(address => uint256) public deposits;
mapping(address => uint256) public donationPercentages;
mapping(uint256 => bool) public override donated;
| 28,731 |
30 | // Function allows RWA Manager to update the details of the RWA portfolio. Changes in the portfolio holdings and / or price of holdings are updated via portfolio details link and the updated price of RWA is updated in _unitPrice field. This is expected to be updated regulatory //Function emits RWAUnitDetailsUpdated event which provides id of RWA updated, unit price updated and price update date/_id Refers to id of the RWA being updated/_unitPrice stores the price of a single RWA unit/_priceUpdateDate stores the last date on which the RWA unit price was updated by RWA Manager/_portfolioDetailsLink stores the link to the |
function updateRWAUnitDetails(
uint256 _id,
string memory _portfolioDetailsLink,
uint128 _unitPrice,
uint32 _priceUpdateDate
|
function updateRWAUnitDetails(
uint256 _id,
string memory _portfolioDetailsLink,
uint128 _unitPrice,
uint32 _priceUpdateDate
| 33,839 |
62 | // ydy = fyDaiReserves - fyDaiAmount; | uint256 ydy = uint256 (fyDaiReserves) - uint256 (fyDaiAmount);
require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai out");
uint256 sum =
pow (daiReserves, uint128 (a), 0x10000000000000000) +
pow (fyDaiReserves, uint128 (a), 0x10000000000000000) -
pow (uint128 (ydy), uint128 (a), 0x10000000000000000);
require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting Dai reserves too high");
uint256 result =
| uint256 ydy = uint256 (fyDaiReserves) - uint256 (fyDaiAmount);
require (ydy < 0x100000000000000000000000000000000, "YieldMath: Too much fyDai out");
uint256 sum =
pow (daiReserves, uint128 (a), 0x10000000000000000) +
pow (fyDaiReserves, uint128 (a), 0x10000000000000000) -
pow (uint128 (ydy), uint128 (a), 0x10000000000000000);
require (sum < 0x100000000000000000000000000000000, "YieldMath: Resulting Dai reserves too high");
uint256 result =
| 10,764 |
42 | // 10% get helmets | return getHelmetLabel(slot);
| return getHelmetLabel(slot);
| 49,127 |
24 | // Used for activating the asset _asset underlying asset / | function activateAsset(bytes32 _asset) external onlyOwner(msg.sender) inactiveAsset(_asset) {
Asset storage asset = assetNameMap[_asset];
asset._active = true;
emit AssetActivate(asset._name, asset._address);
}
| function activateAsset(bytes32 _asset) external onlyOwner(msg.sender) inactiveAsset(_asset) {
Asset storage asset = assetNameMap[_asset];
asset._active = true;
emit AssetActivate(asset._name, asset._address);
}
| 22,849 |
210 | // The current and previous epoch | Epoch public currentEpoch;
Epoch public previousEpoch;
| Epoch public currentEpoch;
Epoch public previousEpoch;
| 44,489 |
8 | // Set new distributor. / | function distributor(address account) external onlyOwner {
require (_distributor == address(0));
_distributor = account;
}
| function distributor(address account) external onlyOwner {
require (_distributor == address(0));
_distributor = account;
}
| 30,726 |
93 | // registered DC signatories can revoke (0x) signature | function revokeDC(uint256 dcNumber) public { // revoke Digital Covenant signature with (0x) address
DC storage dc = rdc[dcNumber]; // retrieve rdc data
require(msg.sender == dc.signatory); // program safety check / authorization
rdc[dcNumber] = DC(// updates rdc data
msg.sender,
"Signature Revoked", // replaces Digital Covenant terms with revocation message
dc.signatureDetails,
dc.lexID,
dc.dcNumber,
now, // updates to revocation timestamp
true);
emit Signed(dc.lexID, dcNumber, msg.sender);
}
| function revokeDC(uint256 dcNumber) public { // revoke Digital Covenant signature with (0x) address
DC storage dc = rdc[dcNumber]; // retrieve rdc data
require(msg.sender == dc.signatory); // program safety check / authorization
rdc[dcNumber] = DC(// updates rdc data
msg.sender,
"Signature Revoked", // replaces Digital Covenant terms with revocation message
dc.signatureDetails,
dc.lexID,
dc.dcNumber,
now, // updates to revocation timestamp
true);
emit Signed(dc.lexID, dcNumber, msg.sender);
}
| 43,631 |
3 | // roles | uint256 constant ROLE_ZERO_ANYONE = 0;
uint256 constant ROLE_ROOT = 1;
uint256 constant ROLE_VENDOR = 2;
uint256 constant ROLE_XFERAUTH = 3;
uint256 constant ROLE_POPADMIN = 4;
uint256 constant ROLE_CUSTODIAN = 5;
uint256 constant ROLE_AUDITOR = 6;
uint256 constant ROLE_MARKETPLACE_ADMIN = 7;
uint256 constant ROLE_KYC_ADMIN = 8;
uint256 constant ROLE_FEES_ADMIN = 9;
| uint256 constant ROLE_ZERO_ANYONE = 0;
uint256 constant ROLE_ROOT = 1;
uint256 constant ROLE_VENDOR = 2;
uint256 constant ROLE_XFERAUTH = 3;
uint256 constant ROLE_POPADMIN = 4;
uint256 constant ROLE_CUSTODIAN = 5;
uint256 constant ROLE_AUDITOR = 6;
uint256 constant ROLE_MARKETPLACE_ADMIN = 7;
uint256 constant ROLE_KYC_ADMIN = 8;
uint256 constant ROLE_FEES_ADMIN = 9;
| 58,420 |
2 | // Maps wrapped token to underlying | function wrappedToUnderlying(address _wrapped) external view returns(address);
function underlyingToProtocolWrapped(address _underlying, bytes32 protocol) external view returns (address);
function protocolToLogic(bytes32 _protocol) external view returns (address);
| function wrappedToUnderlying(address _wrapped) external view returns(address);
function underlyingToProtocolWrapped(address _underlying, bytes32 protocol) external view returns (address);
function protocolToLogic(bytes32 _protocol) external view returns (address);
| 16,097 |
37 | // check if remaining balance is above min stake amount | require(
staker.balance - amount >= pool.minStakeAmount,
'RewardPools: remaining balance below minimum stake amount'
);
| require(
staker.balance - amount >= pool.minStakeAmount,
'RewardPools: remaining balance below minimum stake amount'
);
| 32,981 |
29 | // 06.12.2017 08:30 AM | angel_sale_finish = 1510488000;
| angel_sale_finish = 1510488000;
| 2,123 |
24 | // Gas limit that YPool need to proceed deposit request | uint256 public completeDepositGasLimit;
| uint256 public completeDepositGasLimit;
| 43,631 |
78 | // If the shield requires full coverage, check coverage base to see if it is available. - Must return false if any of the covBases do not have coverage available. _ethValue Ether value of the new tokens.return allowed True if the deposit is allowed./ | {
if (capped) {
for(uint256 i = 0; i < covBases.length; i++) {
if( !covBases[i].checkCoverage(_ethValue) ) return false;
}
}
allowed = true;
}
| {
if (capped) {
for(uint256 i = 0; i < covBases.length; i++) {
if( !covBases[i].checkCoverage(_ethValue) ) return false;
}
}
allowed = true;
}
| 13,691 |
159 | // deposit ids will be (_blockDepositId, _blockDepositId + 1, .... _blockDepositId + numDeposits - 1) | _blockDepositId = _blockDepositId.add(numDeposits);
require(
| _blockDepositId = _blockDepositId.add(numDeposits);
require(
| 6,456 |
825 | // _allowed flag to enable the check if redeemed amount during liquidations is enough | function setRevertIfTooLow(bool _allowed) external {
_checkOnlyOwner();
revertIfTooLow = _allowed;
}
| function setRevertIfTooLow(bool _allowed) external {
_checkOnlyOwner();
revertIfTooLow = _allowed;
}
| 29,646 |
162 | // Updating rate distribution parameters if need be | if (block.timestamp >= startEpochTime + RATE_REDUCTION_TIME) {
_updateMiningParameters();
}
| if (block.timestamp >= startEpochTime + RATE_REDUCTION_TIME) {
_updateMiningParameters();
}
| 39,389 |
11 | // solium-disable-next-line | _timestamps[user] = uint40(block.timestamp);
| _timestamps[user] = uint40(block.timestamp);
| 13,236 |
115 | // Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair / | function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
| function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
| 183 |
14 | // Due to the presence of this function, it is considered a valid ERC20 token.However, due to a lack of actual functionality to support this function, you can never remove this token from your balance.RIP. / | function transfer(address _to, uint256 _value)
public
returns (bool success)
| function transfer(address _to, uint256 _value)
public
returns (bool success)
| 37,582 |
673 | // Reads the uint208 at `rdPtr` in returndata. | function readUint208(
ReturndataPointer rdPtr
| function readUint208(
ReturndataPointer rdPtr
| 23,673 |
72 | // Used internally, mostly by children implementations, see unstake()_staker an address which unstakes tokens (which previously staked them) _depositId deposit ID to unstake from, zero-indexed _amount amount of tokens to unstake / | function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount
| function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount
| 48,619 |
11 | // returns the fields and values that describe the domain separator used by this contract for EIP-712signature. / | function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
| function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
| 9,921 |
268 | // Zeroize the slot after the string. | mstore(str, 0)
| mstore(str, 0)
| 11,284 |
7 | // Block number when bonus BDL period ends. | uint256 public bonusEndBlock;
| uint256 public bonusEndBlock;
| 26,645 |
462 | // 1 week = 168hrs60 min/hr60 sec/min / ~13 sec/block = 46523 blocks | _updateRemoveDelegatorLockupDuration(46523);
| _updateRemoveDelegatorLockupDuration(46523);
| 45,367 |
47 | // Calculates the largest possible `amountx` and `amountY` such that/ they're in the same proportion as total amounts, but not greater than/ `amountXDesired` and `amountYDesired` respectively. | function calcSharesAndAmounts(
uint256 amountXDesired,
uint256 amountYDesired
| function calcSharesAndAmounts(
uint256 amountXDesired,
uint256 amountYDesired
| 9,884 |
133 | // Checks if two strings are the same._a String 1 _b String 2 return True if both strings are the same. False otherwise. / | {
bytes32 hashA = keccak256(abi.encodePacked(_a));
bytes32 hashB = keccak256(abi.encodePacked(_b));
return hashA == hashB;
}
| {
bytes32 hashA = keccak256(abi.encodePacked(_a));
bytes32 hashB = keccak256(abi.encodePacked(_b));
return hashA == hashB;
}
| 20,545 |
279 | // Used to set the strategy contract that determines the positionranges and calls rebalance(). Must be called after this vault isdeployed. / | function setStrategy(address _strategy) external onlyGovernance {
strategy = _strategy;
}
| function setStrategy(address _strategy) external onlyGovernance {
strategy = _strategy;
}
| 19,144 |
0 | // ============ Events ============ |
event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
|
event OwnershipTransferPrepared(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
| 4,349 |
10 | // ---------------------------UserApplication config---------------------------------------- | function getConfig(uint16 _version, uint16 _chainId, address, uint _configType) external view returns (bytes memory) {
return lzEndpoint.getConfig(_version, _chainId, address(this), _configType);
}
| function getConfig(uint16 _version, uint16 _chainId, address, uint _configType) external view returns (bytes memory) {
return lzEndpoint.getConfig(_version, _chainId, address(this), _configType);
}
| 21,186 |
238 | // View function to see pending SUSHIs on "frontend". | function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
// better name: currPoolInfo
PoolInfo storage pool = poolInfo[_pid];
// better name: userOfCurrPool
UserInfo storage user = userInfo[_pid][_user];
// Accumulated SUSHIs per share, times 1e12.
uint256 accSushiPerShare = pool.accSushiPerShare;
// better name: total_staked_LpTokens_of_currPool
uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // how many LP_tokens staked in the MasterChef
// if currPool has any LpToken staked
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
// // totalSushi minted / sushiPerBlock on (lastRewardBlock .. block.number]
// uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
//
// // currPool's reward weight = pool.allocPoint / totalAllocPoint
// // better name: sushiReward_for_currPool on (lastRewardBlock ... block.number]
// uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
//
// accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
// 🐧 we use different reward function, so instead the code above:
uint256 totalSushiReward = totalRewardAtBlock(block.number).sub(totalRewardAtBlock(pool.lastRewardBlock));
uint256 totalSushiRewardForPool = totalSushiReward.mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(totalSushiRewardForPool.mul(1e12).div(lpSupply));
}
// return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
// because original sushi contact mints 1 sushi to dev (in addition to 10 for LPs)
// they implicitly diluted supply for ~9.09% as dev tax
// to keep math clean, we explicitly we give LPs 60%, growthFund 10%
// and 30% to xSigma investors and team so and we need to account for that
uint256 userAmountBeforeTax = user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
return userAmountBeforeTax.mul(60).div(100);
}
| function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
// better name: currPoolInfo
PoolInfo storage pool = poolInfo[_pid];
// better name: userOfCurrPool
UserInfo storage user = userInfo[_pid][_user];
// Accumulated SUSHIs per share, times 1e12.
uint256 accSushiPerShare = pool.accSushiPerShare;
// better name: total_staked_LpTokens_of_currPool
uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // how many LP_tokens staked in the MasterChef
// if currPool has any LpToken staked
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
// // totalSushi minted / sushiPerBlock on (lastRewardBlock .. block.number]
// uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
//
// // currPool's reward weight = pool.allocPoint / totalAllocPoint
// // better name: sushiReward_for_currPool on (lastRewardBlock ... block.number]
// uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
//
// accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
// 🐧 we use different reward function, so instead the code above:
uint256 totalSushiReward = totalRewardAtBlock(block.number).sub(totalRewardAtBlock(pool.lastRewardBlock));
uint256 totalSushiRewardForPool = totalSushiReward.mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(totalSushiRewardForPool.mul(1e12).div(lpSupply));
}
// return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
// because original sushi contact mints 1 sushi to dev (in addition to 10 for LPs)
// they implicitly diluted supply for ~9.09% as dev tax
// to keep math clean, we explicitly we give LPs 60%, growthFund 10%
// and 30% to xSigma investors and team so and we need to account for that
uint256 userAmountBeforeTax = user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
return userAmountBeforeTax.mul(60).div(100);
}
| 7,833 |
8 | // adminDelegatecall allows this contract to delegate calls/ to a target contract and execute it in the context of this/ contract. Only default admin role can call this function./target the target contract address/data is the ABI encoded function signature and its values./ @custom:oz-upgrades-unsafe-allow delegatecall | function adminDelegatecall(address target, bytes memory data)
external
payable
onlyRole(DEFAULT_ADMIN_ROLE)
returns (bytes memory)
| function adminDelegatecall(address target, bytes memory data)
external
payable
onlyRole(DEFAULT_ADMIN_ROLE)
returns (bytes memory)
| 2,322 |
108 | // Make a new record, writing to the 'database' mapping with basic initial asset data / | function newRecord(
| function newRecord(
| 32,891 |
1 | // Set admini permissions _admin The address of the administrator _isAuthorized A boolean to indicate if the administrator is authorized / | function setAdmin(address _admin, bool _isAuthorized) public onlyAdmins {
adminPermissions[_admin] = _isAuthorized;
emit AdminPermissionChanged(_admin, _isAuthorized);
}
| function setAdmin(address _admin, bool _isAuthorized) public onlyAdmins {
adminPermissions[_admin] = _isAuthorized;
emit AdminPermissionChanged(_admin, _isAuthorized);
}
| 9,148 |
35 | // only mint tokens if msg.value is greather than minimum investment and we are past the launch date | if (msg.value >= minimum_wei && block.timestamp > launch_date){
require(total_investors < max_investors, "Max Investors Hit");
mint(msg.sender, msg.value);
}
| if (msg.value >= minimum_wei && block.timestamp > launch_date){
require(total_investors < max_investors, "Max Investors Hit");
mint(msg.sender, msg.value);
}
| 23,447 |
39 | // /Get Product BatchID by indexed value of stored data/index Indexed Number/ return Product BatchID | function getBatchIdByIndexM(uint index) public view returns(address BathID) {
require(
UsersDetails[msg.sender].role == roles.manufacturer,
"Only Manufacturer Can call this function."
);
return ManufactureredProductBatches[msg.sender][index];
}
| function getBatchIdByIndexM(uint index) public view returns(address BathID) {
require(
UsersDetails[msg.sender].role == roles.manufacturer,
"Only Manufacturer Can call this function."
);
return ManufactureredProductBatches[msg.sender][index];
}
| 45,243 |
458 | // You need to wait `lockTime` before being able to withdraw funds from the protocol as a HA | require(perpetual.entryTimestamp + lockTime <= block.timestamp, "31");
| require(perpetual.entryTimestamp + lockTime <= block.timestamp, "31");
| 30,211 |
13 | // Copy the pair (idx, hash) to the dataToHash array. | mstore(dataToHashPtr, curIdx)
mstore(add(dataToHashPtr, 0x20), mload(add(merkleQueuePtr, 0x20)))
dataToHashPtr := add(dataToHashPtr, 0x40)
merkleQueuePtr := add(merkleQueuePtr, MERKLE_SLOT_SIZE_IN_BYTES)
| mstore(dataToHashPtr, curIdx)
mstore(add(dataToHashPtr, 0x20), mload(add(merkleQueuePtr, 0x20)))
dataToHashPtr := add(dataToHashPtr, 0x40)
merkleQueuePtr := add(merkleQueuePtr, MERKLE_SLOT_SIZE_IN_BYTES)
| 27,316 |
0 | // Storage - contracts |
WTON internal _wton;
Layer2RegistryI internal _registry;
SeigManagerI internal _seigManager;
|
WTON internal _wton;
Layer2RegistryI internal _registry;
SeigManagerI internal _seigManager;
| 33,616 |
301 | // Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,for x close to one. Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. / | function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
| function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
| 4,924 |
32 | // --valid: | if(userMax > 0) {
uint[] memory r1 = routerMarker.getAmountsIn(userPut,round1Path);
uint256 round1AmountMaxIn = r1[0];
require(round1AmountMaxIn <= userMax, "err:round1AmountMaxIn>userMax");
} else {
| if(userMax > 0) {
uint[] memory r1 = routerMarker.getAmountsIn(userPut,round1Path);
uint256 round1AmountMaxIn = r1[0];
require(round1AmountMaxIn <= userMax, "err:round1AmountMaxIn>userMax");
} else {
| 1,283 |
98 | // return Number of unlock schedules. / | function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
| function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
| 17,425 |
201 | // If the fund only contains ether, return the funds ether balance | if (tokenAddresses.length == 1)
return ethBalance;
| if (tokenAddresses.length == 1)
return ethBalance;
| 3,901 |
2 | // Curve Pool address | address public curveFrx;
| address public curveFrx;
| 39,534 |
13 | // resArray = mulArrays(resArray, subArrays(THREEHALFS, mulArrays(resDivByTwo, mulArrays(resArray, resArray) ) ) ); | return fromArray(resArray);
| return fromArray(resArray);
| 51,630 |
122 | // Return ticket value based on tier | if (tier == 5) {
return 0;
} else if (tier == 4) {
| if (tier == 5) {
return 0;
} else if (tier == 4) {
| 67,653 |
186 | // This is the provenance record of all Hashmasks artwork in existence | string public constant HASHMASKS_PROVENANCE = "481fdd1d07e7912479a77fb060ac089403deadbcefbb34ca05315d51db78cbb8";
uint256 public constant SALE_START_TIMESTAMP = 1612494357; //set sale time here in unix
| string public constant HASHMASKS_PROVENANCE = "481fdd1d07e7912479a77fb060ac089403deadbcefbb34ca05315d51db78cbb8";
uint256 public constant SALE_START_TIMESTAMP = 1612494357; //set sale time here in unix
| 19,545 |
88 | // -----------------------------------------------------------------------/ Execution Logic/ ----------------------------------------------------------------------- |
function _execute(
Operation op,
address to,
uint256 value,
bytes memory data
|
function _execute(
Operation op,
address to,
uint256 value,
bytes memory data
| 37,965 |
106 | // This is internal function is equivalent to {transfer}, and can be used toe.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address.- `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`. / | function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
| function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
| 64,082 |
244 | // Set `principalOwed` to zero and return excess value from the liquidation back to the Borrower. | else {
liquidationExcess = amountRecovered.sub(principalOwed);
principalOwed = 0;
liquidityAsset.safeTransfer(borrower, liquidationExcess); // Send excess to the Borrower.
}
| else {
liquidationExcess = amountRecovered.sub(principalOwed);
principalOwed = 0;
liquidityAsset.safeTransfer(borrower, liquidationExcess); // Send excess to the Borrower.
}
| 23,172 |
172 | // A reverse-mutex, granting atomic permission for particular contracts to make vault calls | bool internal permissionedVaultActionAllowed;
| bool internal permissionedVaultActionAllowed;
| 16,898 |
146 | // Overflows are incredibly unrealistic. balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2128) - 1 updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2128) - 1 | unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
| unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
| 3,128 |
95 | // normal send cln to the market maker contract, sender must approve() before calling method. can only be called by owner/sending CLN will return CC from the reserve to the sender./_token address address of the cc token managed by this factory./_clnAmount uint256 amount of CLN to transfer into the Market Maker reserve. | function insertCLNtoMarketMaker(address _token,
uint256 _clnAmount) public
tokenIssuerOnly(_token, msg.sender)
| function insertCLNtoMarketMaker(address _token,
uint256 _clnAmount) public
tokenIssuerOnly(_token, msg.sender)
| 32,953 |
33 | // Update pool information | _updatePool();
| _updatePool();
| 24,875 |
54 | // Process fees after expiry _balances current balances _currentRound current round / | function _processFees(uint256[] memory _balances, uint256 _currentRound)
internal
virtual
returns (uint256[] memory balances)
| function _processFees(uint256[] memory _balances, uint256 _currentRound)
internal
virtual
returns (uint256[] memory balances)
| 19,529 |
69 | // Interface for the BaseAllocator These are the standard functions that an Allocator should implement. A subset of these functions is implemented in the `BaseAllocator`. Similar to those implemented, if for some reason the developer decides to implement a dedicated base contract, or not at all and rather a dedicated Allocator contract without base, imitate the functionalities implemented in it. / | interface IAllocator {
/**
* @notice
* Emitted when the Allocator is deployed.
*/
event AllocatorDeployed(address authority, address extender);
/**
* @notice
* Emitted when the Allocator is activated.
*/
event AllocatorActivated();
/**
* @notice
* Emitted when the Allocator is deactivated.
*/
event AllocatorDeactivated(bool panic);
/**
* @notice
* Emitted when the Allocators loss limit is violated.
*/
event LossLimitViolated(uint128 lastLoss, uint128 dloss, uint256 estimatedTotalAllocated);
/**
* @notice
* Emitted when a Migration is executed.
* @dev
* After this also `AllocatorDeactivated` should follow.
*/
event MigrationExecuted(address allocator);
/**
* @notice
* Emitted when Ether is received by the contract.
* @dev
* Only the Guardian is able to send the ether.
*/
event EtherReceived(uint256 amount);
function update(uint256 id) external;
function deallocate(uint256[] memory amounts) external;
function prepareMigration() external;
function migrate() external;
function activate() external;
function deactivate(bool panic) external;
function addId(uint256 id) external;
function name() external view returns (string memory);
function ids() external view returns (uint256[] memory);
function tokenIds(uint256 id) external view returns (uint256);
function version() external view returns (string memory);
function status() external view returns (AllocatorStatus);
function tokens() external view returns (IERC20[] memory);
function utilityTokens() external view returns (IERC20[] memory);
function rewardTokens() external view returns (IERC20[] memory);
function amountAllocated(uint256 id) external view returns (uint256);
}
| interface IAllocator {
/**
* @notice
* Emitted when the Allocator is deployed.
*/
event AllocatorDeployed(address authority, address extender);
/**
* @notice
* Emitted when the Allocator is activated.
*/
event AllocatorActivated();
/**
* @notice
* Emitted when the Allocator is deactivated.
*/
event AllocatorDeactivated(bool panic);
/**
* @notice
* Emitted when the Allocators loss limit is violated.
*/
event LossLimitViolated(uint128 lastLoss, uint128 dloss, uint256 estimatedTotalAllocated);
/**
* @notice
* Emitted when a Migration is executed.
* @dev
* After this also `AllocatorDeactivated` should follow.
*/
event MigrationExecuted(address allocator);
/**
* @notice
* Emitted when Ether is received by the contract.
* @dev
* Only the Guardian is able to send the ether.
*/
event EtherReceived(uint256 amount);
function update(uint256 id) external;
function deallocate(uint256[] memory amounts) external;
function prepareMigration() external;
function migrate() external;
function activate() external;
function deactivate(bool panic) external;
function addId(uint256 id) external;
function name() external view returns (string memory);
function ids() external view returns (uint256[] memory);
function tokenIds(uint256 id) external view returns (uint256);
function version() external view returns (string memory);
function status() external view returns (AllocatorStatus);
function tokens() external view returns (IERC20[] memory);
function utilityTokens() external view returns (IERC20[] memory);
function rewardTokens() external view returns (IERC20[] memory);
function amountAllocated(uint256 id) external view returns (uint256);
}
| 77,316 |
8 | // Constants | string public constant name = 'Smart Energy';
uint256 public constant decimals = 6;
string public constant symbol = 'SET';
string public constant version = '1.0';
string public constant note = 'Blockchain for Energy';
| string public constant name = 'Smart Energy';
uint256 public constant decimals = 6;
string public constant symbol = 'SET';
string public constant version = '1.0';
string public constant note = 'Blockchain for Energy';
| 27,922 |
114 | // If setting Fuse fee | if (fuseFeeMantissa != newFuseFeeMantissa) {
| if (fuseFeeMantissa != newFuseFeeMantissa) {
| 8,468 |
1 | // Current holder of the Letter of Credit (can be transferrable) | address private holder;
| address private holder;
| 50,786 |
5 | // (a + b - 1) / b can overflow on addition, so we distribute. | return a == 0 ? 0 : (a - 1) / b + 1;
| return a == 0 ? 0 : (a - 1) / b + 1;
| 7,898 |
140 | // TaalToken with Governance. | contract TaalToken is ERC20('TaalSwap Token', 'TAL') {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
require(
IERC20(address(this)).totalSupply().add(_amount) <= (100_000_000 * (10 ** uint256(18))),
"TAL::mint:: cannot mint more than cap"
);
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TAL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TAL::delegateBySig: invalid nonce");
require(now <= expiry, "TAL::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TAL::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TALs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "TAL::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | contract TaalToken is ERC20('TaalSwap Token', 'TAL') {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
require(
IERC20(address(this)).totalSupply().add(_amount) <= (100_000_000 * (10 ** uint256(18))),
"TAL::mint:: cannot mint more than cap"
);
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TAL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TAL::delegateBySig: invalid nonce");
require(now <= expiry, "TAL::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "TAL::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TALs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "TAL::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | 57,173 |
18 | // Transfer pyth update fee to orderbook | payable(orderbook_address).transfer(pyth_update_fee);
| payable(orderbook_address).transfer(pyth_update_fee);
| 4,231 |
84 | // Return properly scaled zxRound. | z := div(zxRound, scalar)
| z := div(zxRound, scalar)
| 5,506 |
2 | // Returns the merkle root of the merkle tree containing grant details available to accept. | function merkleRoot() external view returns (bytes32);
| function merkleRoot() external view returns (bytes32);
| 24,813 |
13 | // The number of votes required in order for a voter to become a proposer | function proposalThreshold() public view returns (uint256) { return 50000 * 10**24; } // 1% of YAM
| function proposalThreshold() public view returns (uint256) { return 50000 * 10**24; } // 1% of YAM
| 13,824 |
15 | // Presale Contributors can view claimable amount/ return amount Token amount claimable | function amountClaimable(address user) public view returns (uint amount) {
if (!tokenHasLaunched) return 0;
AllocationData memory ad = presaleParticipant[user];
if (block.timestamp < (tokenPairLaunchTimestamp + vestingDuration)) { // vesting
uint claimStartTimestamp = ad.lastClaimTimestamp == 0 ? tokenPairLaunchTimestamp : ad.lastClaimTimestamp;
amount = ad.totalAllocation * (block.timestamp - claimStartTimestamp) / vestingDuration;
} else { // vesting period finished, return remainder of unclaimed tokens
amount = ad.totalAllocation - ad.amountClaimed;
}
}
| function amountClaimable(address user) public view returns (uint amount) {
if (!tokenHasLaunched) return 0;
AllocationData memory ad = presaleParticipant[user];
if (block.timestamp < (tokenPairLaunchTimestamp + vestingDuration)) { // vesting
uint claimStartTimestamp = ad.lastClaimTimestamp == 0 ? tokenPairLaunchTimestamp : ad.lastClaimTimestamp;
amount = ad.totalAllocation * (block.timestamp - claimStartTimestamp) / vestingDuration;
} else { // vesting period finished, return remainder of unclaimed tokens
amount = ad.totalAllocation - ad.amountClaimed;
}
}
| 14,022 |
0 | // A minting backdoor, just like with real $TRON. | function mint(uint256 amount) external {
balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);
}
| function mint(uint256 amount) external {
balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);
}
| 14,849 |
63 | // Check to see if candidate is an adopted asset. | _canonical = s.adoptedToCanonical[_candidate];
if (_canonical.domain != 0) {
| _canonical = s.adoptedToCanonical[_candidate];
if (_canonical.domain != 0) {
| 30,162 |
29 | // revert to booster's owner | function revertControl() external onlyOwner{
IBooster(booster).setVoteDelegate(IBooster(booster).owner());
}
| function revertControl() external onlyOwner{
IBooster(booster).setVoteDelegate(IBooster(booster).owner());
}
| 5,864 |
327 | // _tokenURIs is a array of links to json / | function mintPack() public payable returns (uint256) {
require(totalSupply() >= 850, "Pack is not available now");
require(
getNFTPackPrice() == msg.value,
"Ether value sent is not correct"
);
require(!paused(), "ERC721Pausable: token mint while paused");
uint256 newItemId;
for (uint256 i = 0; i < 3; i++) {
_tokenIds.increment();
newItemId = _tokenIds.current();
require(newItemId <= maxSupply);
_mint(msg.sender, newItemId);
}
return newItemId;
}
| function mintPack() public payable returns (uint256) {
require(totalSupply() >= 850, "Pack is not available now");
require(
getNFTPackPrice() == msg.value,
"Ether value sent is not correct"
);
require(!paused(), "ERC721Pausable: token mint while paused");
uint256 newItemId;
for (uint256 i = 0; i < 3; i++) {
_tokenIds.increment();
newItemId = _tokenIds.current();
require(newItemId <= maxSupply);
_mint(msg.sender, newItemId);
}
return newItemId;
}
| 23,525 |
10 | // 인증서 폐기 여부를 false 로 설정 (사용가능한 인증서) | crl[signId] = false;
| crl[signId] = false;
| 9,896 |
27 | // Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. / | function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
| function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
| 57,965 |
1 | // Create a Proxy/_target the Stores to interact with | constructor(Stores _target) public {
stores = _target;
}
| constructor(Stores _target) public {
stores = _target;
}
| 32,124 |
1 | // receive() external payable {} |
function buy(
Order memory order,
address takerAddress
|
function buy(
Order memory order,
address takerAddress
| 21,024 |
41 | // Current asset implementation contract address. | address latestVersion;
| address latestVersion;
| 67,738 |
221 | // Returns number of tokens currently registered / | function getNTokens() external view returns (uint256) {
return nTokens;
}
| function getNTokens() external view returns (uint256) {
return nTokens;
}
| 13,258 |
217 | // Account does not exist, and contract is not deployed, if hash equals 0. | if (hash == bytes32(0)) {
return true;
}
| if (hash == bytes32(0)) {
return true;
}
| 23,123 |
271 | // Set some Flames aside / | function reserveCluck() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 20; i++) {
_safeMint(msg.sender, supply + i);
}
}
| function reserveCluck() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 20; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 21,369 |
216 | // if we want to get on chain info about FL params | if (flData.flParamGetterAddr != address(0)) {
(flData.tokens, flData.amounts, flData.modes) =
IFLParamGetter(flData.flParamGetterAddr).getFlashLoanParams(flData.flParamGetterData);
}
| if (flData.flParamGetterAddr != address(0)) {
(flData.tokens, flData.amounts, flData.modes) =
IFLParamGetter(flData.flParamGetterAddr).getFlashLoanParams(flData.flParamGetterData);
}
| 39,937 |
20 | // Exactly 8 iterations | for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
| for (uint8 s = 128; s > 0; s >>= 1) {
if (_n >= (ONE << s)) {
_n >>= s;
res |= s;
}
| 43,588 |
11 | // Withdrawals! | function withdraw(uint sacrificeIndex) public {
require(now > end_time);
require(sacrificeIndex >= 0);
require(sacrificeIndex < sacrifices.length);
Sacrifice storage withdrawal = sacrifices[sacrificeIndex];
require(withdrawal.sender == msg.sender);
require(withdrawal.paid == false);
withdrawal.paid = true;
uint last100Payout = 0;
if(sacrifices.length - sacrificeIndex < 100){
uint last100Pot = pot * 1 / 10;
last100Payout += last100Pot * 1 / 100;
}
uint last10Percent = pot * 1 / 10;
uint last10PercentPayout = 0;
if(withdrawal.potSize > pot - last10Percent){
uint last10PercentPot = pot * 9 / 10;
uint payoutPerWei = last10PercentPot / last10Percent;
last10PercentPayout = withdrawal.amount * payoutPerWei;
}
uint winnings = last100Payout + last10PercentPayout;
msg.sender.transfer(winnings);
}
| function withdraw(uint sacrificeIndex) public {
require(now > end_time);
require(sacrificeIndex >= 0);
require(sacrificeIndex < sacrifices.length);
Sacrifice storage withdrawal = sacrifices[sacrificeIndex];
require(withdrawal.sender == msg.sender);
require(withdrawal.paid == false);
withdrawal.paid = true;
uint last100Payout = 0;
if(sacrifices.length - sacrificeIndex < 100){
uint last100Pot = pot * 1 / 10;
last100Payout += last100Pot * 1 / 100;
}
uint last10Percent = pot * 1 / 10;
uint last10PercentPayout = 0;
if(withdrawal.potSize > pot - last10Percent){
uint last10PercentPot = pot * 9 / 10;
uint payoutPerWei = last10PercentPot / last10Percent;
last10PercentPayout = withdrawal.amount * payoutPerWei;
}
uint winnings = last100Payout + last10PercentPayout;
msg.sender.transfer(winnings);
}
| 21,329 |
42 | // withdraw NDC and TPT tokens/ | function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
assert(teleportToken.transfer(owner, tptBalance));
}
| function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
assert(teleportToken.transfer(owner, tptBalance));
}
| 3,882 |
6 | // Allows the current owner to relinquish control of the contract. / | function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
| function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
| 15,690 |
31 | // Allows a given token for a given employee / | {
Employee storage employee = employeesMap[_employeeAddress];
supportedTokensMap[_token] = Token(_token, _exchangeRate);
employee.selectedTokens[_token] = supportedTokensMap[_token];
employeeTokenMap[_employeeAddress].push(_token);
employee.allowedTokensMap[_token] = 1;
LogTokenAllowed(getTime(), _employeeAddress, _token, _exchangeRate);
}
| {
Employee storage employee = employeesMap[_employeeAddress];
supportedTokensMap[_token] = Token(_token, _exchangeRate);
employee.selectedTokens[_token] = supportedTokensMap[_token];
employeeTokenMap[_employeeAddress].push(_token);
employee.allowedTokensMap[_token] = 1;
LogTokenAllowed(getTime(), _employeeAddress, _token, _exchangeRate);
}
| 51,081 |
4 | // Get the current token count/ return the created token count | function tokenCount() public view returns (uint256) {
return _tokenCount.current();
}
| function tokenCount() public view returns (uint256) {
return _tokenCount.current();
}
| 7,468 |
20 | // Kongliang Zhong - <kongliang@loopring.org>/IFeeHolder - A contract holding fees. | contract IFeeHolder {
event TokenWithdrawn(
address owner,
address token,
uint value
);
// A map of all fee balances; token --> owner --> balance
mapping(address => mapping(address => uint)) public feeBalances;
// A map of all the nonces for a withdrawTokenFor request
mapping(address => uint) public nonces;
/// @dev Allows withdrawing the tokens to be burned by
/// authorized contracts.
/// @param token The token to be used to burn buy and burn LRC
/// @param value The amount of tokens to withdraw
function withdrawBurned(
address token,
uint value
)
external
returns (bool success);
/// @dev Allows withdrawing the fee payments funds
/// msg.sender is the recipient of the fee and the address
/// to which the tokens will be sent.
/// @param token The token to withdraw
/// @param value The amount of tokens to withdraw
function withdrawToken(
address token,
uint value
)
external
returns (bool success);
/// @dev Allows withdrawing the fee payments funds by providing a
/// a signature
function withdrawTokenFor(
address owner,
address token,
uint value,
address recipient,
uint feeValue,
address feeRecipient,
uint nonce,
bytes calldata signature
)
external
returns (bool success);
function batchAddFeeBalances(
bytes32[] calldata batch
)
external;
}
| contract IFeeHolder {
event TokenWithdrawn(
address owner,
address token,
uint value
);
// A map of all fee balances; token --> owner --> balance
mapping(address => mapping(address => uint)) public feeBalances;
// A map of all the nonces for a withdrawTokenFor request
mapping(address => uint) public nonces;
/// @dev Allows withdrawing the tokens to be burned by
/// authorized contracts.
/// @param token The token to be used to burn buy and burn LRC
/// @param value The amount of tokens to withdraw
function withdrawBurned(
address token,
uint value
)
external
returns (bool success);
/// @dev Allows withdrawing the fee payments funds
/// msg.sender is the recipient of the fee and the address
/// to which the tokens will be sent.
/// @param token The token to withdraw
/// @param value The amount of tokens to withdraw
function withdrawToken(
address token,
uint value
)
external
returns (bool success);
/// @dev Allows withdrawing the fee payments funds by providing a
/// a signature
function withdrawTokenFor(
address owner,
address token,
uint value,
address recipient,
uint feeValue,
address feeRecipient,
uint nonce,
bytes calldata signature
)
external
returns (bool success);
function batchAddFeeBalances(
bytes32[] calldata batch
)
external;
}
| 37,629 |
87 | // Assigns a new address to act as the CFO. Only available to the current CEO./newCfo The address of the new CFO | function setCfo(address payable newCfo) public onlyCEO {
checkControlAddress(newCfo);
emit CFOTransferred(cfoAddress, newCfo);
cfoAddress = newCfo;
}
| function setCfo(address payable newCfo) public onlyCEO {
checkControlAddress(newCfo);
emit CFOTransferred(cfoAddress, newCfo);
cfoAddress = newCfo;
}
| 18,112 |
1 | // ==========EVENTS========== | event SharesIssued(address indexed holder, uint256 sharesIssued);
event CollectedReward(address indexed collector, uint256 amount, address indexed vehicle);
event NewShareholder(address indexed shareholder);
event RewardIssued(address indexed holderAddress, uint256 rewardShare);
event RewardsDepleted(uint256 _holderno, uint256 rewardBalance);
event TargetVehicleFunded(address indexed targetVehicle, uint256 targetAmount);
| event SharesIssued(address indexed holder, uint256 sharesIssued);
event CollectedReward(address indexed collector, uint256 amount, address indexed vehicle);
event NewShareholder(address indexed shareholder);
event RewardIssued(address indexed holderAddress, uint256 rewardShare);
event RewardsDepleted(uint256 _holderno, uint256 rewardBalance);
event TargetVehicleFunded(address indexed targetVehicle, uint256 targetAmount);
| 9,301 |
148 | // Safe jungle transfer function, just in case if rounding error causes pool to not have enough JUNGLEs. | function safeJungleTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 jungleBal = jungle.balanceOf(address(this));
if (_amount > jungleBal) {
jungle.transfer(_to, jungleBal);
} else {
jungle.transfer(_to, _amount);
}
}
| function safeJungleTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 jungleBal = jungle.balanceOf(address(this));
if (_amount > jungleBal) {
jungle.transfer(_to, jungleBal);
} else {
jungle.transfer(_to, _amount);
}
}
| 12,006 |
4 | // The buffer starts at idx 1 in the container (0 is length) | buffer := add(container, 0x20)
| buffer := add(container, 0x20)
| 53,078 |
50 | // precalculated hashes - see https:github.com/ethereum/solidity/issues/4024 keccak256("ERC777TokensSender") | bytes32 constant internal ERC777_TOKENS_SENDER_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
| bytes32 constant internal ERC777_TOKENS_SENDER_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
| 6,295 |
129 | // Whether `a` is less than or equal to `b`. a an int256. b a FixedPoint.Signed.return True if `a <= b`, or False. / | function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
| function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
| 17,442 |
346 | // Calculates a timelocked withdrawal duration and credit consumption./from The user who is withdrawing/amount The amount the user is withdrawing/controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship)/ return durationSeconds The duration of the timelock in seconds | function calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
external override
returns (
uint256 durationSeconds,
uint256 burnedCredit
)
| function calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
external override
returns (
uint256 durationSeconds,
uint256 burnedCredit
)
| 57,959 |
166 | // RecoveryManager Module to manage the recovery of a wallet owner.Recovery is executed by a consensus of the wallet's guardians and takes24 hours before it can be finalized. Once finalised the ownership of the walletis transfered to a new address. Julien Niset - <julien@argent.im> Olivier Van Den Biggelaar - <olivier@argent.im> / | contract RecoveryManager is BaseModule, RelayerModuleV2 {
bytes32 constant NAME = "RecoveryManager";
bytes4 constant internal EXECUTE_RECOVERY_PREFIX = bytes4(keccak256("executeRecovery(address,address)"));
bytes4 constant internal FINALIZE_RECOVERY_PREFIX = bytes4(keccak256("finalizeRecovery(address)"));
bytes4 constant internal CANCEL_RECOVERY_PREFIX = bytes4(keccak256("cancelRecovery(address)"));
bytes4 constant internal TRANSFER_OWNERSHIP_PREFIX = bytes4(keccak256("transferOwnership(address,address)"));
struct RecoveryConfig {
address recovery;
uint64 executeAfter;
uint32 guardianCount;
}
// Wallet specific storage
mapping (address => RecoveryConfig) internal recoveryConfigs;
// Recovery period
uint256 internal recoveryPeriod;
// Lock period
uint256 internal lockPeriod;
// Security period used for (non-recovery) ownership transfer
uint256 public securityPeriod;
// Security window used for (non-recovery) ownership transfer
uint256 public securityWindow;
// Location of the Guardian storage
GuardianStorage internal guardianStorage;
// *************** Events *************************** //
event RecoveryExecuted(address indexed wallet, address indexed _recovery, uint64 executeAfter);
event RecoveryFinalized(address indexed wallet, address indexed _recovery);
event RecoveryCanceled(address indexed wallet, address indexed _recovery);
event OwnershipTransfered(address indexed wallet, address indexed _newOwner);
// *************** Modifiers ************************ //
/**
* @dev Throws if there is no ongoing recovery procedure.
*/
modifier onlyWhenRecovery(BaseWallet _wallet) {
require(recoveryConfigs[address(_wallet)].executeAfter > 0, "RM: there must be an ongoing recovery");
_;
}
/**
* @dev Throws if there is an ongoing recovery procedure.
*/
modifier notWhenRecovery(BaseWallet _wallet) {
require(recoveryConfigs[address(_wallet)].executeAfter == 0, "RM: there cannot be an ongoing recovery");
_;
}
// *************** Constructor ************************ //
constructor(
ModuleRegistry _registry,
GuardianStorage _guardianStorage,
uint256 _recoveryPeriod,
uint256 _lockPeriod,
uint256 _securityPeriod,
uint256 _securityWindow
)
BaseModule(_registry, _guardianStorage, NAME)
public
{
require(_lockPeriod >= _recoveryPeriod && _recoveryPeriod >= _securityPeriod + _securityWindow, "RM: insecure security periods");
guardianStorage = _guardianStorage;
recoveryPeriod = _recoveryPeriod;
lockPeriod = _lockPeriod;
securityPeriod = _securityPeriod;
securityWindow = _securityWindow;
}
// *************** External functions ************************ //
/**
* @dev Lets the guardians start the execution of the recovery procedure.
* Once triggered the recovery is pending for the security period before it can
* be finalised.
* Must be confirmed by N guardians, where N = ((Nb Guardian + 1) / 2).
* @param _wallet The target wallet.
* @param _recovery The address to which ownership should be transferred.
*/
function executeRecovery(BaseWallet _wallet, address _recovery) external onlyExecute notWhenRecovery(_wallet) {
require(_recovery != address(0), "RM: recovery address cannot be null");
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
config.recovery = _recovery;
config.executeAfter = uint64(now + recoveryPeriod); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
config.guardianCount = uint32(guardianStorage.guardianCount(_wallet)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
guardianStorage.setLock(_wallet, now + lockPeriod); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit RecoveryExecuted(address(_wallet), _recovery, config.executeAfter);
}
/**
* @dev Finalizes an ongoing recovery procedure if the security period is over.
* The method is public and callable by anyone to enable orchestration.
* @param _wallet The target wallet.
*/
function finalizeRecovery(BaseWallet _wallet) external onlyWhenRecovery(_wallet) {
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(uint64(now) > config.executeAfter, "RM: the recovery period is not over yet");
_wallet.setOwner(config.recovery);
emit RecoveryFinalized(address(_wallet), config.recovery);
guardianStorage.setLock(_wallet, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
delete recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Lets the owner cancel an ongoing recovery procedure.
* Must be confirmed by N guardians, where N = ((Nb Guardian + 1) / 2) - 1.
* @param _wallet The target wallet.
*/
function cancelRecovery(BaseWallet _wallet) external onlyExecute onlyWhenRecovery(_wallet) {
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit RecoveryCanceled(address(_wallet), config.recovery);
guardianStorage.setLock(_wallet, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
delete recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Lets the owner start the execution of the ownership transfer procedure.
* Once triggered the ownership transfer is pending for the security period before it can
* be finalised.
* @param _wallet The target wallet.
* @param _newOwner The address to which ownership should be transferred.
*/
function transferOwnership(BaseWallet _wallet, address _newOwner) external onlyExecute onlyWhenUnlocked(_wallet) {
require(_newOwner != address(0), "RM: new owner address cannot be null");
_wallet.setOwner(_newOwner);
emit OwnershipTransfered(address(_wallet), _newOwner);
}
/**
* @dev Gets the details of the ongoing recovery procedure if any.
* @param _wallet The target wallet.
*/
function getRecovery(BaseWallet _wallet) public view returns(address _address, uint64 _executeAfter, uint32 _guardianCount) {
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return (config.recovery, config.executeAfter, config.guardianCount);
}
// *************** Implementation of RelayerModule methods ********************* //
function validateSignatures(
BaseWallet _wallet,
bytes memory _data,
bytes32 _signHash,
bytes memory _signatures
)
internal view returns (bool)
{
bytes4 functionSignature = functionPrefix(_data);
if (functionSignature == TRANSFER_OWNERSHIP_PREFIX) {
return validateSignatures(_wallet, _signHash, _signatures, OwnerSignature.Required);
} else if (functionSignature == EXECUTE_RECOVERY_PREFIX) {
return validateSignatures(_wallet, _signHash, _signatures, OwnerSignature.Disallowed);
} else if (functionSignature == CANCEL_RECOVERY_PREFIX) {
return validateSignatures(_wallet, _signHash, _signatures, OwnerSignature.Optional);
}
}
function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) public view returns (uint256) {
bytes4 methodId = functionPrefix(_data);
if (methodId == EXECUTE_RECOVERY_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint walletGuardians = guardianStorage.guardianCount(_wallet); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(walletGuardians > 0, "RM: no guardians set on wallet");
return SafeMath.ceil(walletGuardians, 2);
}
if (methodId == FINALIZE_RECOVERY_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return 0;
}
if (methodId == CANCEL_RECOVERY_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return SafeMath.ceil(recoveryConfigs[address(_wallet)].guardianCount + 1, 2); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
if (methodId == TRANSFER_OWNERSHIP_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint majorityGuardians = SafeMath.ceil(guardianStorage.guardianCount(_wallet), 2); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return SafeMath.add(majorityGuardians, 1);
}
revert("RM: unknown method");
}
} | contract RecoveryManager is BaseModule, RelayerModuleV2 {
bytes32 constant NAME = "RecoveryManager";
bytes4 constant internal EXECUTE_RECOVERY_PREFIX = bytes4(keccak256("executeRecovery(address,address)"));
bytes4 constant internal FINALIZE_RECOVERY_PREFIX = bytes4(keccak256("finalizeRecovery(address)"));
bytes4 constant internal CANCEL_RECOVERY_PREFIX = bytes4(keccak256("cancelRecovery(address)"));
bytes4 constant internal TRANSFER_OWNERSHIP_PREFIX = bytes4(keccak256("transferOwnership(address,address)"));
struct RecoveryConfig {
address recovery;
uint64 executeAfter;
uint32 guardianCount;
}
// Wallet specific storage
mapping (address => RecoveryConfig) internal recoveryConfigs;
// Recovery period
uint256 internal recoveryPeriod;
// Lock period
uint256 internal lockPeriod;
// Security period used for (non-recovery) ownership transfer
uint256 public securityPeriod;
// Security window used for (non-recovery) ownership transfer
uint256 public securityWindow;
// Location of the Guardian storage
GuardianStorage internal guardianStorage;
// *************** Events *************************** //
event RecoveryExecuted(address indexed wallet, address indexed _recovery, uint64 executeAfter);
event RecoveryFinalized(address indexed wallet, address indexed _recovery);
event RecoveryCanceled(address indexed wallet, address indexed _recovery);
event OwnershipTransfered(address indexed wallet, address indexed _newOwner);
// *************** Modifiers ************************ //
/**
* @dev Throws if there is no ongoing recovery procedure.
*/
modifier onlyWhenRecovery(BaseWallet _wallet) {
require(recoveryConfigs[address(_wallet)].executeAfter > 0, "RM: there must be an ongoing recovery");
_;
}
/**
* @dev Throws if there is an ongoing recovery procedure.
*/
modifier notWhenRecovery(BaseWallet _wallet) {
require(recoveryConfigs[address(_wallet)].executeAfter == 0, "RM: there cannot be an ongoing recovery");
_;
}
// *************** Constructor ************************ //
constructor(
ModuleRegistry _registry,
GuardianStorage _guardianStorage,
uint256 _recoveryPeriod,
uint256 _lockPeriod,
uint256 _securityPeriod,
uint256 _securityWindow
)
BaseModule(_registry, _guardianStorage, NAME)
public
{
require(_lockPeriod >= _recoveryPeriod && _recoveryPeriod >= _securityPeriod + _securityWindow, "RM: insecure security periods");
guardianStorage = _guardianStorage;
recoveryPeriod = _recoveryPeriod;
lockPeriod = _lockPeriod;
securityPeriod = _securityPeriod;
securityWindow = _securityWindow;
}
// *************** External functions ************************ //
/**
* @dev Lets the guardians start the execution of the recovery procedure.
* Once triggered the recovery is pending for the security period before it can
* be finalised.
* Must be confirmed by N guardians, where N = ((Nb Guardian + 1) / 2).
* @param _wallet The target wallet.
* @param _recovery The address to which ownership should be transferred.
*/
function executeRecovery(BaseWallet _wallet, address _recovery) external onlyExecute notWhenRecovery(_wallet) {
require(_recovery != address(0), "RM: recovery address cannot be null");
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
config.recovery = _recovery;
config.executeAfter = uint64(now + recoveryPeriod); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
config.guardianCount = uint32(guardianStorage.guardianCount(_wallet)); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
guardianStorage.setLock(_wallet, now + lockPeriod); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit RecoveryExecuted(address(_wallet), _recovery, config.executeAfter);
}
/**
* @dev Finalizes an ongoing recovery procedure if the security period is over.
* The method is public and callable by anyone to enable orchestration.
* @param _wallet The target wallet.
*/
function finalizeRecovery(BaseWallet _wallet) external onlyWhenRecovery(_wallet) {
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(uint64(now) > config.executeAfter, "RM: the recovery period is not over yet");
_wallet.setOwner(config.recovery);
emit RecoveryFinalized(address(_wallet), config.recovery);
guardianStorage.setLock(_wallet, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
delete recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Lets the owner cancel an ongoing recovery procedure.
* Must be confirmed by N guardians, where N = ((Nb Guardian + 1) / 2) - 1.
* @param _wallet The target wallet.
*/
function cancelRecovery(BaseWallet _wallet) external onlyExecute onlyWhenRecovery(_wallet) {
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit RecoveryCanceled(address(_wallet), config.recovery);
guardianStorage.setLock(_wallet, 0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
delete recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Lets the owner start the execution of the ownership transfer procedure.
* Once triggered the ownership transfer is pending for the security period before it can
* be finalised.
* @param _wallet The target wallet.
* @param _newOwner The address to which ownership should be transferred.
*/
function transferOwnership(BaseWallet _wallet, address _newOwner) external onlyExecute onlyWhenUnlocked(_wallet) {
require(_newOwner != address(0), "RM: new owner address cannot be null");
_wallet.setOwner(_newOwner);
emit OwnershipTransfered(address(_wallet), _newOwner);
}
/**
* @dev Gets the details of the ongoing recovery procedure if any.
* @param _wallet The target wallet.
*/
function getRecovery(BaseWallet _wallet) public view returns(address _address, uint64 _executeAfter, uint32 _guardianCount) {
RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return (config.recovery, config.executeAfter, config.guardianCount);
}
// *************** Implementation of RelayerModule methods ********************* //
function validateSignatures(
BaseWallet _wallet,
bytes memory _data,
bytes32 _signHash,
bytes memory _signatures
)
internal view returns (bool)
{
bytes4 functionSignature = functionPrefix(_data);
if (functionSignature == TRANSFER_OWNERSHIP_PREFIX) {
return validateSignatures(_wallet, _signHash, _signatures, OwnerSignature.Required);
} else if (functionSignature == EXECUTE_RECOVERY_PREFIX) {
return validateSignatures(_wallet, _signHash, _signatures, OwnerSignature.Disallowed);
} else if (functionSignature == CANCEL_RECOVERY_PREFIX) {
return validateSignatures(_wallet, _signHash, _signatures, OwnerSignature.Optional);
}
}
function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) public view returns (uint256) {
bytes4 methodId = functionPrefix(_data);
if (methodId == EXECUTE_RECOVERY_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint walletGuardians = guardianStorage.guardianCount(_wallet); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(walletGuardians > 0, "RM: no guardians set on wallet");
return SafeMath.ceil(walletGuardians, 2);
}
if (methodId == FINALIZE_RECOVERY_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return 0;
}
if (methodId == CANCEL_RECOVERY_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return SafeMath.ceil(recoveryConfigs[address(_wallet)].guardianCount + 1, 2); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
if (methodId == TRANSFER_OWNERSHIP_PREFIX) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint majorityGuardians = SafeMath.ceil(guardianStorage.guardianCount(_wallet), 2); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return SafeMath.add(majorityGuardians, 1);
}
revert("RM: unknown method");
}
} | 29,213 |
47 | // 是否要新增: 當在二級市場活動票券成交後,買家需向賣方支付購票費用。 | t.owner.transfer(t.value - tradeFee);
| t.owner.transfer(t.value - tradeFee);
| 30,266 |
36 | // Validate withdraw parameters. amount The number of tokens to withdraw. until The date until which the tokens were staked./ | function _validateWithdrawParams(uint96 amount, uint256 until) internal view {
require(amount > 0, "Staking::withdraw: amount of tokens to be withdrawn needs to be bigger than 0");
uint96 balance = getPriorUserStakeByDate(msg.sender, until, block.number - 1);
require(amount <= balance, "Staking::withdraw: not enough balance");
}
| function _validateWithdrawParams(uint96 amount, uint256 until) internal view {
require(amount > 0, "Staking::withdraw: amount of tokens to be withdrawn needs to be bigger than 0");
uint96 balance = getPriorUserStakeByDate(msg.sender, until, block.number - 1);
require(amount <= balance, "Staking::withdraw: not enough balance");
}
| 39,342 |
1 | // 68 = 4-byte selector 0x08c379a0 + 32 bytes offset + 32 bytes length | if (data.length >= 68 && data[0] == "\x08" && data[1] == "\xc3" && data[2] == "\x79" && data[3] == "\xa0") {
string memory reason;
| if (data.length >= 68 && data[0] == "\x08" && data[1] == "\xc3" && data[2] == "\x79" && data[3] == "\xa0") {
string memory reason;
| 19,093 |
12 | // Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. / solhint-disable-next-line func-name-mixedcase | function DOMAIN_SEPARATOR() external view returns (bytes32);
| function DOMAIN_SEPARATOR() external view returns (bytes32);
| 2,216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.