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
|
|---|---|---|---|---|
10
|
// Stake tokens
|
return kudos.transferFrom(msg.sender, address(this), _tokens);
|
return kudos.transferFrom(msg.sender, address(this), _tokens);
| 28,947
|
25
|
// Function for retrieving the currentAdoptionFee return Returns the adoptionFee of uint256
|
function getCurrentAdoptionFee()
external
view
returns (uint256 adoptionFee)
|
function getCurrentAdoptionFee()
external
view
returns (uint256 adoptionFee)
| 47,003
|
357
|
// Emitted when market comped status is changed
|
event MarketComped(GToken gToken, bool isComped);
|
event MarketComped(GToken gToken, bool isComped);
| 45,371
|
206
|
// --- public --- / public mint function - just some safeguards for fair launch /
|
function mint(uint amount) public payable whenMintingAllowed {
require(((_tokenIds.current() + amount) <= _maxSupply) && (amount <= _maxMintPerTx) && (msg.value >= _actualMintPrice() * amount), "Mint failed");
mintToken(_msgSender(), amount, msg.value);
}
|
function mint(uint amount) public payable whenMintingAllowed {
require(((_tokenIds.current() + amount) <= _maxSupply) && (amount <= _maxMintPerTx) && (msg.value >= _actualMintPrice() * amount), "Mint failed");
mintToken(_msgSender(), amount, msg.value);
}
| 30,277
|
14
|
// Set house commission.newHouseCommission New house comission./
|
function setHouseCommission(uint256 newHouseCommission) public onlyOwner {
houseCommission = newHouseCommission;
}
|
function setHouseCommission(uint256 newHouseCommission) public onlyOwner {
houseCommission = newHouseCommission;
}
| 20,806
|
45
|
// DerpfiToken with Governance.
|
contract DerpfiToken is ERC20("Derpfi", "DFI"), Ownable {
uint256 private constant CAP = 210000000e18; // 210 million Derpfi
uint256 private _totalLock;
uint256 public startReleaseBlock;
uint256 public endReleaseBlock;
uint256 public constant MANUAL_MINT_LIMIT = 10500000e18; // 10.5 million Derpfi
uint256 public manualMinted = 0;
mapping(address => uint256) private _locks;
mapping(address => uint256) private _lastUnlockBlock;
event Lock(address indexed to, uint256 value);
constructor(uint256 _startReleaseBlock, uint256 _endReleaseBlock) public {
require(_endReleaseBlock > _startReleaseBlock, "bad endReleaseBlock");
startReleaseBlock = _startReleaseBlock;
endReleaseBlock = _endReleaseBlock;
// maunalMint 250k for seeding liquidity
manualMint(msg.sender, 250000e18);
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function cap() public pure returns (uint256) {
return CAP;
}
function unlockedSupply() external view returns (uint256) {
return totalSupply().sub(totalLock());
}
function totalLock() public view returns (uint256) {
return _totalLock;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
_moveDelegates(_delegates[_msgSender()], _delegates[recipient], amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance"));
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
return true;
}
function manualMint(address _to, uint256 _amount) public onlyOwner {
require(manualMinted.add(_amount) <= MANUAL_MINT_LIMIT, "mint limit exceeded");
manualMinted = manualMinted.add(_amount);
mint(_to, _amount);
}
function mint(address _to, uint256 _amount) public onlyOwner {
require(totalSupply().add(_amount) <= cap(), "cap exceeded");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _account, uint256 _amount) external onlyOwner {
_burn(_account, _amount);
}
function totalBalanceOf(address _account) external view returns (uint256) {
return _locks[_account].add(balanceOf(_account));
}
function lockOf(address _account) external view returns (uint256) {
return _locks[_account];
}
function lastUnlockBlock(address _account) external view returns (uint256) {
return _lastUnlockBlock[_account];
}
function lock(address _account, uint256 _amount) external onlyOwner {
require(_account != address(0), "no lock to address(0)");
require(_amount <= balanceOf(_account), "balance exceeded");
_transfer(_account, address(this), _amount);
_locks[_account] = _locks[_account].add(_amount);
_totalLock = _totalLock.add(_amount);
if (_lastUnlockBlock[_account] < startReleaseBlock) {
_lastUnlockBlock[_account] = startReleaseBlock;
}
emit Lock(_account, _amount);
}
function canUnlockAmount(address _account) public view returns (uint256) {
// When block number less than startReleaseBlock, no BDL can be unlocked
if (block.number < startReleaseBlock) {
return 0;
}
// When block number more than endReleaseBlock, all locked BDL can be unlocked
else if (block.number >= endReleaseBlock) {
return _locks[_account];
}
// When block number is more than startReleaseBlock but less than endReleaseBlock,
// some BDL can be released
else
{
uint256 releasedBlock = block.number.sub(_lastUnlockBlock[_account]);
uint256 blockLeft = endReleaseBlock.sub(_lastUnlockBlock[_account]);
return _locks[_account].mul(releasedBlock).div(blockLeft);
}
}
function unlock() external {
require(_locks[msg.sender] > 0, "no locked DERPFI");
uint256 amount = canUnlockAmount(msg.sender);
_transfer(address(this), msg.sender, amount);
_locks[msg.sender] = _locks[msg.sender].sub(amount);
_lastUnlockBlock[msg.sender] = block.number;
_totalLock = _totalLock.sub(amount);
}
// Governance cloned and modified from COMPOUND to use uint256:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev 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 => uint256) 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, uint256 previousBalance, uint256 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,
uint256 nonce,
uint256 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), "Derpfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Derpfi::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "Derpfi::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, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "Derpfi::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)) {
// 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, "Derpfi::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
contract DerpfiToken is ERC20("Derpfi", "DFI"), Ownable {
uint256 private constant CAP = 210000000e18; // 210 million Derpfi
uint256 private _totalLock;
uint256 public startReleaseBlock;
uint256 public endReleaseBlock;
uint256 public constant MANUAL_MINT_LIMIT = 10500000e18; // 10.5 million Derpfi
uint256 public manualMinted = 0;
mapping(address => uint256) private _locks;
mapping(address => uint256) private _lastUnlockBlock;
event Lock(address indexed to, uint256 value);
constructor(uint256 _startReleaseBlock, uint256 _endReleaseBlock) public {
require(_endReleaseBlock > _startReleaseBlock, "bad endReleaseBlock");
startReleaseBlock = _startReleaseBlock;
endReleaseBlock = _endReleaseBlock;
// maunalMint 250k for seeding liquidity
manualMint(msg.sender, 250000e18);
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function cap() public pure returns (uint256) {
return CAP;
}
function unlockedSupply() external view returns (uint256) {
return totalSupply().sub(totalLock());
}
function totalLock() public view returns (uint256) {
return _totalLock;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
_moveDelegates(_delegates[_msgSender()], _delegates[recipient], amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance"));
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
return true;
}
function manualMint(address _to, uint256 _amount) public onlyOwner {
require(manualMinted.add(_amount) <= MANUAL_MINT_LIMIT, "mint limit exceeded");
manualMinted = manualMinted.add(_amount);
mint(_to, _amount);
}
function mint(address _to, uint256 _amount) public onlyOwner {
require(totalSupply().add(_amount) <= cap(), "cap exceeded");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _account, uint256 _amount) external onlyOwner {
_burn(_account, _amount);
}
function totalBalanceOf(address _account) external view returns (uint256) {
return _locks[_account].add(balanceOf(_account));
}
function lockOf(address _account) external view returns (uint256) {
return _locks[_account];
}
function lastUnlockBlock(address _account) external view returns (uint256) {
return _lastUnlockBlock[_account];
}
function lock(address _account, uint256 _amount) external onlyOwner {
require(_account != address(0), "no lock to address(0)");
require(_amount <= balanceOf(_account), "balance exceeded");
_transfer(_account, address(this), _amount);
_locks[_account] = _locks[_account].add(_amount);
_totalLock = _totalLock.add(_amount);
if (_lastUnlockBlock[_account] < startReleaseBlock) {
_lastUnlockBlock[_account] = startReleaseBlock;
}
emit Lock(_account, _amount);
}
function canUnlockAmount(address _account) public view returns (uint256) {
// When block number less than startReleaseBlock, no BDL can be unlocked
if (block.number < startReleaseBlock) {
return 0;
}
// When block number more than endReleaseBlock, all locked BDL can be unlocked
else if (block.number >= endReleaseBlock) {
return _locks[_account];
}
// When block number is more than startReleaseBlock but less than endReleaseBlock,
// some BDL can be released
else
{
uint256 releasedBlock = block.number.sub(_lastUnlockBlock[_account]);
uint256 blockLeft = endReleaseBlock.sub(_lastUnlockBlock[_account]);
return _locks[_account].mul(releasedBlock).div(blockLeft);
}
}
function unlock() external {
require(_locks[msg.sender] > 0, "no locked DERPFI");
uint256 amount = canUnlockAmount(msg.sender);
_transfer(address(this), msg.sender, amount);
_locks[msg.sender] = _locks[msg.sender].sub(amount);
_lastUnlockBlock[msg.sender] = block.number;
_totalLock = _totalLock.sub(amount);
}
// Governance cloned and modified from COMPOUND to use uint256:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev 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 => uint256) 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, uint256 previousBalance, uint256 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,
uint256 nonce,
uint256 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), "Derpfi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Derpfi::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "Derpfi::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, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "Derpfi::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)) {
// 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, "Derpfi::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 26,673
|
24
|
// This function is internally called by the buyTokens function to automatically forward all investments made to the multi signature wallet. /
|
function forwardFunds() internal {
multiSigWallet.transfer(msg.value);
}
|
function forwardFunds() internal {
multiSigWallet.transfer(msg.value);
}
| 41,578
|
32
|
// Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. a a FixedPoint. b a FixedPoint.return the product of `a` and `b`. /
|
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
|
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
| 11,885
|
155
|
// We're done withdrawing
|
if (strategyId == address(0)) break;
uint256 vaultBalance = _vaultTokenBalance();
uint256 amountNeeded = amountAdjusted - vaultBalance;
|
if (strategyId == address(0)) break;
uint256 vaultBalance = _vaultTokenBalance();
uint256 amountNeeded = amountAdjusted - vaultBalance;
| 59,614
|
0
|
// generate example Merkle tree
|
(bytes32 root, bytes32[] memory proof) = generateMerkleTree(
keccak256(abi.encodePacked(address(this), EXAMPLE_USER_SHARES)),
10,
keccak256(abi.encodePacked(block.timestamp))
);
exampleProof = proof;
|
(bytes32 root, bytes32[] memory proof) = generateMerkleTree(
keccak256(abi.encodePacked(address(this), EXAMPLE_USER_SHARES)),
10,
keccak256(abi.encodePacked(block.timestamp))
);
exampleProof = proof;
| 21,471
|
44
|
// Minting and burning can be permanently disabled by the owner
|
function disableMinting() external onlyOwner {
mintingEnabled = false;
}
|
function disableMinting() external onlyOwner {
mintingEnabled = false;
}
| 11,611
|
2
|
// Grant the items to the minter
|
items[_id].balances[msg.sender] = _totalSupply;
emit Mint(_name, _totalSupply, _uri, _decimals, _symbol, _itemId);
|
items[_id].balances[msg.sender] = _totalSupply;
emit Mint(_name, _totalSupply, _uri, _decimals, _symbol, _itemId);
| 10,156
|
252
|
// The token URI determines which NFT this is
|
_safeMint(msg.sender, lastId, "");
_setTokenURI(lastId, _tokenURI);
|
_safeMint(msg.sender, lastId, "");
_setTokenURI(lastId, _tokenURI);
| 16,992
|
115
|
// earnings reward rate
|
uint public REWARD_RATE_X_100 = 5000;
uint public REWARD_INTERVAL = 365 days;
|
uint public REWARD_RATE_X_100 = 5000;
uint public REWARD_INTERVAL = 365 days;
| 25,791
|
39
|
// The estimator for a struct r The struct to be encodedreturn The number of bytes encoded in estimation /
|
function _estimate(
Data memory r
|
function _estimate(
Data memory r
| 3,065
|
61
|
// Triggers to get specificied `tokenId` expiration timestamptokenId Gateway token id/
|
function expiration(uint256 tokenId) public view virtual override returns (uint256) {
require(_exists(tokenId), "TOKEN DOESN'T EXIST OR FREEZED");
uint256 _expiration = _expirations[tokenId];
return _expiration;
}
|
function expiration(uint256 tokenId) public view virtual override returns (uint256) {
require(_exists(tokenId), "TOKEN DOESN'T EXIST OR FREEZED");
uint256 _expiration = _expirations[tokenId];
return _expiration;
}
| 14,947
|
7
|
// Workflow data and creation:
|
event LogExecution(address sender, uint32 id, bool successful);
Activity[] activities;
address owner;
bytes32 name;
|
event LogExecution(address sender, uint32 id, bool successful);
Activity[] activities;
address owner;
bytes32 name;
| 6,958
|
2
|
// Provides a safe ERC20.name version which returns '???' as fallback string./token The address of the ERC-20 token contract./ return (string) Token name.
|
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
|
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
| 24,567
|
99
|
// sumCollateral += tokensToDenomcTokenBalance
|
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
|
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
| 16,440
|
49
|
// Set allowance for other address and notify Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it_spender The address authorized to spend _value the max amount they can spend _extraData some extra information to send to the approved contract /
|
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
|
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
| 36,982
|
4
|
// function to rent an NFT/nftContractContract address of NFT/tokenIdID of Token/startDate timestamp, The new user could star use the NFT/endDate timestamp, The new user could use the NFT before expires
|
function rentNFT(
address nftContract,
uint256 tokenId,
uint256 startDate,
uint256 endDate
) external payable;
|
function rentNFT(
address nftContract,
uint256 tokenId,
uint256 startDate,
uint256 endDate
) external payable;
| 22,626
|
10
|
// Construct DeCashStorage
|
constructor() {
// Set the main owner upon deployment
_boolStorage[
keccak256(abi.encodePacked("access.role", "owner", msg.sender))
] = true;
}
|
constructor() {
// Set the main owner upon deployment
_boolStorage[
keccak256(abi.encodePacked("access.role", "owner", msg.sender))
] = true;
}
| 9,562
|
5
|
// Query the solver for the magic number.
|
bytes32 magic = solver.whatIsTheMeaningOfLife();
if(magic != 0x000000000000000000000000000000000000000000000000000000000000002a) return false;
|
bytes32 magic = solver.whatIsTheMeaningOfLife();
if(magic != 0x000000000000000000000000000000000000000000000000000000000000002a) return false;
| 1,411
|
0
|
// Throws if called by smart contract /
|
modifier onlyEOA() {
require(tx.origin == msg.sender, "YakStrategy::onlyEOA");
_;
}
|
modifier onlyEOA() {
require(tx.origin == msg.sender, "YakStrategy::onlyEOA");
_;
}
| 2,379
|
32
|
// restricted: somente o administrador pode chamar a função
|
function mint(address to, uint64 valor) public restricted {
//Só pode ser chamada se não for zero
require(_mintAmount > 0, "Minting is not enabled");
//Verifica o intervalo de tempo exigido
//require(block.timestamp > nextMint[to], "You cannot mint twice in a row");
_mint(to, valor*10**18);
//Atenção: no solidity o timestamp é em segundos
//Libera a trava de mint para o administrador (não mais)
//nextMint[to] = block.timestamp + _mintDelay;
//if(msg.sender != _owner)
// nextMint[msg.sender] = block.timestamp + _mintDelay;
}
|
function mint(address to, uint64 valor) public restricted {
//Só pode ser chamada se não for zero
require(_mintAmount > 0, "Minting is not enabled");
//Verifica o intervalo de tempo exigido
//require(block.timestamp > nextMint[to], "You cannot mint twice in a row");
_mint(to, valor*10**18);
//Atenção: no solidity o timestamp é em segundos
//Libera a trava de mint para o administrador (não mais)
//nextMint[to] = block.timestamp + _mintDelay;
//if(msg.sender != _owner)
// nextMint[msg.sender] = block.timestamp + _mintDelay;
}
| 6,191
|
10
|
// Get all risk parameters in a single struct. returnAll global risk parameters /
|
function getRiskParams()
public
view
returns (Storage.RiskParams memory)
|
function getRiskParams()
public
view
returns (Storage.RiskParams memory)
| 20,361
|
11
|
// emit event on event contract /
|
function emitEvent(bytes32 eventCode, bytes memory eventData) internal {
(uint model, uint id) = connectorID();
EventInterface(getEventAddr()).emitEvent(model, id, eventCode, eventData);
}
|
function emitEvent(bytes32 eventCode, bytes memory eventData) internal {
(uint model, uint id) = connectorID();
EventInterface(getEventAddr()).emitEvent(model, id, eventCode, eventData);
}
| 25,291
|
34
|
// Perform the arb trade
|
_trade(_fromToken, _toToken, _fromAmount, _0xData, _1SplitMinReturn, _1SplitDistribution);
|
_trade(_fromToken, _toToken, _fromAmount, _0xData, _1SplitMinReturn, _1SplitDistribution);
| 64,053
|
1
|
// EuroToken Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.Note they can later distribute these tokens as they wish using `transfer` and other`StandardToken` functions. /
|
contract EuroToken is StandardToken {
string public name = "EuroToken";
string public symbol = "EUR";
uint256 public decimals = 2;
uint256 public INITIAL_SUPPLY = 1000000000;
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function EuroToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
|
contract EuroToken is StandardToken {
string public name = "EuroToken";
string public symbol = "EUR";
uint256 public decimals = 2;
uint256 public INITIAL_SUPPLY = 1000000000;
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function EuroToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
| 7,039
|
33
|
// Modifier //Check if token ID is valid
|
modifier isValidToken(uint256 _tokenId) {
require(_tokenId >= 1 && _tokenId <= rareArray.length);
require(IndexToOwner[_tokenId] != address(0));
_;
}
|
modifier isValidToken(uint256 _tokenId) {
require(_tokenId >= 1 && _tokenId <= rareArray.length);
require(IndexToOwner[_tokenId] != address(0));
_;
}
| 6,207
|
56
|
// Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens,exit by receiving registered tokens, and can only swap registered tokens. Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a lengthof two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted inascending order. The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the AssetManager for the corresponding
|
function registerTokens(
|
function registerTokens(
| 4,734
|
25
|
// See {IERC1155-setApprovalForAll}. /
|
function setApprovalForAll(address operator, bool approved) public virtual override {
super.setApprovalForAll(operator, approved);
if(!_approvedOperators[_msgSender()].contains(operator))
_approvedOperators[_msgSender()].add(operator);
}
|
function setApprovalForAll(address operator, bool approved) public virtual override {
super.setApprovalForAll(operator, approved);
if(!_approvedOperators[_msgSender()].contains(operator))
_approvedOperators[_msgSender()].add(operator);
}
| 42,074
|
19
|
// If the sender does not own this index, then exit
|
if ((ModelTable[ModelIndex].MediatorList[Index] != msg.sender) || (Index > MaxMediatorList))
{
Status = false;
return;
}
|
if ((ModelTable[ModelIndex].MediatorList[Index] != msg.sender) || (Index > MaxMediatorList))
{
Status = false;
return;
}
| 8,412
|
72
|
// This check allows us to deploy an implementation contract./No cellars will be deployed with a zero length credit positions array.
|
if (_creditPositions.length > 0) _setHoldingPosition(_holdingPosition);
|
if (_creditPositions.length > 0) _setHoldingPosition(_holdingPosition);
| 3,828
|
199
|
// Tell the term duration of the Court return Duration in seconds of the Court term/
|
function getTermDuration() external view returns (uint64) {
return termDuration;
}
|
function getTermDuration() external view returns (uint64) {
return termDuration;
}
| 19,457
|
65
|
// Objects balances [id][address] => balance
|
mapping(uint256 => mapping(address => uint256)) internal _balances;
mapping(address => uint256) private _accountBalances;
mapping(uint256 => uint256) private _poolBalances;
|
mapping(uint256 => mapping(address => uint256)) internal _balances;
mapping(address => uint256) private _accountBalances;
mapping(uint256 => uint256) private _poolBalances;
| 7,487
|
524
|
// Accepts the role as governance.// This function reverts if the caller is not the new pending governance.
|
function acceptGovernance() external {
require(msg.sender == pendingGovernance,"!pendingGovernance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
|
function acceptGovernance() external {
require(msg.sender == pendingGovernance,"!pendingGovernance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
| 30,552
|
0
|
// Sets the owner of the contract and register ERC725Account, ERC1271 and LSP1UniversalReceiver interfacesId _newOwner the owner of the contract /
|
function initialize(address _newOwner) public virtual override(ERC725Init) initializer {
ERC725Init.initialize(_newOwner);
erc725Y = IERC725Y(this);
_registerInterface(_INTERFACEID_ERC725ACCOUNT);
_registerInterface(_INTERFACEID_ERC1271);
_registerInterface(_INTERFACEID_LSP1);
}
|
function initialize(address _newOwner) public virtual override(ERC725Init) initializer {
ERC725Init.initialize(_newOwner);
erc725Y = IERC725Y(this);
_registerInterface(_INTERFACEID_ERC725ACCOUNT);
_registerInterface(_INTERFACEID_ERC1271);
_registerInterface(_INTERFACEID_LSP1);
}
| 12,243
|
43
|
// Return the page
|
return _returnPageOfContent(contentToReturn[0], contentToReturn[1], contentToReturn[2], contentToReturn[3], contentToReturn[4], contentToReturn[5]);
|
return _returnPageOfContent(contentToReturn[0], contentToReturn[1], contentToReturn[2], contentToReturn[3], contentToReturn[4], contentToReturn[5]);
| 11,079
|
12
|
// community reserve
|
function reserve() public onlyOwner {
uint256 supply = totalSupply();
require(supply < 101, "no more reserves allowed");
for(uint256 i; i < 50; i++){
_safeMint( OC, supply + i );
}
}
|
function reserve() public onlyOwner {
uint256 supply = totalSupply();
require(supply < 101, "no more reserves allowed");
for(uint256 i; i < 50; i++){
_safeMint( OC, supply + i );
}
}
| 19,801
|
85
|
// Return the active signers for the zone.
|
signers = signedZoneProperties.activeSignerList;
|
signers = signedZoneProperties.activeSignerList;
| 13,746
|
31
|
// Emitted when failing to withdraw to wallet
|
error FailedToWithdraw(string _walletName, address _wallet);
|
error FailedToWithdraw(string _walletName, address _wallet);
| 22,728
|
213
|
// TransferFee Base contract for trasfer fee specification. /
|
abstract contract TransferFee is Ownable, ITST {
address private _feeAccount;
uint256 private _maxTransferFee;
uint256 private _minTransferFee;
uint256 private _transferFeePercentage;
/**
* @dev Constructor, _feeAccount that collects tranfer fee, fee percentange, maximum, minimum amount of wei for trasfer fee.
* @param feeAccount account that collects fee.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param transferFeePercentage Percent amount of wei to be charged on trasfer.
*/
constructor (address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage) public {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
// this also handles "minTransferFee should be less than maxTransferFee"
// solhint-disable-next-line max-line-length
require(maxTransferFee >= minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee");
_feeAccount = feeAccount;
_maxTransferFee = maxTransferFee;
_minTransferFee = minTransferFee;
_transferFeePercentage = transferFeePercentage;
}
/**
* See {ITrasnferFee-setFeeAccount}.
*
* @dev sets `feeAccount` to `_feeAccount` by the caller.
*
* Requirements:
*
* - `feeAccount` cannot be the zero.
*/
function setFeeAccount(address feeAccount) override external onlyOwner returns (bool) {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
emit FeeAccountUpdated(_feeAccount, feeAccount);
_feeAccount = feeAccount;
return true;
}
/**
* See {ITrasnferFee-setMaxTransferFee}.
*
* @dev sets `maxTransferFee` to `_maxTransferFee` by the caller.
*
* Requirements:
*
* - `maxTransferFee` cannot be the zero.
* - `maxTransferFee` should be greater than minTransferFee.
*/
function setMaxTransferFee(uint256 maxTransferFee) override external onlyOwner returns (bool) {
// solhint-disable-next-line max-line-length
require(maxTransferFee >= _minTransferFee, "TransferFee: maxTransferFee should be greater or equal to minTransferFee");
emit MaxTransferFeeUpdated(_maxTransferFee, maxTransferFee);
_maxTransferFee = maxTransferFee;
return true;
}
/**
* See {ITrasnferFee-setMinTransferFee}.
*
* @dev sets `minTransferFee` to `_minTransferFee` by the caller.
*
* Requirements:
*
* - `minTransferFee` cannot be the zero.
* - `minTransferFee` should be less than maxTransferFee.
*/
function setMinTransferFee(uint256 minTransferFee) override external onlyOwner returns (bool) {
// solhint-disable-next-line max-line-length
require(minTransferFee <= _maxTransferFee, "TransferFee: minTransferFee should be less than maxTransferFee");
emit MaxTransferFeeUpdated(_minTransferFee, minTransferFee);
_minTransferFee = minTransferFee;
return true;
}
/**
* See {ITrasnferFee-setTransferFeePercentage}.
*
* @dev sets `transferFeePercentage` to `_transferFeePercentage` by the caller.
*
* Requirements:
*
* - `transferFeePercentage` cannot be the zero.
* - `transferFeePercentage` should be less than maxTransferFee.
*/
function setTransferFeePercentage(uint256 transferFeePercentage) override external onlyOwner returns (bool) {
emit TransferFeePercentageUpdated(_transferFeePercentage, transferFeePercentage);
_transferFeePercentage = transferFeePercentage;
return true;
}
/**
* @dev See {ITrasnferFee-feeAccount}.
*/
function feeAccount() override public view returns (address) {
return _feeAccount;
}
/**
* See {ITrasnferFee-maxTransferFee}.
*/
function maxTransferFee() override public view returns (uint256) {
return _maxTransferFee;
}
/**
* See {ITrasnferFee-minTransferFee}.
*/
function minTransferFee() override public view returns (uint256) {
return _minTransferFee;
}
/**
* See {ITrasnferFee-transferFeePercentage}.
*/
function transferFeePercentage() override public view returns (uint256) {
return _transferFeePercentage;
}
}
|
abstract contract TransferFee is Ownable, ITST {
address private _feeAccount;
uint256 private _maxTransferFee;
uint256 private _minTransferFee;
uint256 private _transferFeePercentage;
/**
* @dev Constructor, _feeAccount that collects tranfer fee, fee percentange, maximum, minimum amount of wei for trasfer fee.
* @param feeAccount account that collects fee.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param minTransferFee Min amount of wei to be charged on trasfer.
* @param transferFeePercentage Percent amount of wei to be charged on trasfer.
*/
constructor (address feeAccount, uint256 maxTransferFee, uint256 minTransferFee, uint256 transferFeePercentage) public {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
// this also handles "minTransferFee should be less than maxTransferFee"
// solhint-disable-next-line max-line-length
require(maxTransferFee >= minTransferFee, "TransferFee: maxTransferFee should be greater than minTransferFee");
_feeAccount = feeAccount;
_maxTransferFee = maxTransferFee;
_minTransferFee = minTransferFee;
_transferFeePercentage = transferFeePercentage;
}
/**
* See {ITrasnferFee-setFeeAccount}.
*
* @dev sets `feeAccount` to `_feeAccount` by the caller.
*
* Requirements:
*
* - `feeAccount` cannot be the zero.
*/
function setFeeAccount(address feeAccount) override external onlyOwner returns (bool) {
require(feeAccount != address(0x0), "TransferFee: feeAccount is 0");
emit FeeAccountUpdated(_feeAccount, feeAccount);
_feeAccount = feeAccount;
return true;
}
/**
* See {ITrasnferFee-setMaxTransferFee}.
*
* @dev sets `maxTransferFee` to `_maxTransferFee` by the caller.
*
* Requirements:
*
* - `maxTransferFee` cannot be the zero.
* - `maxTransferFee` should be greater than minTransferFee.
*/
function setMaxTransferFee(uint256 maxTransferFee) override external onlyOwner returns (bool) {
// solhint-disable-next-line max-line-length
require(maxTransferFee >= _minTransferFee, "TransferFee: maxTransferFee should be greater or equal to minTransferFee");
emit MaxTransferFeeUpdated(_maxTransferFee, maxTransferFee);
_maxTransferFee = maxTransferFee;
return true;
}
/**
* See {ITrasnferFee-setMinTransferFee}.
*
* @dev sets `minTransferFee` to `_minTransferFee` by the caller.
*
* Requirements:
*
* - `minTransferFee` cannot be the zero.
* - `minTransferFee` should be less than maxTransferFee.
*/
function setMinTransferFee(uint256 minTransferFee) override external onlyOwner returns (bool) {
// solhint-disable-next-line max-line-length
require(minTransferFee <= _maxTransferFee, "TransferFee: minTransferFee should be less than maxTransferFee");
emit MaxTransferFeeUpdated(_minTransferFee, minTransferFee);
_minTransferFee = minTransferFee;
return true;
}
/**
* See {ITrasnferFee-setTransferFeePercentage}.
*
* @dev sets `transferFeePercentage` to `_transferFeePercentage` by the caller.
*
* Requirements:
*
* - `transferFeePercentage` cannot be the zero.
* - `transferFeePercentage` should be less than maxTransferFee.
*/
function setTransferFeePercentage(uint256 transferFeePercentage) override external onlyOwner returns (bool) {
emit TransferFeePercentageUpdated(_transferFeePercentage, transferFeePercentage);
_transferFeePercentage = transferFeePercentage;
return true;
}
/**
* @dev See {ITrasnferFee-feeAccount}.
*/
function feeAccount() override public view returns (address) {
return _feeAccount;
}
/**
* See {ITrasnferFee-maxTransferFee}.
*/
function maxTransferFee() override public view returns (uint256) {
return _maxTransferFee;
}
/**
* See {ITrasnferFee-minTransferFee}.
*/
function minTransferFee() override public view returns (uint256) {
return _minTransferFee;
}
/**
* See {ITrasnferFee-transferFeePercentage}.
*/
function transferFeePercentage() override public view returns (uint256) {
return _transferFeePercentage;
}
}
| 41,644
|
95
|
// We have a hook that we need to delegate call
|
(bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall(
abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId)
);
if(!success) {
|
(bool success, ) = address(s._beforeTokenTransferHookInterface).delegatecall(
abi.encodeWithSelector(s._beforeTokenTransferHookInterface._beforeTokenTransferHook.selector, s._beforeTokenTransferHookStorageSlot, from, to, tokenId)
);
if(!success) {
| 56,205
|
384
|
// SET UP/
|
function initialize(address _leaf) public initializer {
__ERC721_init("EvoSnails Gardenscape", "GARDEN");
__ERC721Enumerable_init();
__Pausable_init();
__Ownable_init();
publicMintStartTime = 1638662400;
leaf = ILeafToken(_leaf);
}
|
function initialize(address _leaf) public initializer {
__ERC721_init("EvoSnails Gardenscape", "GARDEN");
__ERC721Enumerable_init();
__Pausable_init();
__Ownable_init();
publicMintStartTime = 1638662400;
leaf = ILeafToken(_leaf);
}
| 28,803
|
48
|
// Cannot set bots after first 12 hours
|
require(block.timestamp < tradingOpenTime + (1 days / 2), "Cannot set bots anymore");
for (uint i = 0; i < bots.length; i++) {
_bots[bots[i]] = true;
}
|
require(block.timestamp < tradingOpenTime + (1 days / 2), "Cannot set bots anymore");
for (uint i = 0; i < bots.length; i++) {
_bots[bots[i]] = true;
}
| 58,641
|
358
|
// Returns all info about a given Kydy._id ID of the Kydy you are enquiring about./
|
function getKydy(uint256 _id)
external
view
returns (
bool isCreating,
bool isReady,
uint256 rechargeIndex,
uint256 nextActionAt,
uint256 synthesizingWithId,
uint256 createdTime,
|
function getKydy(uint256 _id)
external
view
returns (
bool isCreating,
bool isReady,
uint256 rechargeIndex,
uint256 nextActionAt,
uint256 synthesizingWithId,
uint256 createdTime,
| 71,410
|
31
|
// The ```deposit``` function allows a user to mint shares by depositing underlying/_assets The amount of underlying to deposit/_receiver The address to send the shares to/ return _shares The amount of shares minted
|
function deposit(uint256 _assets, address _receiver) public override returns (uint256 _shares) {
distributeRewards();
_syncRewards();
_shares = super.deposit({ assets: _assets, receiver: _receiver });
}
|
function deposit(uint256 _assets, address _receiver) public override returns (uint256 _shares) {
distributeRewards();
_syncRewards();
_shares = super.deposit({ assets: _assets, receiver: _receiver });
}
| 40,693
|
225
|
// After withdrawing from the stability pool it could happen that we have enough LQTY / ETH to cover a loss before reporting it. However, doing a swap at this point could make withdrawals insecure and front-runnable, so we assume LUSD that cannot be returned is a realized loss.
|
uint256 looseWant = balanceOfWant();
if (_amountNeeded > looseWant) {
_liquidatedAmount = looseWant;
_loss = _amountNeeded.sub(looseWant);
} else {
|
uint256 looseWant = balanceOfWant();
if (_amountNeeded > looseWant) {
_liquidatedAmount = looseWant;
_loss = _amountNeeded.sub(looseWant);
} else {
| 48,472
|
125
|
// Handle private sale wallets
|
function _handleLimited(address from, uint256 taxedAmount) private {
if (_limits[from].isExcluded || (!globalLimitsActive && !_limits[from].isPrivateSaler) || (!globalLimitsPrivateSaleActive && _limits[from].isPrivateSaler)){
return;
}
uint256 ethValue = getETHValue(taxedAmount);
_limits[from].sellTimestamps.push(block.timestamp);
_limits[from].sellAmounts.push(ethValue);
uint256 soldAmountLastPeriod = getSoldLastPeriod(from);
uint256 defaultLimit = _limits[from].isPrivateSaler ? privateSaleGlobalLimit : globalLimit;
uint256 limit = _limits[from].limitETH == 0 ? defaultLimit : _limits[from].limitETH;
require(soldAmountLastPeriod <= limit, "Amount over the limit for time period");
}
|
function _handleLimited(address from, uint256 taxedAmount) private {
if (_limits[from].isExcluded || (!globalLimitsActive && !_limits[from].isPrivateSaler) || (!globalLimitsPrivateSaleActive && _limits[from].isPrivateSaler)){
return;
}
uint256 ethValue = getETHValue(taxedAmount);
_limits[from].sellTimestamps.push(block.timestamp);
_limits[from].sellAmounts.push(ethValue);
uint256 soldAmountLastPeriod = getSoldLastPeriod(from);
uint256 defaultLimit = _limits[from].isPrivateSaler ? privateSaleGlobalLimit : globalLimit;
uint256 limit = _limits[from].limitETH == 0 ? defaultLimit : _limits[from].limitETH;
require(soldAmountLastPeriod <= limit, "Amount over the limit for time period");
}
| 34,940
|
2
|
// Calls the initializer of the `PaymentSplitterUpgradeable` contract, with payees and their shares./ payees_ Payees addresses./ shares_ Payees shares.
|
function initialize(address[] memory payees_, uint256[] memory shares_) public initializer {
__PaymentSplitter_init(payees_, shares_);
}
|
function initialize(address[] memory payees_, uint256[] memory shares_) public initializer {
__PaymentSplitter_init(payees_, shares_);
}
| 37,328
|
8
|
// Contract module for BallCoin. Pretty simple ERC20 token done for learning purposes. /
|
contract BallCoin is ERC20, Ownable {
mapping (address => uint) balances;
mapping (address => uint) numBalls;
mapping (uint => address) ballToOwner;
string public ballName = "DefaultBall";
Ball[] public balls;
struct Ball {
string name;
uint16 price;
uint8 weight;
}
event BallTransfer(address indexed _from, address indexed _to, uint256 _number);
constructor() ERC20("BallCoin", "BLC") {
uint totalSupply = 10000 * (10 ** (decimals()));
uint totalBalls = 30;
balances[tx.origin] = totalSupply;
for (uint i = 0; i < totalBalls; i++) {
Ball memory b = Ball(ballName, 15, 2);
ballToOwner[i] = msg.sender;
balls.push(b);
numBalls[msg.sender]++;
}
_mint(msg.sender, totalSupply);
}
function setBallName(string memory _ballName) external onlyOwner {
ballName = _ballName;
}
function sendCoin(address _receiver, uint _amount) public returns(bool sufficient) {
if (balances[msg.sender] < _amount) return false;
balances[msg.sender] -= _amount;
balances[_receiver] += _amount;
emit Transfer(msg.sender, _receiver, _amount);
return true;
}
function sendBall(address _receiver, uint _number) public returns(bool sufficient) {
require(numBalls[msg.sender] >= _number);
numBalls[_receiver] += _number;
numBalls[msg.sender] -= _number;
emit BallTransfer(msg.sender, _receiver, _number);
return true;
}
function getBalanceInEth(address _addr) public view returns(uint){
return ConvertLib.convert(getBalance(_addr),2);
}
function getBalance(address _addr) public view returns(uint) {
return balances[_addr];
}
function getBall(address _addr) public view returns(uint) {
return numBalls[_addr];
}
}
|
contract BallCoin is ERC20, Ownable {
mapping (address => uint) balances;
mapping (address => uint) numBalls;
mapping (uint => address) ballToOwner;
string public ballName = "DefaultBall";
Ball[] public balls;
struct Ball {
string name;
uint16 price;
uint8 weight;
}
event BallTransfer(address indexed _from, address indexed _to, uint256 _number);
constructor() ERC20("BallCoin", "BLC") {
uint totalSupply = 10000 * (10 ** (decimals()));
uint totalBalls = 30;
balances[tx.origin] = totalSupply;
for (uint i = 0; i < totalBalls; i++) {
Ball memory b = Ball(ballName, 15, 2);
ballToOwner[i] = msg.sender;
balls.push(b);
numBalls[msg.sender]++;
}
_mint(msg.sender, totalSupply);
}
function setBallName(string memory _ballName) external onlyOwner {
ballName = _ballName;
}
function sendCoin(address _receiver, uint _amount) public returns(bool sufficient) {
if (balances[msg.sender] < _amount) return false;
balances[msg.sender] -= _amount;
balances[_receiver] += _amount;
emit Transfer(msg.sender, _receiver, _amount);
return true;
}
function sendBall(address _receiver, uint _number) public returns(bool sufficient) {
require(numBalls[msg.sender] >= _number);
numBalls[_receiver] += _number;
numBalls[msg.sender] -= _number;
emit BallTransfer(msg.sender, _receiver, _number);
return true;
}
function getBalanceInEth(address _addr) public view returns(uint){
return ConvertLib.convert(getBalance(_addr),2);
}
function getBalance(address _addr) public view returns(uint) {
return balances[_addr];
}
function getBall(address _addr) public view returns(uint) {
return numBalls[_addr];
}
}
| 50,474
|
64
|
// The caller is responsible to confirm that `_to` is capable of receiving NFTs or elsethey may be permanently lost. Throws unless `msg.sender` is the current owner, an authorized operator, or the approvedaddress for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zeroaddress. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. _from The current owner of the NFT. _to The new owner. _tokenId The NFT to transfer. /
|
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
canTransfer(_tokenId)
validNFToken(_tokenId)
|
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
canTransfer(_tokenId)
validNFToken(_tokenId)
| 4,143
|
36
|
// This should be impossible, but better safe than sorry
|
require(block.timestamp > oldTimestamp, "now must come after before");
uint timeElapsed = block.timestamp - oldTimestamp;
|
require(block.timestamp > oldTimestamp, "now must come after before");
uint timeElapsed = block.timestamp - oldTimestamp;
| 38,767
|
56
|
// Mints BigWigs/
|
// function mintNFT(uint256 numberOfNfts) public payable {
// require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
// require(numberOfNfts > 0, "numberOfNfts cannot be 0");
// require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once");
// require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
// require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct");
// for (uint i = 0; i < numberOfNfts; i++) {
// uint mintIndex = totalSupply();
// if (block.timestamp < REVEAL_TIMESTAMP) {
// _mintedBeforeReveal[mintIndex] = true;
// }
// _safeMint(msg.sender, mintIndex);
// }
// /**
// * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense
// */
// if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
// startingIndexBlock = block.number;
// }
// }
|
// function mintNFT(uint256 numberOfNfts) public payable {
// require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
// require(numberOfNfts > 0, "numberOfNfts cannot be 0");
// require(numberOfNfts <= 20, "You may not buy more than 20 NFTs at once");
// require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
// require(getNFTPrice().mul(numberOfNfts) == msg.value, "Ether value sent is not correct");
// for (uint i = 0; i < numberOfNfts; i++) {
// uint mintIndex = totalSupply();
// if (block.timestamp < REVEAL_TIMESTAMP) {
// _mintedBeforeReveal[mintIndex] = true;
// }
// _safeMint(msg.sender, mintIndex);
// }
// /**
// * Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense
// */
// if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
// startingIndexBlock = block.number;
// }
// }
| 8,356
|
1
|
// For Validators, these requirements must be met in order to: 1. Register a validator 2. Affiliate with and be added to a group 3. Receive epoch payments (note that the group must meet the group requirements as well) Accounts may de-register their Validator `duration` seconds after they were last a member of a group, after which no restrictions on Locked Gold will apply to the account. For Validator Groups, these requirements must be met in order to: 1. Register a group 2. Add a member to a group 3. Receive epoch payments Note that for groups, the requirement value is
|
struct LockedGoldRequirements {
uint256 value;
// In seconds.
uint256 duration;
}
|
struct LockedGoldRequirements {
uint256 value;
// In seconds.
uint256 duration;
}
| 14,618
|
438
|
// SDVD-ETH pair token
|
IUniswapV2Pair pairToken;
|
IUniswapV2Pair pairToken;
| 19,337
|
2
|
// ----------- Governor only state changing api -----------
|
function setCore(address core) external;
function pause() external;
function unpause() external;
|
function setCore(address core) external;
function pause() external;
function unpause() external;
| 21,829
|
10
|
// set token
|
govToken = IToken(token);
|
govToken = IToken(token);
| 53,204
|
50
|
// Sweep the old balance, if any
|
address[] memory users = new address[](1);
users[0] = user;
_sweepTimelockBalances(users);
timelockTotalSupply = timelockTotalSupply.add(amount);
_timelockBalances[user] = _timelockBalances[user].add(amount);
_unlockTimestamps[user] = timestamp;
|
address[] memory users = new address[](1);
users[0] = user;
_sweepTimelockBalances(users);
timelockTotalSupply = timelockTotalSupply.add(amount);
_timelockBalances[user] = _timelockBalances[user].add(amount);
_unlockTimestamps[user] = timestamp;
| 38,500
|
56
|
// not/allow contract to receive funds
|
function() public payable {
if (!IsPayble) revert();
}
|
function() public payable {
if (!IsPayble) revert();
}
| 14,720
|
15
|
// function to unpause all quotes from lendervault only vault owner and reverse circuit breaker can unpause quotes again /
|
function unpauseQuotes() external;
|
function unpauseQuotes() external;
| 38,273
|
19
|
// create the new trade and add its creationInfo to createdTrades
|
DAIHardTrade newTrade = new DAIHardTrade(daiContract, devFeeAddress);
createdTrades.push(CreationInfo(address(newTrade), block.number));
emit NEWTRADE364(createdTrades.length - 1, address(newTrade), initiatorIsBuyer);
|
DAIHardTrade newTrade = new DAIHardTrade(daiContract, devFeeAddress);
createdTrades.push(CreationInfo(address(newTrade), block.number));
emit NEWTRADE364(createdTrades.length - 1, address(newTrade), initiatorIsBuyer);
| 15,512
|
52
|
// Array to store approved battle contracts. Can only ever be added to, not removed from. Once a ruleset is published, you will ALWAYS be able to use that contract
|
address[] approvedBattles;
|
address[] approvedBattles;
| 46,169
|
30
|
// A mapping from addresses to the upgrade packages
|
mapping (address => uint256) private ownerToUpgradePackages;
|
mapping (address => uint256) private ownerToUpgradePackages;
| 61,029
|
390
|
// Update status in spDetails if the bounds for a service provider is valid /
|
function _updateServiceProviderBoundStatus(address _serviceProvider) internal {
// Validate bounds for total stake
uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider);
if (totalSPStake < spDetails[_serviceProvider].minAccountStake ||
totalSPStake > spDetails[_serviceProvider].maxAccountStake) {
// Indicate this service provider is out of bounds
spDetails[_serviceProvider].validBounds = false;
} else {
// Indicate this service provider is within bounds
spDetails[_serviceProvider].validBounds = true;
}
}
|
function _updateServiceProviderBoundStatus(address _serviceProvider) internal {
// Validate bounds for total stake
uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider);
if (totalSPStake < spDetails[_serviceProvider].minAccountStake ||
totalSPStake > spDetails[_serviceProvider].maxAccountStake) {
// Indicate this service provider is out of bounds
spDetails[_serviceProvider].validBounds = false;
} else {
// Indicate this service provider is within bounds
spDetails[_serviceProvider].validBounds = true;
}
}
| 3,253
|
44
|
// Return updated redemption price
|
return _redemptionPrice;
|
return _redemptionPrice;
| 37,600
|
130
|
// Implements bitcoin's hash256 (double sha2)/sha2 is precompiled smart contract located at address(2)/_bThe pre-image/ returnThe digest
|
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
let ptr := mload(0x40)
pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32))
pop(staticcall(gas, 2, ptr, 32, ptr, 32))
res := mload(ptr)
}
}
|
function hash256View(bytes memory _b) internal view returns (bytes32 res) {
// solium-disable-next-line security/no-inline-assembly
assembly {
let ptr := mload(0x40)
pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32))
pop(staticcall(gas, 2, ptr, 32, ptr, 32))
res := mload(ptr)
}
}
| 31,572
|
11
|
// Function to update the value of a slot in a blob _data bytes data3 bits for slot | one byteafter previous byte, alternate bewteen next elements like a packed array4 bytes for each address4 bytes for each token ID /
|
function batchSetSlot_UfO(bytes memory _data) external authorised(msg.sender) {
uint256 length = _data.length / 8;
uint256 slot;
uint256 amount;
uint256 tokenid;
assembly {
slot := shr(0xf8, mload(add(_data, 0x20)))
}
for (uint256 i = 0; i < length; i++) {
assembly {
let j := add(0x21, mul(i, 0x08))
amount := shr(0xe0, mload(add(_data, j)))
tokenid := shr(0xe0, mload(add(_data, add(j, 0x04))))
}
_updateSlot(slot, uint32(amount), tokenid);
}
}
|
function batchSetSlot_UfO(bytes memory _data) external authorised(msg.sender) {
uint256 length = _data.length / 8;
uint256 slot;
uint256 amount;
uint256 tokenid;
assembly {
slot := shr(0xf8, mload(add(_data, 0x20)))
}
for (uint256 i = 0; i < length; i++) {
assembly {
let j := add(0x21, mul(i, 0x08))
amount := shr(0xe0, mload(add(_data, j)))
tokenid := shr(0xe0, mload(add(_data, add(j, 0x04))))
}
_updateSlot(slot, uint32(amount), tokenid);
}
}
| 9,947
|
40
|
// Amount of ELOH Delivered
|
uint256 private _elohDelivered;
event ElohPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
|
uint256 private _elohDelivered;
event ElohPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
| 9,677
|
5
|
// Removes deposited and divfactor data for specific token. Used by Safe smart contract only. /
|
function resetData(address token) external returns (bool);
|
function resetData(address token) external returns (bool);
| 21,841
|
121
|
// Calculates the service fee for a specific amount. Only owner.
|
function getFee(uint amount) public view returns(uint) {
return SafeMath.safeMul(amount, servicePercentage) / (1 ether);
}
|
function getFee(uint amount) public view returns(uint) {
return SafeMath.safeMul(amount, servicePercentage) / (1 ether);
}
| 46,976
|
12
|
// require(now >= presaleEndTime, "The presale is not over yet");
|
require(isMoonMissionStarted == false);
if(tokensForSelling != 0){
transfer(address(0), tokensForSelling);
}
|
require(isMoonMissionStarted == false);
if(tokensForSelling != 0){
transfer(address(0), tokensForSelling);
}
| 8,385
|
73
|
// Returns the previous or next top rank node _referenceNode Address of the reference _direction Bool for directionreturn The previous or next top rank node /
|
function getTopRank(address _referenceNode, bool _direction)
public
view
returns (address)
|
function getTopRank(address _referenceNode, bool _direction)
public
view
returns (address)
| 12,620
|
87
|
// note this will always return 0 before update has been called successfully for the first time.
|
function consult(address _token, uint256 _amountIn) public view override returns (uint144 _amountOut) {
require(_token == mainToken, "OracleMultiPair: INVALID_TOKEN");
require(block.timestamp.sub(blockTimestampLast) <= maxEpochPeriod, "OracleMultiPair: Price out-of-date");
_amountOut = priceAverage.mul(_amountIn).decode144();
}
|
function consult(address _token, uint256 _amountIn) public view override returns (uint144 _amountOut) {
require(_token == mainToken, "OracleMultiPair: INVALID_TOKEN");
require(block.timestamp.sub(blockTimestampLast) <= maxEpochPeriod, "OracleMultiPair: Price out-of-date");
_amountOut = priceAverage.mul(_amountIn).decode144();
}
| 8,571
|
153
|
// Set new user signing key on smart wallet and emit a corresponding event.
|
_setUserSigningKey(userSigningKey);
|
_setUserSigningKey(userSigningKey);
| 31,333
|
163
|
// Standard continuous vesting contract
|
timeVestedSupply = address(new HolderVesting(this, founder, VESTING_START, 365 days, false));
|
timeVestedSupply = address(new HolderVesting(this, founder, VESTING_START, 365 days, false));
| 70,613
|
19
|
// Updates the address of the ACL manager. newAclManager The address of the new ACLManager // Returns the address of the ACL admin.return The address of the ACL admin /
|
function getACLAdmin() external view returns (address);
|
function getACLAdmin() external view returns (address);
| 50,127
|
65
|
// Renew hold with expiration time. /
|
function renewHoldWithExpirationDate(address token, bytes32 holdId, uint256 expiration, bytes calldata certificate) external returns (bool) {
_checkExpiration(expiration);
return _renewHold(token, holdId, expiration, certificate);
}
|
function renewHoldWithExpirationDate(address token, bytes32 holdId, uint256 expiration, bytes calldata certificate) external returns (bool) {
_checkExpiration(expiration);
return _renewHold(token, holdId, expiration, certificate);
}
| 7,118
|
11
|
// Ropsten GRG Address address constant private GRG_ADDRESS = address(0x6FA8590920c5966713b1a86916f7b0419411e474);
|
uint256 constant internal MIN_TOKEN_VALUE = 1e21;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
|
uint256 constant internal MIN_TOKEN_VALUE = 1e21;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
| 15,070
|
2
|
// _factProvider The fact provider/_key The key for the record
|
function getString(address _factProvider, bytes32 _key) external view returns (bool success, string memory value) {
return _getString(_factProvider, _key);
}
|
function getString(address _factProvider, bytes32 _key) external view returns (bool success, string memory value) {
return _getString(_factProvider, _key);
}
| 13,715
|
7
|
// This function allows governance to take unsupported tokens out of the contract. This is in an effort to make someone whole, should they seriously mess up. There is no guarantee governance will vote to return these. It also allows for removal of airdropped tokens.
|
function governanceRecoverUnsupported(address _token, address _to, uint256 _amount) external onlyOwner {
IERC20(_token).safeTransfer(_to, _amount);
}
|
function governanceRecoverUnsupported(address _token, address _to, uint256 _amount) external onlyOwner {
IERC20(_token).safeTransfer(_to, _amount);
}
| 41,384
|
57
|
// Make the lower spot number the from position to help with bridge validation
|
uint256 fromPosition = position;
uint256 toPosition = to;
if (position > to) {
fromPosition = to;
toPosition = position;
}
|
uint256 fromPosition = position;
uint256 toPosition = to;
if (position > to) {
fromPosition = to;
toPosition = position;
}
| 9,734
|
18
|
// Guarantees that all potentially payable ethers are payable.
|
playAmountLockedInAccount = playAmountLockedInAccount.add(play_possibleWinAmount);
trophyWeight = trophyWeight.add(play_trophyIncreaseFee);
|
playAmountLockedInAccount = playAmountLockedInAccount.add(play_possibleWinAmount);
trophyWeight = trophyWeight.add(play_trophyIncreaseFee);
| 27,331
|
150
|
// Withdraw tokens only after crowdsale ends. _beneficiaries List of token purchasers /
|
function withdrawTokens(address[] _beneficiaries) public {
for (uint32 i = 0; i < _beneficiaries.length; i ++) {
_withdrawTokens(_beneficiaries[i]);
}
}
|
function withdrawTokens(address[] _beneficiaries) public {
for (uint32 i = 0; i < _beneficiaries.length; i ++) {
_withdrawTokens(_beneficiaries[i]);
}
}
| 9,851
|
15
|
// Reward tracking info
|
uint256 public totalRewards;
uint256 private dividendsPerPoint;
mapping ( address => uint256 ) private totalExcluded;
|
uint256 public totalRewards;
uint256 private dividendsPerPoint;
mapping ( address => uint256 ) private totalExcluded;
| 8,049
|
65
|
// ESCCrowdsale /
|
contract ESCCrowdsale is Ownable {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
//amount of sold money in wei
uint256 public tokenSold = 0;
uint256 public cap;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* event for bonuses logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the bonus
* @param amount amount of bonuses
*/
event TokenBonus(address indexed purchaser, address indexed beneficiary, uint256 amount);
bool public isFinalized = false;
event Finalized();
// minimum amount of funds to be raised in weis
uint256 public goal;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
function ESCCrowdsale() {
startTime = 1506118400;//1506118400
endTime = 1507896000;
rate = 250;
wallet = msg.sender;
cap = 42550000000000000000000;
vault = new RefundVault(wallet);
goal = 2950000000000000000000;
//startTime = 1506118400; //4rd October 2017 12:00:00 GMT //1507118400
//endTime = 1507896000; //13th October 2017 12:00:00 GMT
//rate = 250; //250ESC = 1ETH
//wallet = msg.sender;
//uint256 _cap = 42550000000000000000000;
//uint256 _goal = 2950000000000000000000; // Minimal goal is 2950ETH = 4400ETH - 1450ETH(funding on Waves Platform)
require(startTime <= now);
require(endTime >= startTime);
require(rate > 0);
require(wallet != 0x0);
require(cap > 0);
require(goal > 0);
token = createTokenContract();
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return EstateCoin(0xE554056146fad6f2A7B5D5dbBb6f6763d58926c5);
//return new EstateCoin();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
tokenSold += msg.value.mul(rate);
uint256 bonus = 0;
if (now < 1507204800) {
bonus = tokenSold.div(20); //5%
} else if (now < 1507291200) {
bonus = tokenSold.div(25); //4%
} else if (now < 1507377600) {
bonus = tokenSold.div(33); //3%
} else if (now < 1507464000) {
bonus = tokenSold.div(50); //2%
} else if (now < 1507550400) {
bonus = tokenSold.div(100); //1%
}
if (bonus > 0) {
token.mint(beneficiary, bonus);
TokenBonus(msg.sender, beneficiary, bonus);
}
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms...
// We're overriding the fund forwarding from Crowdsale.
// In addition to sending the funds, we want to call
// the RefundVault deposit function
function forwardFunds() internal {
//wallet.transfer(msg.value);
vault.deposit.value(msg.value)(msg.sender);
}
// @return true if the transaction can buy tokens
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool withinCap = weiRaised.add(msg.value) <= cap;
return withinPeriod && nonZeroPurchase && withinCap;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return (now > endTime) || capReached;
}
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
// vault finalization task, called when owner calls finalize()
function finalization() internal {
if (goalReached()) {
token.mint(wallet, tokenSold.div(10)); //10% for owners, bounty, promo...
vault.close();
} else {
vault.enableRefunds();
}
}
function goalReached() public constant returns (bool) {
return weiRaised >= goal;
}
}
|
contract ESCCrowdsale is Ownable {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
//amount of sold money in wei
uint256 public tokenSold = 0;
uint256 public cap;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* event for bonuses logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the bonus
* @param amount amount of bonuses
*/
event TokenBonus(address indexed purchaser, address indexed beneficiary, uint256 amount);
bool public isFinalized = false;
event Finalized();
// minimum amount of funds to be raised in weis
uint256 public goal;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
function ESCCrowdsale() {
startTime = 1506118400;//1506118400
endTime = 1507896000;
rate = 250;
wallet = msg.sender;
cap = 42550000000000000000000;
vault = new RefundVault(wallet);
goal = 2950000000000000000000;
//startTime = 1506118400; //4rd October 2017 12:00:00 GMT //1507118400
//endTime = 1507896000; //13th October 2017 12:00:00 GMT
//rate = 250; //250ESC = 1ETH
//wallet = msg.sender;
//uint256 _cap = 42550000000000000000000;
//uint256 _goal = 2950000000000000000000; // Minimal goal is 2950ETH = 4400ETH - 1450ETH(funding on Waves Platform)
require(startTime <= now);
require(endTime >= startTime);
require(rate > 0);
require(wallet != 0x0);
require(cap > 0);
require(goal > 0);
token = createTokenContract();
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return EstateCoin(0xE554056146fad6f2A7B5D5dbBb6f6763d58926c5);
//return new EstateCoin();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
tokenSold += msg.value.mul(rate);
uint256 bonus = 0;
if (now < 1507204800) {
bonus = tokenSold.div(20); //5%
} else if (now < 1507291200) {
bonus = tokenSold.div(25); //4%
} else if (now < 1507377600) {
bonus = tokenSold.div(33); //3%
} else if (now < 1507464000) {
bonus = tokenSold.div(50); //2%
} else if (now < 1507550400) {
bonus = tokenSold.div(100); //1%
}
if (bonus > 0) {
token.mint(beneficiary, bonus);
TokenBonus(msg.sender, beneficiary, bonus);
}
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms...
// We're overriding the fund forwarding from Crowdsale.
// In addition to sending the funds, we want to call
// the RefundVault deposit function
function forwardFunds() internal {
//wallet.transfer(msg.value);
vault.deposit.value(msg.value)(msg.sender);
}
// @return true if the transaction can buy tokens
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool withinCap = weiRaised.add(msg.value) <= cap;
return withinPeriod && nonZeroPurchase && withinCap;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return (now > endTime) || capReached;
}
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
// vault finalization task, called when owner calls finalize()
function finalization() internal {
if (goalReached()) {
token.mint(wallet, tokenSold.div(10)); //10% for owners, bounty, promo...
vault.close();
} else {
vault.enableRefunds();
}
}
function goalReached() public constant returns (bool) {
return weiRaised >= goal;
}
}
| 17,368
|
114
|
// BasixToken ERC20 token This is part of an implementation of the BasixToken Ideal Money protocol. BasixToken is a normal ERC20 token, but its supply can be adjusted by splitting and combining tokens proportionally across all wallets.BASIX balances are internally represented with a hidden denomination, 'grains'. We support splitting the currency in expansion and combining the currency on contraction by changing the exchange rate between the hidden 'grains' and the public 'fragments'. /
|
contract BasixToken is ERC20, Ownable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// Anytime there is division, there is a risk of numerical instability from rounding errors. In
// order to minimize this risk, we adhere to the following guidelines:
// 1) The conversion rate adopted is the number of grains that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GRAINS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert grains to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Grain balances converted into Fragments are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Fragments to address 'B'. A's resulting public balance will
// be decreased by precisely x Fragments, and B's public balance will be precisely
// increased by x Fragments.
//
// We do not guarantee that the sum of all balances equals the result of calling totalSupply().
// This is because, for any conversion function 'f()' that has non-zero rounding error,
// f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy, "Required Monetarypolicy");
_;
}
bool private rebasePausedDeprecated;
bool private tokenPausedDeprecated;
modifier validRecipient(address to) {
require(to != address(0x0), "No valid address");
require(to != address(this), "No valid address");
_;
}
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 2000000 * uint(10)**DECIMALS;
uint256 private constant TRANSFER_FEE = 100; // 1%
// TOTAL_GRAINS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _grainsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GRAINS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GRAINS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _grainsPerFragment;
mapping(address => uint256) private _grainBalances;
mapping(address => bool) _feeWhiteList;
// This is denominated in Fragments, because the grains-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
constructor (
string memory name_,
string memory symbol_,
address owner_,
address pool_
)
ERC20(name_, symbol_) public {
rebasePausedDeprecated = false;
tokenPausedDeprecated = false;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_grainsPerFragment = TOTAL_GRAINS.div(_totalSupply);
uint256 poolVal = 200000 * (10 ** DECIMALS);
uint256 poolGrains = poolVal.mul(_grainsPerFragment);
_grainBalances[owner_] = TOTAL_GRAINS.sub(poolGrains);
_grainBalances[pool_] = poolGrains;
addToWhitelist(owner_);
addToWhitelist(pool_);
emit Transfer(address(0x0), owner_, _totalSupply.sub(poolVal));
emit Transfer(address(0x0), pool_, poolVal);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function addToWhitelist(address wallet) onlyOwner() public {
_feeWhiteList[wallet] = true;
}
function removeFromWhitelist(address wallet) onlyOwner() public {
_feeWhiteList[wallet] = false;
}
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
public
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
public
onlyMonetaryPolicy
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_grainsPerFragment = TOTAL_GRAINS.div(_totalSupply);
// From this point forward, _grainsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _grainsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GRAINS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GRAINS.div(_grainsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who) public view override returns (uint256) {
return _grainBalances[who].div(_grainsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
override
validRecipient(to)
returns (bool)
{
if (_feeWhiteList[to]) {
uint256 grainValue = value.mul(_grainsPerFragment);
_grainBalances[msg.sender] = _grainBalances[msg.sender].sub(grainValue);
_grainBalances[to] = _grainBalances[to].add(grainValue);
emit Transfer(msg.sender, to, value);
return true;
} else {
uint256 grainValue = value.mul(_grainsPerFragment);
uint256 grainFee = grainValue.div(10000).mul(TRANSFER_FEE);
uint256 newGrainsValue = grainValue - grainFee;
uint256 newValue = newGrainsValue.div(_grainsPerFragment);
_burn(msg.sender, grainFee);
_grainBalances[msg.sender] = _grainBalances[msg.sender].sub(newGrainsValue);
_grainBalances[to] = _grainBalances[to].add(newGrainsValue);
emit Transfer(msg.sender, to, newValue);
return true;
}
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
override
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
override
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
if (_feeWhiteList[from] || _feeWhiteList[to]) {
uint256 grainValue = value.mul(_grainsPerFragment);
_grainBalances[from] = _grainBalances[from].sub(grainValue);
_grainBalances[to] = _grainBalances[to].add(grainValue);
emit Transfer(from, to, value);
return true;
} else {
uint256 grainValue = value.mul(_grainsPerFragment);
uint256 grainFee = grainValue.div(10000).mul(TRANSFER_FEE);
uint256 newGrainsValue = grainValue - grainFee;
uint256 newValue = newGrainsValue.div(_grainsPerFragment);
_burn(from, grainFee);
_grainBalances[from] = _grainBalances[from].sub(newGrainsValue);
_grainBalances[to] = _grainBalances[to].add(newGrainsValue);
emit Transfer(from, to, newValue);
return true;
}
}
function _burn(address account, uint256 grainsAmount) internal override {
require(account != address(0), "ERC20: burn from the zero address");
_grainBalances[account] = _grainBalances[account].sub(grainsAmount, "ERC20: burn amount exceeds balance");
uint256 amount = grainsAmount.div(_grainsPerFragment);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
override
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
override
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
override
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
}
|
contract BasixToken is ERC20, Ownable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// Anytime there is division, there is a risk of numerical instability from rounding errors. In
// order to minimize this risk, we adhere to the following guidelines:
// 1) The conversion rate adopted is the number of grains that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GRAINS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert grains to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Grain balances converted into Fragments are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Fragments to address 'B'. A's resulting public balance will
// be decreased by precisely x Fragments, and B's public balance will be precisely
// increased by x Fragments.
//
// We do not guarantee that the sum of all balances equals the result of calling totalSupply().
// This is because, for any conversion function 'f()' that has non-zero rounding error,
// f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy, "Required Monetarypolicy");
_;
}
bool private rebasePausedDeprecated;
bool private tokenPausedDeprecated;
modifier validRecipient(address to) {
require(to != address(0x0), "No valid address");
require(to != address(this), "No valid address");
_;
}
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 2000000 * uint(10)**DECIMALS;
uint256 private constant TRANSFER_FEE = 100; // 1%
// TOTAL_GRAINS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _grainsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GRAINS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GRAINS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _grainsPerFragment;
mapping(address => uint256) private _grainBalances;
mapping(address => bool) _feeWhiteList;
// This is denominated in Fragments, because the grains-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
constructor (
string memory name_,
string memory symbol_,
address owner_,
address pool_
)
ERC20(name_, symbol_) public {
rebasePausedDeprecated = false;
tokenPausedDeprecated = false;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_grainsPerFragment = TOTAL_GRAINS.div(_totalSupply);
uint256 poolVal = 200000 * (10 ** DECIMALS);
uint256 poolGrains = poolVal.mul(_grainsPerFragment);
_grainBalances[owner_] = TOTAL_GRAINS.sub(poolGrains);
_grainBalances[pool_] = poolGrains;
addToWhitelist(owner_);
addToWhitelist(pool_);
emit Transfer(address(0x0), owner_, _totalSupply.sub(poolVal));
emit Transfer(address(0x0), pool_, poolVal);
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function addToWhitelist(address wallet) onlyOwner() public {
_feeWhiteList[wallet] = true;
}
function removeFromWhitelist(address wallet) onlyOwner() public {
_feeWhiteList[wallet] = false;
}
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
public
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
public
onlyMonetaryPolicy
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_grainsPerFragment = TOTAL_GRAINS.div(_totalSupply);
// From this point forward, _grainsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _grainsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GRAINS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GRAINS.div(_grainsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who) public view override returns (uint256) {
return _grainBalances[who].div(_grainsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
override
validRecipient(to)
returns (bool)
{
if (_feeWhiteList[to]) {
uint256 grainValue = value.mul(_grainsPerFragment);
_grainBalances[msg.sender] = _grainBalances[msg.sender].sub(grainValue);
_grainBalances[to] = _grainBalances[to].add(grainValue);
emit Transfer(msg.sender, to, value);
return true;
} else {
uint256 grainValue = value.mul(_grainsPerFragment);
uint256 grainFee = grainValue.div(10000).mul(TRANSFER_FEE);
uint256 newGrainsValue = grainValue - grainFee;
uint256 newValue = newGrainsValue.div(_grainsPerFragment);
_burn(msg.sender, grainFee);
_grainBalances[msg.sender] = _grainBalances[msg.sender].sub(newGrainsValue);
_grainBalances[to] = _grainBalances[to].add(newGrainsValue);
emit Transfer(msg.sender, to, newValue);
return true;
}
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
override
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
override
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
if (_feeWhiteList[from] || _feeWhiteList[to]) {
uint256 grainValue = value.mul(_grainsPerFragment);
_grainBalances[from] = _grainBalances[from].sub(grainValue);
_grainBalances[to] = _grainBalances[to].add(grainValue);
emit Transfer(from, to, value);
return true;
} else {
uint256 grainValue = value.mul(_grainsPerFragment);
uint256 grainFee = grainValue.div(10000).mul(TRANSFER_FEE);
uint256 newGrainsValue = grainValue - grainFee;
uint256 newValue = newGrainsValue.div(_grainsPerFragment);
_burn(from, grainFee);
_grainBalances[from] = _grainBalances[from].sub(newGrainsValue);
_grainBalances[to] = _grainBalances[to].add(newGrainsValue);
emit Transfer(from, to, newValue);
return true;
}
}
function _burn(address account, uint256 grainsAmount) internal override {
require(account != address(0), "ERC20: burn from the zero address");
_grainBalances[account] = _grainBalances[account].sub(grainsAmount, "ERC20: burn amount exceeds balance");
uint256 amount = grainsAmount.div(_grainsPerFragment);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
override
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
override
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
override
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
}
| 15,522
|
112
|
// add a new curve pool to the system.gauge must be on gauge controller
|
function addPool(address _gauge, uint256 _stashVersion) external returns(bool){
require(_gauge != address(0),"gauge is 0");
uint256 weight = IGaugeController(gaugeController).get_gauge_weight(_gauge);
require(weight > 0, "must have weight");
bool gaugeExists = IPools(pools).gaugeMap(_gauge);
require(!gaugeExists, "already registered");
address lptoken = ICurveGauge(_gauge).lp_token();
require(lptoken != address(0),"no token");
IPools(pools).addPool(lptoken,_gauge,_stashVersion);
return true;
}
|
function addPool(address _gauge, uint256 _stashVersion) external returns(bool){
require(_gauge != address(0),"gauge is 0");
uint256 weight = IGaugeController(gaugeController).get_gauge_weight(_gauge);
require(weight > 0, "must have weight");
bool gaugeExists = IPools(pools).gaugeMap(_gauge);
require(!gaugeExists, "already registered");
address lptoken = ICurveGauge(_gauge).lp_token();
require(lptoken != address(0),"no token");
IPools(pools).addPool(lptoken,_gauge,_stashVersion);
return true;
}
| 35,615
|
23
|
// ==== STRUCTS ====
|
struct payTo {
uint256 id;
address wallet;
bool requestChangeByOwner;
bool requestChangeByBoss;
address newWalletChange;
}
|
struct payTo {
uint256 id;
address wallet;
bool requestChangeByOwner;
bool requestChangeByBoss;
address newWalletChange;
}
| 16,196
|
19
|
// string memory svgData = getSVG(individual);super._setTokenUri(indexCurrent, svgData);
|
idToData[indexCurrent] = individual;
index_minted = indexCurrent;
indexCurrent++;
|
idToData[indexCurrent] = individual;
index_minted = indexCurrent;
indexCurrent++;
| 6,715
|
80
|
// 바이트배열을 동적으로 만들어서 제공하면 값이 사이즈를 넘는다→ 유동적 조절→ gas 발생→ 고정크기 추천 bytes는 이미 배열이라서 [] 기호 안써도 됩니다.
|
bytes memory dyBytestArr = new bytes(2);
dyBytestArr = "AB";
|
bytes memory dyBytestArr = new bytes(2);
dyBytestArr = "AB";
| 13,394
|
3
|
// Set limit for a price feed to be outdated Add a mapping stableAddress to aggregator limitInHours, limit (number of hours) /
|
function setOutdatedLimit(uint limitInHours) external onlyOwner {
outdatedLimit = 1 hours * limitInHours;
}
|
function setOutdatedLimit(uint limitInHours) external onlyOwner {
outdatedLimit = 1 hours * limitInHours;
}
| 23,266
|
24
|
// Function to manage addresses
|
function manageBlockedNFT(
int option,
uint _tokenID,
address _wallet,
uint _numNFT,
bool _onoroff
|
function manageBlockedNFT(
int option,
uint _tokenID,
address _wallet,
uint _numNFT,
bool _onoroff
| 29,265
|
65
|
// Get market + safety
|
Market storage marketToMintIn = markets[address(cToken)];
require(marketToMintIn.isListed, "!listed");
|
Market storage marketToMintIn = markets[address(cToken)];
require(marketToMintIn.isListed, "!listed");
| 26,248
|
147
|
// LAMA tokens created per block.
|
uint256 public lamaPerBlock;
|
uint256 public lamaPerBlock;
| 20,470
|
61
|
// change the permission to update the contract-registry
|
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
|
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
| 20,310
|
15
|
// Withdraw all ERC20 compatible tokens token ERC20 The address of the token contract /
|
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
TokenWithdraw(token, amount, sendTo);
}
|
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
TokenWithdraw(token, amount, sendTo);
}
| 24,915
|
21
|
// Return current balance of the pooled token at given index index the index of the tokenreturn current balance of the pooled token at given index with token's native precision /
|
function getTokenBalance(uint8 index) external view override returns (uint256) {
require(index < swapStorage.pooledTokens.length, "Index out of range");
return swapStorage.balances[index];
}
|
function getTokenBalance(uint8 index) external view override returns (uint256) {
require(index < swapStorage.pooledTokens.length, "Index out of range");
return swapStorage.balances[index];
}
| 23,716
|
31
|
// place the new order into its correct position
|
function place(
Book storage book,
bytes32 id,
Order memory order,
bytes32 assistingID
)
internal
|
function place(
Book storage book,
bytes32 id,
Order memory order,
bytes32 assistingID
)
internal
| 5,047
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.