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
|
|---|---|---|---|---|
75
|
// Stores the data for the roll (spin)
|
struct rollData {
uint win;
uint loss;
uint jp;
}
|
struct rollData {
uint win;
uint loss;
uint jp;
}
| 69,976
|
75
|
// a case of a user/account moving funds to this contract account
|
vaults[id].transferFrom(
sender,
address(this),
estimatedShares
); //move yv shares
withdrawn = withdrawn.add(
vaults[id].withdraw(estimatedShares)
); //get the bearing tokens corresponding to the estimaded amount of shares
|
vaults[id].transferFrom(
sender,
address(this),
estimatedShares
); //move yv shares
withdrawn = withdrawn.add(
vaults[id].withdraw(estimatedShares)
); //get the bearing tokens corresponding to the estimaded amount of shares
| 29,051
|
22
|
// The loanRemainder will be the amount of underlyingTokens that are needed from the original transaction caller in order to pay the flash swap. IMPORTANT: THIS IS EFFECTIVELY THE PREMIUM PAID IN UNDERLYINGTOKENS TO PURCHASE THE OPTIONTOKEN.
|
uint256 loanRemainder;
|
uint256 loanRemainder;
| 34,036
|
110
|
// SynthetixEscrow interface /
|
interface ISynthetixEscrow {
function balanceOf(address account) public view returns (uint);
function appendVestingEntry(address account, uint quantity) public;
}
|
interface ISynthetixEscrow {
function balanceOf(address account) public view returns (uint);
function appendVestingEntry(address account, uint quantity) public;
}
| 5,698
|
35
|
// collatteral[_minter].investor = _minter;
|
collatteral[_minter].bUSDValue = collatteral[_minter].bUSDValue.add(_value);
collatteral[_minter].USDbValueinBYN = collatteral[_minter].USDbValueinBYN.add(amountInBYN);
collatteral[_minter].collatteralValue = collatteral[_minter].collatteralValue.add(collatteralValueInBYN);
collatteral[_minter].currentCollatteralRatio =(collatteral[_minter].collatteralValue.mul(100)).div(collatteral[_minter].USDbValueinBYN);
collatteral[_minter].rewardClaimTime = rewardClaimTime;//.add(3 minutes);
require(collatteralValueInBYN <= beyond.balanceCheck(_minter));
totalMintedUSDb = totalMintedUSDb.add(_value);
totalStackedBYN = totalStackedBYN.add(collatteralValueInBYN);
|
collatteral[_minter].bUSDValue = collatteral[_minter].bUSDValue.add(_value);
collatteral[_minter].USDbValueinBYN = collatteral[_minter].USDbValueinBYN.add(amountInBYN);
collatteral[_minter].collatteralValue = collatteral[_minter].collatteralValue.add(collatteralValueInBYN);
collatteral[_minter].currentCollatteralRatio =(collatteral[_minter].collatteralValue.mul(100)).div(collatteral[_minter].USDbValueinBYN);
collatteral[_minter].rewardClaimTime = rewardClaimTime;//.add(3 minutes);
require(collatteralValueInBYN <= beyond.balanceCheck(_minter));
totalMintedUSDb = totalMintedUSDb.add(_value);
totalStackedBYN = totalStackedBYN.add(collatteralValueInBYN);
| 5,089
|
16
|
// Inserts a 32 bit unsigned integer shifted by an offset into a 256 bit word, replacing the old value. Returnsthe new word. Assumes `value` only uses its least significant 32 bits, otherwise it may overwrite sibling bytes. /
|
function insertUint32(
bytes32 word,
uint256 value,
uint256 offset
|
function insertUint32(
bytes32 word,
uint256 value,
uint256 offset
| 25,406
|
27
|
// Set the deployer of this contract/newDeployer The address of the new deployer
|
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
|
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
| 21,867
|
8
|
// Use token address ETH_TOKEN_ADDRESS for ether/Trade from src to dest token and sends dest token to destAddress/trader Address of the taker side of this trade/src Source token/srcAmount Amount of src tokens in twei/dest Destination token/destAddress Address to send tokens to/maxDestAmount A limit on the amount of dest tokens in twei/minConversionRate The minimal conversion rate. If actual rate is lower, trade reverts/platformWallet Platform wallet address for receiving fees/platformFeeBps Part of the trade that is allocated as fee to platform wallet. Ex: 1000 = 10%/hint Advanced instructions for running the trade / return destAmount Amount of actual dest tokens in twei
|
function tradeWithHintAndFee(
address payable trader,
IERC20Ext src,
uint256 srcAmount,
IERC20Ext dest,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable platformWallet,
uint256 platformFeeBps,
|
function tradeWithHintAndFee(
address payable trader,
IERC20Ext src,
uint256 srcAmount,
IERC20Ext dest,
address payable destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address payable platformWallet,
uint256 platformFeeBps,
| 47,463
|
64
|
// Recover ERC20 tokens that were accidentally sent to this smart contract./token The token contract. Can be anything. This contract should not hold ERC20 tokens./to The address to send the tokens to./value The number of tokens to transfer to `to`.
|
function recover(address token, address to, uint256 value) external onlyOwner nonReentrant {
token.safeTransfer(to, value);
}
|
function recover(address token, address to, uint256 value) external onlyOwner nonReentrant {
token.safeTransfer(to, value);
}
| 70,348
|
59
|
// Internal function in which `amount` of ERC20 `token` is transferred from `msg.sender` to the InvestmentDelegation-type contract`delegationShare`, with the resulting shares credited to `depositor`.return shares The amount of new shares in `delegationShare` that have been credited to the `depositor`. /
|
function _depositInto(address depositor, IDelegationShare delegationShare, IERC20 token, uint256 amount)
internal
returns (uint256 shares)
|
function _depositInto(address depositor, IDelegationShare delegationShare, IERC20 token, uint256 amount)
internal
returns (uint256 shares)
| 3,934
|
6
|
// Count all NFTs assigned to an owner
|
function balanceOf(address _owner) public view virtual returns (uint256);
|
function balanceOf(address _owner) public view virtual returns (uint256);
| 15,824
|
4
|
// AraProxy Gives the possibility to delegate any call to a foreign implementation. /
|
contract AraProxy {
bytes32 private constant registryPosition_ = keccak256("io.ara.proxy.registry");
bytes32 private constant implementationPosition_ = keccak256("io.ara.proxy.implementation");
modifier restricted() {
bytes32 registryPosition = registryPosition_;
address registryAddress;
assembly {
registryAddress := sload(registryPosition)
}
require(
msg.sender == registryAddress,
"Only the AraRegistry can upgrade this proxy."
);
_;
}
/**
* @dev the constructor sets the AraRegistry address
*/
constructor(address _registryAddress, address _implementationAddress) public {
bytes32 registryPosition = registryPosition_;
bytes32 implementationPosition = implementationPosition_;
assembly {
sstore(registryPosition, _registryAddress)
sstore(implementationPosition, _implementationAddress)
}
}
function setImplementation(address _newImplementation) public restricted {
require(_newImplementation != address(0));
bytes32 implementationPosition = implementationPosition_;
assembly {
sstore(implementationPosition, _newImplementation)
}
}
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable public {
bytes32 implementationPosition = implementationPosition_;
address _impl;
assembly {
_impl := sload(implementationPosition)
}
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
|
contract AraProxy {
bytes32 private constant registryPosition_ = keccak256("io.ara.proxy.registry");
bytes32 private constant implementationPosition_ = keccak256("io.ara.proxy.implementation");
modifier restricted() {
bytes32 registryPosition = registryPosition_;
address registryAddress;
assembly {
registryAddress := sload(registryPosition)
}
require(
msg.sender == registryAddress,
"Only the AraRegistry can upgrade this proxy."
);
_;
}
/**
* @dev the constructor sets the AraRegistry address
*/
constructor(address _registryAddress, address _implementationAddress) public {
bytes32 registryPosition = registryPosition_;
bytes32 implementationPosition = implementationPosition_;
assembly {
sstore(registryPosition, _registryAddress)
sstore(implementationPosition, _implementationAddress)
}
}
function setImplementation(address _newImplementation) public restricted {
require(_newImplementation != address(0));
bytes32 implementationPosition = implementationPosition_;
assembly {
sstore(implementationPosition, _newImplementation)
}
}
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () payable public {
bytes32 implementationPosition = implementationPosition_;
address _impl;
assembly {
_impl := sload(implementationPosition)
}
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
| 31,180
|
519
|
// res += valcoefficients[120].
|
res := addmod(res,
mulmod(val, /*coefficients[120]*/ mload(0x1300), PRIME),
PRIME)
|
res := addmod(res,
mulmod(val, /*coefficients[120]*/ mload(0x1300), PRIME),
PRIME)
| 19,688
|
30
|
// Generates supply for days with static supply_investmentDay investemnt day index (1-30)/
|
function _generateStaticSupply(uint256 _investmentDay ) internal {
dailyTotalSupply[_investmentDay] = dailyMinSupply[_investmentDay] * CROP_PER_TF;
g.totalTransferTokens += dailyTotalSupply[_investmentDay];
g.generatedDays++;
g.generationDayBuffer = 0;
g.generationTimeout = 0;
emit GeneratedStaticSupply(_investmentDay, dailyTotalSupply[_investmentDay]);
}
|
function _generateStaticSupply(uint256 _investmentDay ) internal {
dailyTotalSupply[_investmentDay] = dailyMinSupply[_investmentDay] * CROP_PER_TF;
g.totalTransferTokens += dailyTotalSupply[_investmentDay];
g.generatedDays++;
g.generationDayBuffer = 0;
g.generationTimeout = 0;
emit GeneratedStaticSupply(_investmentDay, dailyTotalSupply[_investmentDay]);
}
| 31,422
|
48
|
// checks if voting window is open
|
modifier windowOpen(uint256 startTimestamp) {
require(
block.timestamp > startTimestamp &&
// voting window is one day long, starts at deadline and ends at deadline + 1 days
block.timestamp < startTimestamp + 1 days
);
_;
}
|
modifier windowOpen(uint256 startTimestamp) {
require(
block.timestamp > startTimestamp &&
// voting window is one day long, starts at deadline and ends at deadline + 1 days
block.timestamp < startTimestamp + 1 days
);
_;
}
| 26,579
|
54
|
// We use a single lock for the whole contract. /
|
bool private reentrancy_lock = false;
|
bool private reentrancy_lock = false;
| 27,223
|
14
|
// Gewinner basierend auf den meisten erfüllten Bedingungen auswählen
|
return (challengerCompleted >= runnerUpCompleted) ? challenges[_challengeId].challenger : challenges[_challengeId].runnerUp;
|
return (challengerCompleted >= runnerUpCompleted) ? challenges[_challengeId].challenger : challenges[_challengeId].runnerUp;
| 2,935
|
11
|
// Random prize roller/
|
library RandomPrize {
/**
* @dev Pattern to manage prize pool and roll to prize map
*/
struct PrizePool {
ProvablyFair.RollState state;
uint256[] prizes;
uint256[] rollToPrizeMap;
}
/**
* @dev rolls the dice and assigns the prize
*/
function roll(
PrizePool memory pool,
string memory clientSeed,
bool saveSeed
) internal view returns(uint256) {
// provably fair roller
uint256 _roll = ProvablyFair.roll(pool.state, clientSeed, saveSeed);
//this is the determined prize
uint256 prize;
uint256 less;
uint256 difference = 0;
for (uint8 i = 0; i < pool.rollToPrizeMap.length; i++) {
if (i > 0 && pool.rollToPrizeMap[i - 1] > 0) {
difference = pool.rollToPrizeMap[i - 1];
}
// if the roll value is not zero
// and the roll is less than the roll value
if (prize == 0
&& pool.rollToPrizeMap[i] > 0
&& _roll <= pool.rollToPrizeMap[i]
) {
//set the respective prize
prize = pool.prizes[i];
//get what we need to less
less = pool.rollToPrizeMap[i] - difference;
//set this now to zero so it can't be rolled for again
pool.rollToPrizeMap[i] = 0;
//less the max in the state
pool.state.max -= less;
}
//if we have a prize, then we should just less the map range
if (prize > 0 && pool.rollToPrizeMap[i] > 0) {
pool.rollToPrizeMap[i] -= less;
}
}
return prize;
}
}
|
library RandomPrize {
/**
* @dev Pattern to manage prize pool and roll to prize map
*/
struct PrizePool {
ProvablyFair.RollState state;
uint256[] prizes;
uint256[] rollToPrizeMap;
}
/**
* @dev rolls the dice and assigns the prize
*/
function roll(
PrizePool memory pool,
string memory clientSeed,
bool saveSeed
) internal view returns(uint256) {
// provably fair roller
uint256 _roll = ProvablyFair.roll(pool.state, clientSeed, saveSeed);
//this is the determined prize
uint256 prize;
uint256 less;
uint256 difference = 0;
for (uint8 i = 0; i < pool.rollToPrizeMap.length; i++) {
if (i > 0 && pool.rollToPrizeMap[i - 1] > 0) {
difference = pool.rollToPrizeMap[i - 1];
}
// if the roll value is not zero
// and the roll is less than the roll value
if (prize == 0
&& pool.rollToPrizeMap[i] > 0
&& _roll <= pool.rollToPrizeMap[i]
) {
//set the respective prize
prize = pool.prizes[i];
//get what we need to less
less = pool.rollToPrizeMap[i] - difference;
//set this now to zero so it can't be rolled for again
pool.rollToPrizeMap[i] = 0;
//less the max in the state
pool.state.max -= less;
}
//if we have a prize, then we should just less the map range
if (prize > 0 && pool.rollToPrizeMap[i] > 0) {
pool.rollToPrizeMap[i] -= less;
}
}
return prize;
}
}
| 39,625
|
89
|
// Compiler will pack this into a single 256bit word.
|
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
|
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
| 52,566
|
0
|
// mapping (address=>string) SCMap;
|
address[] public unclaimedServices;
address[] public unverifiedClaims;
address[] public verifiedClaims;
event ClaimVerified(address addr, bool confirm);
event Claims(address[] claims);
event ClaimLength(uint256 claimLength);
event ClaimAdded(address addr);
event Check(address addr);
address providerAddr;
|
address[] public unclaimedServices;
address[] public unverifiedClaims;
address[] public verifiedClaims;
event ClaimVerified(address addr, bool confirm);
event Claims(address[] claims);
event ClaimLength(uint256 claimLength);
event ClaimAdded(address addr);
event Check(address addr);
address providerAddr;
| 34,529
|
356
|
// ========== REDEEM REALLOCATION ========== // Redeem vault shares after reallocation has been processed for the vault Requirements:- Can only be invoked by vaultvaultStrategies Array of vault strategy addresses depositProportions Values representing how the vault has deposited it's withdrawn sharesindex Index at which the reallocation was perofmed /
|
function redeemReallocation(
address[] memory vaultStrategies,
uint256 depositProportions,
uint256 index
|
function redeemReallocation(
address[] memory vaultStrategies,
uint256 depositProportions,
uint256 index
| 34,816
|
144
|
// Crowdsale data store separated from logic
|
VIVACrowdsaleData public data;
|
VIVACrowdsaleData public data;
| 15,545
|
220
|
// enables a reserve to be used as collateral_self the reserve object_baseLTVasCollateral the loan to value of the asset when used as collateral_liquidationThreshold the threshold at which loans using this asset as collateral will be considered undercollateralized_liquidationBonus the bonus liquidators receive to liquidate this asset/
|
) external {
require(
_self.usageAsCollateralEnabled == false,
"Reserve is already enabled as collateral"
);
_self.usageAsCollateralEnabled = true;
_self.baseLTVasCollateral = _baseLTVasCollateral;
_self.liquidationThreshold = _liquidationThreshold;
_self.liquidationBonus = _liquidationBonus;
if (_self.lastLiquidityCumulativeIndex == 0)
_self.lastLiquidityCumulativeIndex = WadRayMath.ray();
}
|
) external {
require(
_self.usageAsCollateralEnabled == false,
"Reserve is already enabled as collateral"
);
_self.usageAsCollateralEnabled = true;
_self.baseLTVasCollateral = _baseLTVasCollateral;
_self.liquidationThreshold = _liquidationThreshold;
_self.liquidationBonus = _liquidationBonus;
if (_self.lastLiquidityCumulativeIndex == 0)
_self.lastLiquidityCumulativeIndex = WadRayMath.ray();
}
| 55,874
|
422
|
// Exponentiation-by-squaring
|
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n.div(2);
} else { // if (n % 2 != 0)
|
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n.div(2);
} else { // if (n % 2 != 0)
| 59,856
|
17
|
// Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. This will revert due to insufficient balance or insufficient allowance. This function returns the actual amount received, which may be less than `amount` if there is a fee attached to the transfer.Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. /
|
function doTransferIn(address from, uint tokenId) internal override returns (uint) {
ICERC721Moonbird token = ICERC721Moonbird(underlying);
uint balanceBefore = token.balanceOf(address(this));
if (reserves[tokenId] == address(0)) {
token.transferFrom(from, address(this), tokenId);
} else {
require(reserves[tokenId] == from, "invalid supply");
balanceBefore -= 1;
}
userTokens[from].push(tokenId);
// bool success;
// assembly {
// switch returndatasize()
// case 0 { // This is a non-standard ERC-20
// success := not(0) // set success to true
// }
// case 32 { // This is a compliant ERC-20
// returndatacopy(0, 0, 32)
// success := mload(0) // Set `success = returndata` of external call
// }
// default { // This is an excessively non-compliant ERC-20, revert.
// revert(0, 0)
// }
// }
// require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
|
function doTransferIn(address from, uint tokenId) internal override returns (uint) {
ICERC721Moonbird token = ICERC721Moonbird(underlying);
uint balanceBefore = token.balanceOf(address(this));
if (reserves[tokenId] == address(0)) {
token.transferFrom(from, address(this), tokenId);
} else {
require(reserves[tokenId] == from, "invalid supply");
balanceBefore -= 1;
}
userTokens[from].push(tokenId);
// bool success;
// assembly {
// switch returndatasize()
// case 0 { // This is a non-standard ERC-20
// success := not(0) // set success to true
// }
// case 32 { // This is a compliant ERC-20
// returndatacopy(0, 0, 32)
// success := mload(0) // Set `success = returndata` of external call
// }
// default { // This is an excessively non-compliant ERC-20, revert.
// revert(0, 0)
// }
// }
// require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
| 11,833
|
62
|
// Called by a owner to pause, triggers stopped state./
|
function _pause() internal {
_paused = true;
emit Paused(_msgSender());
}
|
function _pause() internal {
_paused = true;
emit Paused(_msgSender());
}
| 10,273
|
4
|
// Called to validate the cancellation of a proposal governance governance contract to fetch proposals from proposalId Id of the generic proposal user entity initiating the cancellationreturn boolean, true if can be cancelled /
|
{
governance;
proposalId;
user;
return isCancellationAllowed;
}
|
{
governance;
proposalId;
user;
return isCancellationAllowed;
}
| 40,711
|
16
|
// generic description of an outcome. Outcomes are only accepted if/ accompanied by a valid proof.
|
struct TranscriptOutcome {
/// @dev identifies the participant the outcome affects.
address participant;
LibTranscript.Outcome outcome;
/// @dev proof for the node chosen by the participant
ChoiceProof proof;
/// @dev generic data blob which will generaly describe the situation
/// resulting from the choice proven by the outcome. This data is emitted in
/// logs but not stored on chain.
bytes data;
/// @dev the stack position of the set of choices available to participant for there next
/// commitment. typically, the data will provide context for these.
uint256 choiceLeafIndex;
}
|
struct TranscriptOutcome {
/// @dev identifies the participant the outcome affects.
address participant;
LibTranscript.Outcome outcome;
/// @dev proof for the node chosen by the participant
ChoiceProof proof;
/// @dev generic data blob which will generaly describe the situation
/// resulting from the choice proven by the outcome. This data is emitted in
/// logs but not stored on chain.
bytes data;
/// @dev the stack position of the set of choices available to participant for there next
/// commitment. typically, the data will provide context for these.
uint256 choiceLeafIndex;
}
| 11,747
|
57
|
// `msg.sender` approves `_spender` to spend `_amount` tokens on/its behalf. This is a modified version of the ERC20 approve function/to be a little bit safer/_spender The address of the account able to transfer the tokens/_amount The amount of tokens to be approved for transfer/ return True if the approval was successful
|
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
|
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
| 18,441
|
176
|
// all expected amounts must be positive
|
require(_expectedAmounts[i]>=0);
|
require(_expectedAmounts[i]>=0);
| 68,711
|
26
|
// Holds the amount and date of a given balance lock.
|
struct BalanceLock {
uint256 amount;
uint256 unlockDate;
}
|
struct BalanceLock {
uint256 amount;
uint256 unlockDate;
}
| 34,866
|
31
|
// Assign allowance to an specified address to use the owner balance_spender The address to be allowed to spend._value The amount to be allowed./
|
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
|
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 41,983
|
2
|
// Creates a PoolManagerLogic contract.This function is meant to be called by PoolFactory or CappedPoolFactory.Check _performanceFee in the calling contract._poolAddress address of the pool._manager address of the pool's manager._performanceFee the pool's performance fee. return address The address of the newly created contract./
|
function createPoolManagerLogic(address _poolAddress, address _manager, uint _performanceFee) external returns (address);
|
function createPoolManagerLogic(address _poolAddress, address _manager, uint _performanceFee) external returns (address);
| 41,844
|
215
|
// Disables the timeLock after buying for everyone
|
function TeamDisableBuyLock(bool disabled) public onlyOwner{
buyLockDisabled=disabled;
}
|
function TeamDisableBuyLock(bool disabled) public onlyOwner{
buyLockDisabled=disabled;
}
| 18,705
|
15
|
// add addresses to the whitelist addrs addressesreturn success true if at least one address was added to the whitelist,false if all addresses were already in the whitelist /
|
function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
|
function addAddressesToWhitelist(address[] memory addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
| 11,321
|
371
|
// Captures the necessary data for making a commitment. Used as a parameter when making batch commitments. Not used as a data structure for storage.
|
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
|
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
| 9,929
|
6
|
// _erc721TransferHelper The ZORA ERC-721 Transfer Helper address/_royaltyEngine The Manifold Royalty Engine address/_protocolFeeSettings The ZORA Protocol Fee Settings address/_weth The WETH token address
|
constructor(
address _erc721TransferHelper,
address _royaltyEngine,
address _protocolFeeSettings,
address _weth
)
FeePayoutSupportV1(
_royaltyEngine,
_protocolFeeSettings,
_weth,
|
constructor(
address _erc721TransferHelper,
address _royaltyEngine,
address _protocolFeeSettings,
address _weth
)
FeePayoutSupportV1(
_royaltyEngine,
_protocolFeeSettings,
_weth,
| 26,912
|
10
|
// type specific book keeping
|
if (component.isProduct()) { EnumerableSet.add(_products, id); }
|
if (component.isProduct()) { EnumerableSet.add(_products, id); }
| 40,808
|
1
|
// 判断字符串是否相等
|
function isStrEqual(string _str1, string _str2) public pure returns(bool){
return keccak256(_str1) == keccak256(_str2);
}
|
function isStrEqual(string _str1, string _str2) public pure returns(bool){
return keccak256(_str1) == keccak256(_str2);
}
| 54,633
|
14
|
// v2.1 => v2.1
|
if (fromVersion == uint8(RegistryVersion.V21)) {
return encodedUpkeeps;
}
|
if (fromVersion == uint8(RegistryVersion.V21)) {
return encodedUpkeeps;
}
| 19,014
|
9
|
// An Ethereum contract that contains the metadata for a rules engine/Aaron Kendall/1.) Certain steps are required in order to use this engine correctly + 2.) Deployment of this contract to a blockchain is expensive (~8000000 gas) + 3.) Various require() statements are commented out to save deployment costs/Even though you can create rule trees by calling this contract directly, it is generally recommended that you create them using the Nethereum library
|
contract WonkaEngineMetadata {
using WonkaLibrary for *;
address public rulesMaster;
uint public attrCounter;
// The Attributes known by this instance of the rules engine
mapping(bytes32 => WonkaLibrary.WonkaAttr) private attrMap;
WonkaLibrary.WonkaAttr[] public attributes;
// The cache of records that are owned by "rulers" and that are validated when invoking a rule tree
mapping(address => mapping(bytes32 => string)) currentRecords;
/// @dev Constructor for the rules engine
/// @notice Currently, the engine will create three dummy Attributes within the cache by default, but they will be removed later
constructor() {
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 1,
attrName: "Title",
maxLength: 256,
maxLengthTruncate: true,
maxNumValue: 0,
defaultValue: "",
isString: true,
isDecimal: false,
isNumeric: false,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 2,
attrName: "Price",
maxLength: 128,
maxLengthTruncate: false,
maxNumValue: 1000000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 3,
attrName: "PageAmount",
maxLength: 256,
maxLengthTruncate: false,
maxNumValue: 1000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attrCounter = 4;
}
modifier onlyEngineOwner() {
// NOTE: Should be altered later
// require(msg.sender == rulesMaster, "No exec perm");
// Do not forget the "_;"! It will
// be replaced by the actual function
// body when the modifier is used.
_;
}
/// @dev This method will add a new Attribute to the cache. By adding Attributes, we expand the set of possible values that can be held by a record.
/// @notice
function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string memory pDefVal, bool pIsStr, bool pIsNum) public onlyEngineOwner {
attributes.push(WonkaLibrary.WonkaAttr({
attrId: attrCounter++,
attrName: pAttrName,
maxLength: pMaxLen,
maxLengthTruncate: (pMaxLen > 0),
maxNumValue: pMaxNumVal,
defaultValue: pDefVal,
isString: pIsStr,
isDecimal: false,
isNumeric: pIsNum,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
}
/// @dev This method will return the Attribute struct (if one has been provided)
/// @notice
function getAttribute(bytes32 pAttrName) public view returns(WonkaLibrary.WonkaAttr memory _attr) {
return attrMap[pAttrName];
}
/// @dev This method will return the current number of Attributes in the cache
/// @notice This method should only be used for debugging purposes.
function getNumberOfAttributes() public view returns(uint) {
return attributes.length;
}
}
|
contract WonkaEngineMetadata {
using WonkaLibrary for *;
address public rulesMaster;
uint public attrCounter;
// The Attributes known by this instance of the rules engine
mapping(bytes32 => WonkaLibrary.WonkaAttr) private attrMap;
WonkaLibrary.WonkaAttr[] public attributes;
// The cache of records that are owned by "rulers" and that are validated when invoking a rule tree
mapping(address => mapping(bytes32 => string)) currentRecords;
/// @dev Constructor for the rules engine
/// @notice Currently, the engine will create three dummy Attributes within the cache by default, but they will be removed later
constructor() {
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 1,
attrName: "Title",
maxLength: 256,
maxLengthTruncate: true,
maxNumValue: 0,
defaultValue: "",
isString: true,
isDecimal: false,
isNumeric: false,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 2,
attrName: "Price",
maxLength: 128,
maxLengthTruncate: false,
maxNumValue: 1000000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLibrary.WonkaAttr({
attrId: 3,
attrName: "PageAmount",
maxLength: 256,
maxLengthTruncate: false,
maxNumValue: 1000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attrCounter = 4;
}
modifier onlyEngineOwner() {
// NOTE: Should be altered later
// require(msg.sender == rulesMaster, "No exec perm");
// Do not forget the "_;"! It will
// be replaced by the actual function
// body when the modifier is used.
_;
}
/// @dev This method will add a new Attribute to the cache. By adding Attributes, we expand the set of possible values that can be held by a record.
/// @notice
function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string memory pDefVal, bool pIsStr, bool pIsNum) public onlyEngineOwner {
attributes.push(WonkaLibrary.WonkaAttr({
attrId: attrCounter++,
attrName: pAttrName,
maxLength: pMaxLen,
maxLengthTruncate: (pMaxLen > 0),
maxNumValue: pMaxNumVal,
defaultValue: pDefVal,
isString: pIsStr,
isDecimal: false,
isNumeric: pIsNum,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
}
/// @dev This method will return the Attribute struct (if one has been provided)
/// @notice
function getAttribute(bytes32 pAttrName) public view returns(WonkaLibrary.WonkaAttr memory _attr) {
return attrMap[pAttrName];
}
/// @dev This method will return the current number of Attributes in the cache
/// @notice This method should only be used for debugging purposes.
function getNumberOfAttributes() public view returns(uint) {
return attributes.length;
}
}
| 48,686
|
15
|
// Get pending premia reward for a user on a pool _pool Address of option pool contract _isCallPool True if for call option pool, False if for put option pool /
|
function pendingPremia(
address _pool,
bool _isCallPool,
address _user
|
function pendingPremia(
address _pool,
bool _isCallPool,
address _user
| 37,240
|
122
|
// https:github.com/ethereum/EIPs/issues/223
|
interface TokenFallback {
function tokenFallback(address _from, uint _value, bytes calldata _data) external;
}
|
interface TokenFallback {
function tokenFallback(address _from, uint _value, bytes calldata _data) external;
}
| 37,700
|
78
|
// Private functions -----------------------------------------------------------------------------------------------------------------
|
function _registerService(address service, uint256 timeout)
private
|
function _registerService(address service, uint256 timeout)
private
| 44,765
|
3
|
// SLO Registered event
|
event SLORegistered(address indexed sla, uint256 sloValue, SLOType sloType);
|
event SLORegistered(address indexed sla, uint256 sloValue, SLOType sloType);
| 33,922
|
47
|
// Function to check eligibility and availability for claiming rewards
|
function checkEligibilityAndAvailability() private view {
require(!isNotEligibleForTxFeeReward[msg.sender], "Address not eligible for Fee rewards");
require(lastClaimedSnapshot[msg.sender] < periods.length, "No rewards available");
}
|
function checkEligibilityAndAvailability() private view {
require(!isNotEligibleForTxFeeReward[msg.sender], "Address not eligible for Fee rewards");
require(lastClaimedSnapshot[msg.sender] < periods.length, "No rewards available");
}
| 9,277
|
6
|
// mint License NFT function
|
function _mint(
address _to,
uint _id,
uint _amount,
bytes memory _data
|
function _mint(
address _to,
uint _id,
uint _amount,
bytes memory _data
| 34,632
|
17
|
// Tells whether an operator is approved by a given owner _owner owner address which you want to query the approval of _operator operator address which you want to query the approval ofreturn bool whether the given operator is approved by the given owner /
|
function isApprovedForAll(
address _owner,
address _operator
)
public
override
view
returns (bool)
|
function isApprovedForAll(
address _owner,
address _operator
)
public
override
view
returns (bool)
| 5,055
|
405
|
// If this account has bitmaps set, this is the corresponding currency id
|
uint16 bitmapCurrencyId;
|
uint16 bitmapCurrencyId;
| 6,017
|
26
|
// _UNIWethPoolAddress = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); main net
|
_UNIWethPoolAddress = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xc778417E063141139Fce010982780140Aa0cD5Ab, address(this)); //ropsten test net
|
_UNIWethPoolAddress = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xc778417E063141139Fce010982780140Aa0cD5Ab, address(this)); //ropsten test net
| 31,053
|
43
|
// emits an event when a stable asset price changes
|
event StablePriceUpdated(address indexed asset, uint256 price);
|
event StablePriceUpdated(address indexed asset, uint256 price);
| 31,683
|
5
|
// Create additional deeds by extending an exisiting collections total supply/collection The address of the collection to extend/additionalSupply The amount of tokens to add to the collection
|
function extendCollection(
address collection,
uint256 additionalSupply
|
function extendCollection(
address collection,
uint256 additionalSupply
| 18,389
|
232
|
// Rounds up to the nearest tick where tick % tickSpacing == 0/tick The tick to round/tickSpacing The tick spacing to round to/ return the ceiled tick/Ensure tick +/- tickSpacing does not overflow or underflow int24
|
function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod > 0) return tick - mod + tickSpacing;
return tick - mod;
}
}
|
function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod > 0) return tick - mod + tickSpacing;
return tick - mod;
}
}
| 38,613
|
213
|
// Emits one {CallScheduled} event per transaction in the batch. Requirements: - the caller must have the 'proposer' role. /
|
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
|
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == datas.length, "TimelockController: length mismatch");
| 20,223
|
22
|
// ERC23 Token fallback_from address incoming token_amount incoming amount/
|
{
_deposited(_from, _amount, msg.sender, _data);
}
|
{
_deposited(_from, _amount, msg.sender, _data);
}
| 5,370
|
29
|
// Function to transfer an NFT between wallets.
|
function transfer(address to, uint256 tokenId) public {
safeTransferFrom(msg.sender, to, tokenId);
}
|
function transfer(address to, uint256 tokenId) public {
safeTransferFrom(msg.sender, to, tokenId);
}
| 63,757
|
70
|
// Transfer amount of tokens from a specified address to a recipient. Transfer amount of tokens from sender account to recipient.
|
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
|
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
| 14,660
|
194
|
// send back excess but ignore dust
|
if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
|
if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
| 38,584
|
75
|
// 0x42: Tried to divide by zero.
|
DivisionByZero,
|
DivisionByZero,
| 47,527
|
0
|
// ============ CONSTRUCTORS ========== /
|
function initialize(address _fsm) external initializer {
require(_fsm != address(0), "FsmReserve::constructor: invalid address");
fsm = IERC20(_fsm);
}
|
function initialize(address _fsm) external initializer {
require(_fsm != address(0), "FsmReserve::constructor: invalid address");
fsm = IERC20(_fsm);
}
| 22,589
|
0
|
// Constructor
|
constructor(
Universe universe,
address companyLegalRep
)
public
SingleEquityTokenController(universe, companyLegalRep)
|
constructor(
Universe universe,
address companyLegalRep
)
public
SingleEquityTokenController(universe, companyLegalRep)
| 30,587
|
26
|
// Set an ODEM claim./ Only ODEM can set claims./Requires caller to have the role "claims__issuer"./subject The address of the individual./key The ODEM event code./uri The URI where the certificate can be downloaded./hash The hash of the certificate file.
|
function setODEMClaim(address subject, bytes32 key, bytes uri, bytes32 hash) public onlyRole(ROLE_ISSUER) {
address resolved = resolveAddress(subject);
claims[resolved][key].uri = uri;
claims[resolved][key].hash = hash;
hasClaims[resolved] = true;
emit ClaimSet(msg.sender, subject, key, hash, now);
}
|
function setODEMClaim(address subject, bytes32 key, bytes uri, bytes32 hash) public onlyRole(ROLE_ISSUER) {
address resolved = resolveAddress(subject);
claims[resolved][key].uri = uri;
claims[resolved][key].hash = hash;
hasClaims[resolved] = true;
emit ClaimSet(msg.sender, subject, key, hash, now);
}
| 31,908
|
7
|
// If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
|
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
|
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
x >>= count; // now x < 2
res = count * FIXED_1;
}
| 17,615
|
0
|
// State variable Claims
|
Claim[] internal claims;
mapping(uint256 => uint256[]) internal coverToClaims;
mapping(uint256 => uint256) public claimToCover;
mapping(uint256 => uint256) public coverToPayout;
mapping(uint256 => mapping(uint80 => bool)) public coverToValidRoundId; // coverId => roundId -> true/false
CollectiveClaim[] internal collectiveClaims;
mapping(uint256 => uint256[]) internal requestToCollectiveClaims;
mapping(uint256 => uint256) public collectiveClaimToRequest;
|
Claim[] internal claims;
mapping(uint256 => uint256[]) internal coverToClaims;
mapping(uint256 => uint256) public claimToCover;
mapping(uint256 => uint256) public coverToPayout;
mapping(uint256 => mapping(uint80 => bool)) public coverToValidRoundId; // coverId => roundId -> true/false
CollectiveClaim[] internal collectiveClaims;
mapping(uint256 => uint256[]) internal requestToCollectiveClaims;
mapping(uint256 => uint256) public collectiveClaimToRequest;
| 19,173
|
33
|
// //Migrate `underlying` `amount` from BENTO into AAVE by batching calls to `bento` and `aave`.
|
function bentoToAave(IERC20 underlying, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, msg.sender, 0); // stake `underlying` into `aave` for `msg.sender`
}
|
function bentoToAave(IERC20 underlying, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, msg.sender, 0); // stake `underlying` into `aave` for `msg.sender`
}
| 26,984
|
69
|
// Allows any user to get a part of his ETH refunded, in proportionto the % reduced of the allocation
|
function partial_refund() {
require(bought_tokens && percent_reduction > 0);
//Amount to refund is the amount minus the X% of the reduction
//amount_to_refund = balance*X
uint256 amount = SafeMath.div(SafeMath.mul(balances[msg.sender], percent_reduction), 100);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], amount);
balances_bonus[msg.sender] = balances[msg.sender];
if (owner_supplied_eth) {
//dev fees aren't refunded, only owner fees
uint256 fee = amount.div(FEE).mul(percent_reduction).div(100);
amount = amount.add(fee);
}
msg.sender.transfer(amount);
}
|
function partial_refund() {
require(bought_tokens && percent_reduction > 0);
//Amount to refund is the amount minus the X% of the reduction
//amount_to_refund = balance*X
uint256 amount = SafeMath.div(SafeMath.mul(balances[msg.sender], percent_reduction), 100);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], amount);
balances_bonus[msg.sender] = balances[msg.sender];
if (owner_supplied_eth) {
//dev fees aren't refunded, only owner fees
uint256 fee = amount.div(FEE).mul(percent_reduction).div(100);
amount = amount.add(fee);
}
msg.sender.transfer(amount);
}
| 46,935
|
24
|
// / !!!!!!!!!!!!!!/ !!! NOTICE !!! transfer does not return a value, in violation of the ERC-20 specification/ !!!!!!!!!!!!!!/
|
function transfer(address dst, uint256 amount) external;
|
function transfer(address dst, uint256 amount) external;
| 52,603
|
1
|
// Getter function to retrieve the current value of `myNumber`
|
function getNumber() public view returns (uint256) {
return myNumber;
}
|
function getNumber() public view returns (uint256) {
return myNumber;
}
| 22,086
|
63
|
// total eth fund in presale stage
|
uint public presale_eth_fund= 0;
|
uint public presale_eth_fund= 0;
| 69,235
|
72
|
// require(raisedAmount <= hardCap);
|
uint tokens = (msg.value / tokenPrice) * 10**18;
_mint(msg.sender,tokens);
uint treasury = (msg.value).div(2);
treasuryRaised += treasury;
treasuryAddress.transfer(treasury); // transfering the value sent to the ICO to the deposit address - %50 to treasury
uint core = (msg.value).div(4);
coreAddress.transfer(core); // transfering the value sent to the ICO to the deposit address - %25 to core
|
uint tokens = (msg.value / tokenPrice) * 10**18;
_mint(msg.sender,tokens);
uint treasury = (msg.value).div(2);
treasuryRaised += treasury;
treasuryAddress.transfer(treasury); // transfering the value sent to the ICO to the deposit address - %50 to treasury
uint core = (msg.value).div(4);
coreAddress.transfer(core); // transfering the value sent to the ICO to the deposit address - %25 to core
| 5,614
|
218
|
// get tickets for msg sender by stage an ticket position /
|
{
return (stages[_stage].playerTickets[msg.sender][_position].n1,
stages[_stage].playerTickets[msg.sender][_position].n2,
stages[_stage].playerTickets[msg.sender][_position].n3,
stages[_stage].playerTickets[msg.sender][_position].n4,
stages[_stage].playerTickets[msg.sender][_position].n5,
stages[_stage].playerTickets[msg.sender][_position].pb);
}
|
{
return (stages[_stage].playerTickets[msg.sender][_position].n1,
stages[_stage].playerTickets[msg.sender][_position].n2,
stages[_stage].playerTickets[msg.sender][_position].n3,
stages[_stage].playerTickets[msg.sender][_position].n4,
stages[_stage].playerTickets[msg.sender][_position].n5,
stages[_stage].playerTickets[msg.sender][_position].pb);
}
| 20,804
|
121
|
// check if this collection is closed
|
if (isClosed==true) {
revert("This contract is closed!");
}
|
if (isClosed==true) {
revert("This contract is closed!");
}
| 39,688
|
7
|
// Lets the owner add multiple addresses to the whitelist
|
function addMultipleToWhiteList(address[] memory newAddresses) public onlyOwner {
for (uint i = 0; i < newAddresses.length; i++) {
_whiteList[newAddresses[i]] = true;
}
}
|
function addMultipleToWhiteList(address[] memory newAddresses) public onlyOwner {
for (uint i = 0; i < newAddresses.length; i++) {
_whiteList[newAddresses[i]] = true;
}
}
| 78,553
|
9
|
// Mapping of propertyID to property
|
mapping (uint24 => Property) map;
|
mapping (uint24 => Property) map;
| 50,462
|
63
|
// Public field inicates the finalization state of smart-contract
|
bool public finalized;
|
bool public finalized;
| 68,343
|
26
|
// – confirm semi approved superblock. A semi approved superblock can be confirmed if it has several descendant superblocks that are also semi-approved. If none of the descendants were challenged they will also be confirmed.superblockHash – the claim ID.descendantId - claim ID descendants
|
function confirmClaim(bytes32 superblockHash, bytes32 descendantId) public returns (bool) {
uint numSuperblocks = 0;
bool confirmDescendants = true;
bytes32 id = descendantId;
SuperblockClaim storage claim = claims[id];
while (id != superblockHash) {
if (!claimExists(claim)) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM);
return false;
}
if (trustedSuperblocks.getSuperblockStatus(id) != DogeSuperblocks.Status.SemiApproved) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return false;
}
if (confirmDescendants && claim.challengers.length > 0) {
confirmDescendants = false;
}
id = trustedSuperblocks.getSuperblockParentId(id);
claim = claims[id];
numSuperblocks += 1;
}
if (numSuperblocks < superblockConfirmations) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MISSING_CONFIRMATIONS);
return false;
}
if (trustedSuperblocks.getSuperblockStatus(id) != DogeSuperblocks.Status.SemiApproved) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return false;
}
bytes32 parentId = trustedSuperblocks.getSuperblockParentId(superblockHash);
if (trustedSuperblocks.getSuperblockStatus(parentId) != DogeSuperblocks.Status.Approved) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return false;
}
(uint err, ) = trustedSuperblocks.confirm(superblockHash, msg.sender);
if (err != ERR_SUPERBLOCK_OK) {
emit ErrorClaim(superblockHash, err);
return false;
}
emit SuperblockClaimSuccessful(superblockHash, claim.submitter);
doPaySubmitter(superblockHash, claim);
unbondDeposit(superblockHash, claim.submitter);
if (confirmDescendants) {
bytes32[] memory descendants = new bytes32[](numSuperblocks);
id = descendantId;
uint idx = 0;
while (id != superblockHash) {
descendants[idx] = id;
id = trustedSuperblocks.getSuperblockParentId(id);
idx += 1;
}
while (idx > 0) {
idx -= 1;
id = descendants[idx];
claim = claims[id];
(err, ) = trustedSuperblocks.confirm(id, msg.sender);
require(err == ERR_SUPERBLOCK_OK);
emit SuperblockClaimSuccessful(id, claim.submitter);
doPaySubmitter(id, claim);
unbondDeposit(id, claim.submitter);
}
}
return true;
}
|
function confirmClaim(bytes32 superblockHash, bytes32 descendantId) public returns (bool) {
uint numSuperblocks = 0;
bool confirmDescendants = true;
bytes32 id = descendantId;
SuperblockClaim storage claim = claims[id];
while (id != superblockHash) {
if (!claimExists(claim)) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_CLAIM);
return false;
}
if (trustedSuperblocks.getSuperblockStatus(id) != DogeSuperblocks.Status.SemiApproved) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return false;
}
if (confirmDescendants && claim.challengers.length > 0) {
confirmDescendants = false;
}
id = trustedSuperblocks.getSuperblockParentId(id);
claim = claims[id];
numSuperblocks += 1;
}
if (numSuperblocks < superblockConfirmations) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_MISSING_CONFIRMATIONS);
return false;
}
if (trustedSuperblocks.getSuperblockStatus(id) != DogeSuperblocks.Status.SemiApproved) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return false;
}
bytes32 parentId = trustedSuperblocks.getSuperblockParentId(superblockHash);
if (trustedSuperblocks.getSuperblockStatus(parentId) != DogeSuperblocks.Status.Approved) {
emit ErrorClaim(superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return false;
}
(uint err, ) = trustedSuperblocks.confirm(superblockHash, msg.sender);
if (err != ERR_SUPERBLOCK_OK) {
emit ErrorClaim(superblockHash, err);
return false;
}
emit SuperblockClaimSuccessful(superblockHash, claim.submitter);
doPaySubmitter(superblockHash, claim);
unbondDeposit(superblockHash, claim.submitter);
if (confirmDescendants) {
bytes32[] memory descendants = new bytes32[](numSuperblocks);
id = descendantId;
uint idx = 0;
while (id != superblockHash) {
descendants[idx] = id;
id = trustedSuperblocks.getSuperblockParentId(id);
idx += 1;
}
while (idx > 0) {
idx -= 1;
id = descendants[idx];
claim = claims[id];
(err, ) = trustedSuperblocks.confirm(id, msg.sender);
require(err == ERR_SUPERBLOCK_OK);
emit SuperblockClaimSuccessful(id, claim.submitter);
doPaySubmitter(id, claim);
unbondDeposit(id, claim.submitter);
}
}
return true;
}
| 36,598
|
153
|
// Update the User Balances for each token and with the Pool Factor previously calculated
|
UserDepositSnapshot memory userDepositSnapshot = UserDepositSnapshot(
userAmountToStoreTokenA,
userAmountToStoreTokenB,
fImpOpening
);
_userSnapshots[owner] = userDepositSnapshot;
_onAddLiquidity(_userSnapshots[owner], owner);
|
UserDepositSnapshot memory userDepositSnapshot = UserDepositSnapshot(
userAmountToStoreTokenA,
userAmountToStoreTokenB,
fImpOpening
);
_userSnapshots[owner] = userDepositSnapshot;
_onAddLiquidity(_userSnapshots[owner], owner);
| 56,913
|
92
|
// Calculate output amount for an input score score uint256 tokens IERC20[] /
|
function calculateMultiple(uint256 score, IERC20[] calldata tokens)
external
view
returns (uint256[] memory outputAmounts)
|
function calculateMultiple(uint256 score, IERC20[] calldata tokens)
external
view
returns (uint256[] memory outputAmounts)
| 32,562
|
8
|
// transfer Ownership to other address
|
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
|
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
| 4,286
|
73
|
// Remove liquidity from Uniswap V2 pool to receive the reserve tokens (shortOptionTokens + UnderlyingTokens).
|
(uint256 amountShortOptions, uint256 amountUnderlyingTokens) =
router.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
address(this),
deadline
);
|
(uint256 amountShortOptions, uint256 amountUnderlyingTokens) =
router.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
address(this),
deadline
);
| 34,076
|
18
|
// Calculates penalty amount if penalty == unstakeAmount, that indicates that unstake is forbidden pool Pool of the stake stakee Stake to unstake from unstakeAmount Amount to unstakereturn penalty amount /
|
function calculateUnstakePenalty(Pool storage pool, Stake storage stakee, uint256 unstakeAmount) internal view returns(uint256) {
uint256 timePassed = block.timestamp.sub(stakee.start);
if(timePassed >= pool.duration) return 0;
if(timePassed < pool.cliff) return unstakeAmount; //unstake is prohibited
uint256 penaltyTimeLeft = pool.duration.sub(timePassed);
uint256 linearVestingDuration = pool.duration.sub(pool.cliff);
// penaltyTimePeriod != 0 because if pool.duration == pool.cliff, then one of conditions above will be true
return unstakeAmount.mul(pool.penalty).mul(penaltyTimeLeft).div(linearVestingDuration).div(EXP);
}
|
function calculateUnstakePenalty(Pool storage pool, Stake storage stakee, uint256 unstakeAmount) internal view returns(uint256) {
uint256 timePassed = block.timestamp.sub(stakee.start);
if(timePassed >= pool.duration) return 0;
if(timePassed < pool.cliff) return unstakeAmount; //unstake is prohibited
uint256 penaltyTimeLeft = pool.duration.sub(timePassed);
uint256 linearVestingDuration = pool.duration.sub(pool.cliff);
// penaltyTimePeriod != 0 because if pool.duration == pool.cliff, then one of conditions above will be true
return unstakeAmount.mul(pool.penalty).mul(penaltyTimeLeft).div(linearVestingDuration).div(EXP);
}
| 72,410
|
16
|
// Handle non-overflow cases, 256 by 256 division.
|
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
|
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
| 22,668
|
53
|
// Transfer tokens from the caller to a new holder.Remember, there's a 10% fee here as well.
|
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% 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;
}
|
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% 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;
}
| 61,760
|
143
|
// solium-disable security/no-block-members
|
require(deadline >= block.timestamp, "AudiusToken: Deadline has expired");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
|
require(deadline >= block.timestamp, "AudiusToken: Deadline has expired");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
| 66,896
|
31
|
// revert if there's not enough amount in the tip bucket
|
revert WOMBAT_INVALID_VALUE();
|
revert WOMBAT_INVALID_VALUE();
| 30,134
|
17
|
// A record of states for signing / validating signatures
|
mapping(address => uint256) public nonces;
|
mapping(address => uint256) public nonces;
| 3,445
|
215
|
// /
|
require(addressList.length == 7, "LIST_LENGTH_WRONG");
initOwner(addressList[0]);
_MAINTAINER_ = addressList[1];
_BASE_TOKEN_ = IERC20(addressList[2]);
_QUOTE_TOKEN_ = IERC20(addressList[3]);
_BIDDER_PERMISSION_ = IPermissionManager(addressList[4]);
_MT_FEE_RATE_MODEL_ = IFeeRateModel(addressList[5]);
_POOL_FACTORY_ = addressList[6];
|
require(addressList.length == 7, "LIST_LENGTH_WRONG");
initOwner(addressList[0]);
_MAINTAINER_ = addressList[1];
_BASE_TOKEN_ = IERC20(addressList[2]);
_QUOTE_TOKEN_ = IERC20(addressList[3]);
_BIDDER_PERMISSION_ = IPermissionManager(addressList[4]);
_MT_FEE_RATE_MODEL_ = IFeeRateModel(addressList[5]);
_POOL_FACTORY_ = addressList[6];
| 20,495
|
18
|
// THe user should not be marked as fraudlent.
|
require(users[msg.sender].fraudStatus == false);
|
require(users[msg.sender].fraudStatus == false);
| 27,993
|
142
|
// Token Contract /
|
contract Token is ERC20, Ownable, Pausable, Blacklist {
using SafeMath for uint256;
/// @dev A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @dev A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint256 fromBlock;
uint256 votes;
}
/// @dev A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @dev The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @dev The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
/// @dev 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)"
);
/// @dev A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice The timestamp after which minting may occur
uint public mintingAllowedAfter;
/// @notice Minimum time between mints
uint32 public constant minimumTimeBetweenMints = 1 days * 365;
/// @notice Cap on the percentage of totalSupply that can be minted at each mint
uint8 public constant mintCap = 2;
/// @dev An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @dev An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
constructor(string memory _name, string memory _symbol, uint256 _initialSupply, uint256 mintingAllowedAfter_)
public
ERC20(_name, _symbol)
{
_mint(msg.sender, _initialSupply.mul(10**18));
mintingAllowedAfter = mintingAllowedAfter_;
}
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint256 size) {
require(msg.data.length >= size + 4, "Address type not allowed!");
_;
}
/**
* @dev Mint new tokens (only owner)
* @param recipient recipient address
* @param _mintVal amount to mint
*/
function mint(address recipient, uint256 _mintVal)
public
onlyOwner
whenNotPaused
{
require(recipient != address(0), "JPT::mint: cannot transfer to the zero address");
require(!isBlackListed[recipient], "Mint - Recipient is blacklisted");
require(block.timestamp >= mintingAllowedAfter, "JPT::mint: minting not allowed yet");
// record the mint
mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints);
// mint the amount
require(_mintVal <= SafeMath.div(SafeMath.mul(totalSupply(), mintCap), 100), "JPT::mint: exceeded mint cap");
_mint(recipient, _mintVal);
// move delegates
_moveDelegates(address(0), _delegates[recipient], _mintVal);
}
/**
* @dev burns tokens
* @param _burnVal amount to burn
*/
function burn(uint256 _burnVal) public whenNotPaused {
require(!isBlackListed[msg.sender], "Burn - Sender is blacklisted");
_burn(msg.sender, _burnVal);
}
/**
* @dev Transfer tokens from one address to another
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
* @return true if success
*/
function transfer(address _to, uint256 _value)
public
override
onlyPayloadSize(2 * 32)
whenNotPaused
returns (bool)
{
require(!isBlackListed[msg.sender], "Transfer - Sender is blacklisted");
require(!isBlackListed[_to], "Transfer - Recipient is blacklisted");
super.transfer(_to, _value);
_moveDelegates(_delegates[msg.sender], _delegates[_to], _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
* @return true if success
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public override onlyPayloadSize(3 * 32) whenNotPaused returns (bool) {
require(!isBlackListed[_from], "TransferFrom - Sender is blacklisted");
require(!isBlackListed[_to], "TransferFrom - Recipient is blacklisted");
super.transferFrom(_from, _to, _value);
_moveDelegates(_delegates[_from], _delegates[_to], _value);
}
/**
* @dev Pause token
*/
function setPause() external whenNotPaused onlyOwner {
_pause();
}
/**
* @dev Unpause token
*/
function setUnpause() external whenPaused onlyOwner {
_unpause();
}
//////////////////////////////////////////////////////////////////////////////////////
/**
* @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];
}
/**
* @dev Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @dev 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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(string(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),
"Token::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Token::delegateBySig: invalid nonce"
);
require(now <= expiry, "Token::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @dev 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;
}
/**
* @dev 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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Token::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);
_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)) {
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)) {
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 {
uint256 blockNumber = block.number;
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 getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
contract Token is ERC20, Ownable, Pausable, Blacklist {
using SafeMath for uint256;
/// @dev A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @dev A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint256 fromBlock;
uint256 votes;
}
/// @dev A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @dev The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @dev The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
/// @dev 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)"
);
/// @dev A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice The timestamp after which minting may occur
uint public mintingAllowedAfter;
/// @notice Minimum time between mints
uint32 public constant minimumTimeBetweenMints = 1 days * 365;
/// @notice Cap on the percentage of totalSupply that can be minted at each mint
uint8 public constant mintCap = 2;
/// @dev An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @dev An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
constructor(string memory _name, string memory _symbol, uint256 _initialSupply, uint256 mintingAllowedAfter_)
public
ERC20(_name, _symbol)
{
_mint(msg.sender, _initialSupply.mul(10**18));
mintingAllowedAfter = mintingAllowedAfter_;
}
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint256 size) {
require(msg.data.length >= size + 4, "Address type not allowed!");
_;
}
/**
* @dev Mint new tokens (only owner)
* @param recipient recipient address
* @param _mintVal amount to mint
*/
function mint(address recipient, uint256 _mintVal)
public
onlyOwner
whenNotPaused
{
require(recipient != address(0), "JPT::mint: cannot transfer to the zero address");
require(!isBlackListed[recipient], "Mint - Recipient is blacklisted");
require(block.timestamp >= mintingAllowedAfter, "JPT::mint: minting not allowed yet");
// record the mint
mintingAllowedAfter = SafeMath.add(block.timestamp, minimumTimeBetweenMints);
// mint the amount
require(_mintVal <= SafeMath.div(SafeMath.mul(totalSupply(), mintCap), 100), "JPT::mint: exceeded mint cap");
_mint(recipient, _mintVal);
// move delegates
_moveDelegates(address(0), _delegates[recipient], _mintVal);
}
/**
* @dev burns tokens
* @param _burnVal amount to burn
*/
function burn(uint256 _burnVal) public whenNotPaused {
require(!isBlackListed[msg.sender], "Burn - Sender is blacklisted");
_burn(msg.sender, _burnVal);
}
/**
* @dev Transfer tokens from one address to another
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
* @return true if success
*/
function transfer(address _to, uint256 _value)
public
override
onlyPayloadSize(2 * 32)
whenNotPaused
returns (bool)
{
require(!isBlackListed[msg.sender], "Transfer - Sender is blacklisted");
require(!isBlackListed[_to], "Transfer - Recipient is blacklisted");
super.transfer(_to, _value);
_moveDelegates(_delegates[msg.sender], _delegates[_to], _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
* @return true if success
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public override onlyPayloadSize(3 * 32) whenNotPaused returns (bool) {
require(!isBlackListed[_from], "TransferFrom - Sender is blacklisted");
require(!isBlackListed[_to], "TransferFrom - Recipient is blacklisted");
super.transferFrom(_from, _to, _value);
_moveDelegates(_delegates[_from], _delegates[_to], _value);
}
/**
* @dev Pause token
*/
function setPause() external whenNotPaused onlyOwner {
_pause();
}
/**
* @dev Unpause token
*/
function setUnpause() external whenPaused onlyOwner {
_unpause();
}
//////////////////////////////////////////////////////////////////////////////////////
/**
* @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];
}
/**
* @dev Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @dev 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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(string(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),
"Token::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Token::delegateBySig: invalid nonce"
);
require(now <= expiry, "Token::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @dev 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;
}
/**
* @dev 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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Token::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);
_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)) {
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)) {
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 {
uint256 blockNumber = block.number;
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 getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
| 8,735
|
69
|
// on sell
|
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * (sellTotalFees)/(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
|
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount * (sellTotalFees)/(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
tokensForBurn += fees * sellBurnFee / sellTotalFees;
}
| 21,598
|
195
|
// Record current epoch start height and public keys (by storing them in address format)
|
require(eccd.putCurEpochStartHeight(header.height), "Save Poly chain current epoch start height to Data contract failed!");
require(eccd.putCurEpochConPubKeyBytes(ECCUtils.serializeKeepers(keepers)), "Save Poly chain current epoch book keepers to Data contract failed!");
|
require(eccd.putCurEpochStartHeight(header.height), "Save Poly chain current epoch start height to Data contract failed!");
require(eccd.putCurEpochConPubKeyBytes(ECCUtils.serializeKeepers(keepers)), "Save Poly chain current epoch book keepers to Data contract failed!");
| 20,933
|
172
|
// Fetch the `symbol()` from an ERC20 token Grabs the `symbol()` from a contract _token Address of the ERC20 tokenreturn string Symbol of the ERC20 token /
|
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
|
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
| 26,218
|
92
|
// Gets the token namereturn string representing the token name /
|
function name() public view returns (string) {
return name_;
}
|
function name() public view returns (string) {
return name_;
}
| 36,750
|
5
|
// STATE MODIFYING FUNCTIONS // Borrow the specified token from this pool for this transaction only. This function will call`IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the tokenand the associated fee by the end of the callback transaction. If the conditions are not met, this callis reverted. receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiverinterface and the callback function `executeOperation`. token the protocol fee in bps to be applied on the total flash loan fee amount the total amount to borrow in this transaction params optional data to pass along to
|
function flashLoan(
address receiver,
IERC20 token,
uint256 amount,
bytes memory params
|
function flashLoan(
address receiver,
IERC20 token,
uint256 amount,
bytes memory params
| 30,026
|
7
|
// Make a transfer from msg.sender to "to"
|
function transfer(address to, uint tokens) public returns (bool success){
balances[msg.sender] = balances[msg.sender] - tokens;
balances[to] = balances[to] + tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
|
function transfer(address to, uint tokens) public returns (bool success){
balances[msg.sender] = balances[msg.sender] - tokens;
balances[to] = balances[to] + tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
| 48,612
|
40
|
// Perform the swap with Uniswap V2 to the given token addresses and amounts. _totalAmountToSwap Total amount of erc20TokenOrigin to spend in swaps. _deadline The unix timestamp after a swap will fail. _swaps The array of the Swaps data. Swap ETH to ERC20. /
|
function performSwapV2ETH(
uint256 _totalAmountToSwap,
uint32 _deadline,
SwapV2[] calldata _swaps
|
function performSwapV2ETH(
uint256 _totalAmountToSwap,
uint32 _deadline,
SwapV2[] calldata _swaps
| 21,459
|
107
|
// Sets the fees for sells/_marketingFee The fee for the marketing wallet/_liquidityFee The fee for the liquidity pool/_devFee The fee for the dev wallet
|
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
|
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
| 13,682
|
19
|
// MockDharmaKeyRingFactory /
|
contract MockDharmaKeyRingFactory {
// Use DharmaKeyRing initialize selector to construct initialization calldata.
bytes4 private constant _INITIALIZE_SELECTOR = bytes4(0x30fc201f);
function newKeyRing(
uint256 adminThreshold,
uint256 executorThreshold,
address[] calldata userSigningKeys,
uint8[] calldata keyTypes
) external returns (address keyRing) {
// Get initialization calldata using the initial user signing key.
bytes memory initializationCalldata = abi.encodeWithSelector(
_INITIALIZE_SELECTOR,
adminThreshold,
executorThreshold,
userSigningKeys,
keyTypes
);
// Deploy and initialize new user key ring as an Upgrade Beacon proxy.
keyRing = _deployUpgradeBeaconProxyInstance(initializationCalldata);
}
/**
* @notice Private function to deploy an upgrade beacon proxy via `CREATE2`.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the deployed contract to the implementation set on
* the upgrade beacon during contract creation.
* @return The address of the newly-deployed upgrade beacon proxy.
*/
function _deployUpgradeBeaconProxyInstance(
bytes memory initializationCalldata
) private returns (address upgradeBeaconProxyInstance) {
// Place creation code and constructor args of new proxy instance in memory.
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
// Get salt to use during deployment using the supplied initialization code.
(uint256 salt, ) = _getSaltAndTarget(initCode);
// Deploy the new upgrade beacon proxy contract using `CREATE2`.
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
upgradeBeaconProxyInstance := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// Pass along failure message and revert if contract deployment fails.
if iszero(upgradeBeaconProxyInstance) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next deployed contract (using `CREATE2`) based on the
* contract creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (uint256 nonce, address target) {
// Get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// Set the initial nonce to be provided when constructing the salt.
nonce = 0;
// Declare variable for code size of derived address.
uint256 codeSize;
// Loop until an contract deployment address with no code has been found.
while (true) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
nonce, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// Exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
}
|
contract MockDharmaKeyRingFactory {
// Use DharmaKeyRing initialize selector to construct initialization calldata.
bytes4 private constant _INITIALIZE_SELECTOR = bytes4(0x30fc201f);
function newKeyRing(
uint256 adminThreshold,
uint256 executorThreshold,
address[] calldata userSigningKeys,
uint8[] calldata keyTypes
) external returns (address keyRing) {
// Get initialization calldata using the initial user signing key.
bytes memory initializationCalldata = abi.encodeWithSelector(
_INITIALIZE_SELECTOR,
adminThreshold,
executorThreshold,
userSigningKeys,
keyTypes
);
// Deploy and initialize new user key ring as an Upgrade Beacon proxy.
keyRing = _deployUpgradeBeaconProxyInstance(initializationCalldata);
}
/**
* @notice Private function to deploy an upgrade beacon proxy via `CREATE2`.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the deployed contract to the implementation set on
* the upgrade beacon during contract creation.
* @return The address of the newly-deployed upgrade beacon proxy.
*/
function _deployUpgradeBeaconProxyInstance(
bytes memory initializationCalldata
) private returns (address upgradeBeaconProxyInstance) {
// Place creation code and constructor args of new proxy instance in memory.
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
// Get salt to use during deployment using the supplied initialization code.
(uint256 salt, ) = _getSaltAndTarget(initCode);
// Deploy the new upgrade beacon proxy contract using `CREATE2`.
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
upgradeBeaconProxyInstance := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// Pass along failure message and revert if contract deployment fails.
if iszero(upgradeBeaconProxyInstance) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next deployed contract (using `CREATE2`) based on the
* contract creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (uint256 nonce, address target) {
// Get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// Set the initial nonce to be provided when constructing the salt.
nonce = 0;
// Declare variable for code size of derived address.
uint256 codeSize;
// Loop until an contract deployment address with no code has been found.
while (true) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
nonce, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// Exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
}
| 34,031
|
14
|
// Total number of tokens /
|
uint16 public constant NUM_TOKENS = 10000;
|
uint16 public constant NUM_TOKENS = 10000;
| 17,168
|
6
|
// It’s necessary to add an empty first member
|
addMember(0, "");
|
addMember(0, "");
| 32,665
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.