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
|
|---|---|---|---|---|
19
|
// ERC20Basic Simpler version of ERC20 interface /
|
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
|
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
| 42,412
|
185
|
// Get the address of the recovery Vault instance (to recover funds) return Address of the Vault/
|
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
|
function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
| 6,255
|
73
|
// Generates `_amount` tokens that are assigned to `_owner`/_user The address that will be assigned the new tokens/_amount The quantity of tokens generated/ return True if the tokens are generated correctly
|
function generateTokens(address _user, uint _amount) onlyController public returns (bool) {
require(balanceOf[owner] >= _amount);
balanceOf[_user] += _amount;
balanceOf[owner] -= _amount;
Transfer(0, _user, _amount);
return true;
}
|
function generateTokens(address _user, uint _amount) onlyController public returns (bool) {
require(balanceOf[owner] >= _amount);
balanceOf[_user] += _amount;
balanceOf[owner] -= _amount;
Transfer(0, _user, _amount);
return true;
}
| 78,125
|
5
|
// Removes the item at the end of the queue and returns it. Reverts with `Empty` if the queue is empty. /
|
function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) {
if (empty(deque)) revert Empty();
int128 backIndex;
unchecked {
backIndex = deque._end - 1;
}
value = deque._data[backIndex];
delete deque._data[backIndex];
deque._end = backIndex;
}
|
function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) {
if (empty(deque)) revert Empty();
int128 backIndex;
unchecked {
backIndex = deque._end - 1;
}
value = deque._data[backIndex];
delete deque._data[backIndex];
deque._end = backIndex;
}
| 1,703
|
24
|
// Calculate the power of a dungeon floor.
|
function getDungeonPower(uint _genes) public pure returns (uint);
|
function getDungeonPower(uint _genes) public pure returns (uint);
| 26,442
|
20
|
// Like divDown(), but it also works when `a` would overflow in `divDown`. d and e must be chosen such thatde = 1e18 (raw numbers, or de = 1e-18 with respect to the numbers they represent in fixed point). Note thatthis requires d, e ≤ 1e18 (raw, or d, e ≤ 1 with respect to the numbers represented).This operation is safe if both of- ad ≤ 1.15e77 (raw, i.e., ad ≤ 1.15e41 with respect to the value that is represented)- b ≥ e (with respect to raw or represented numbers)hold.Introduces some rounding error that is relevant iff b is small and
|
function divDownLarge(
uint256 a,
uint256 b,
uint256 d,
uint256 e
|
function divDownLarge(
uint256 a,
uint256 b,
uint256 d,
uint256 e
| 17,891
|
6
|
// An array of list addresses.
|
address[] public lists;
|
address[] public lists;
| 48,848
|
17
|
// Public quack function/ quacks QUACK QUACK QUACK. Get with the QUACKING program
|
function quackQuackMfer(uint256 quacks) external payable {
/// Check if the sale is paused
require(saleState == SaleState.PUBLIC, "Ducks: Public Sale paused");
uint256 previous = _numberMinted(_msgSender());
// Check if user has not exceeded the max mint per wallet
require(
previous + quacks <= config.maxPublicMintPerWallet,
"Ducks: Exceeds public mint limit"
);
/// Check if the max supply has been reached
require(
totalSupply() + quacks <= config.maxSupply,
"Ducks: Max supply minted"
);
/// Check if the correct amount of ETH was sent
require(
msg.value >= config.publicMintPrice * quacks,
"Ducks: Incorrect amount sent"
);
/// Mint the token
_safeMint(_msgSender(), quacks);
}
|
function quackQuackMfer(uint256 quacks) external payable {
/// Check if the sale is paused
require(saleState == SaleState.PUBLIC, "Ducks: Public Sale paused");
uint256 previous = _numberMinted(_msgSender());
// Check if user has not exceeded the max mint per wallet
require(
previous + quacks <= config.maxPublicMintPerWallet,
"Ducks: Exceeds public mint limit"
);
/// Check if the max supply has been reached
require(
totalSupply() + quacks <= config.maxSupply,
"Ducks: Max supply minted"
);
/// Check if the correct amount of ETH was sent
require(
msg.value >= config.publicMintPrice * quacks,
"Ducks: Incorrect amount sent"
);
/// Mint the token
_safeMint(_msgSender(), quacks);
}
| 36,474
|
23
|
// Initializable allows to create initializable contractsso that only deployer can initialize contract and only once /
|
contract Initializable is Context {
bool private _isContractInitialized;
address private _deployer;
constructor() public {
_deployer = _msgSender();
}
modifier initializer {
require(_msgSender() == _deployer, "user not allowed to initialize");
require(!_isContractInitialized, "contract already initialized");
_;
_isContractInitialized = true;
}
}
|
contract Initializable is Context {
bool private _isContractInitialized;
address private _deployer;
constructor() public {
_deployer = _msgSender();
}
modifier initializer {
require(_msgSender() == _deployer, "user not allowed to initialize");
require(!_isContractInitialized, "contract already initialized");
_;
_isContractInitialized = true;
}
}
| 18,339
|
169
|
// To receive BNB from sharkRouter when swapping
|
receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "SHARK::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
|
receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOperator {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "SHARK::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
| 4,419
|
17
|
// Internal interface for the minting of tokens. /
|
contract Mintable {
/**
* @dev Mints tokens for an account
* This function should emit the Minted event.
*/
function mintInternal(address receiver, uint amount) internal;
/** Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
}
|
contract Mintable {
/**
* @dev Mints tokens for an account
* This function should emit the Minted event.
*/
function mintInternal(address receiver, uint amount) internal;
/** Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
}
| 33,107
|
51
|
// Distributor mints PLAY/_toAddress where to mint PLAY/_amountAmount of PLAY to mint
|
function mint(address _to, uint256 _amount) external {
require(msg.sender == distributor, "msg.sender is not distributor");
IPLAY(PLAY).mint(_to, _amount);
}
|
function mint(address _to, uint256 _amount) external {
require(msg.sender == distributor, "msg.sender is not distributor");
IPLAY(PLAY).mint(_to, _amount);
}
| 43,659
|
9
|
// returns periodic release number.
|
function getPeriodicReleaseNum() public view returns (uint256) {
return periodicReleaseNum;
}
|
function getPeriodicReleaseNum() public view returns (uint256) {
return periodicReleaseNum;
}
| 29,232
|
78
|
// Contract module that allows children to implement role-based accesscontrol mechanisms. This is a lightweight version that doesn't allow enumerating rolemembers except through off-chain means by accessing the contract event logs. Someapplications may benefit from on-chain enumerability, for those cases see
|
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
|
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
| 246
|
85
|
// Confirms a pending change of the active implementation associated with this contract. When called by the custodian with a lock id associated with a pending change, the `ERC20Impl erc20Impl` member will be updated with the requested address. _lockIdThe identifier of a pending change request./
|
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
|
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
| 38,237
|
12
|
// ------------------------------------------------------------------------ Token Information ------------------------------------------------------------------------
|
string public name; // Full Token name
uint8 public decimals; // How many decimals to show
string public symbol; // An identifier
|
string public name; // Full Token name
uint8 public decimals; // How many decimals to show
string public symbol; // An identifier
| 16,267
|
14
|
// Modify the current _owner in newOwner - owner only allowed
|
function modifyOwner(address newOwner) public onlyOwner{
_owner = newOwner;
}
|
function modifyOwner(address newOwner) public onlyOwner{
_owner = newOwner;
}
| 7,331
|
9
|
// Emerald
|
if (ch == 0xa515) return 0x37Dfd1a00116d59a08B97D19F95f1c2a435fF5Df;
if (ch == 0xa516) return 0xd0dD1dFE79bB4Ad64d727Ee99F51cb968e949bf4;
|
if (ch == 0xa515) return 0x37Dfd1a00116d59a08B97D19F95f1c2a435fF5Df;
if (ch == 0xa516) return 0xd0dD1dFE79bB4Ad64d727Ee99F51cb968e949bf4;
| 26,455
|
54
|
// 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. The caller is responsible to confirm that `_to` is capable of receiving NFTs or elsethey may be permanently lost. _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)
| 33,015
|
161
|
// Check the execution price matches the order price
|
require(order.price == msg.value, "Marketplace: invalid price");
require(order.seller != msg.sender, "Marketplace: unauthorized sender");
order.currency == MARKETPLACE_ETHER ?
require(order.price == msg.value, "Marketplace: invalid price")
:
require(order.price == _priceInWei, "Marketplace: invalid price");
|
require(order.price == msg.value, "Marketplace: invalid price");
require(order.seller != msg.sender, "Marketplace: unauthorized sender");
order.currency == MARKETPLACE_ETHER ?
require(order.price == msg.value, "Marketplace: invalid price")
:
require(order.price == _priceInWei, "Marketplace: invalid price");
| 17,206
|
111
|
// Remove all Ether from the contract, which is the owner's cuts/as well as any Ether sent directly to the contract address./Always transfers to the NFT contract, but can be called either by/the owner or the NFT contract.
|
function withdrawBalance() external {
address payable nftAddress = address(uint160(address(nonFungibleContract)));
require(
msg.sender == owner ||
msg.sender == nftAddress
);
|
function withdrawBalance() external {
address payable nftAddress = address(uint160(address(nonFungibleContract)));
require(
msg.sender == owner ||
msg.sender == nftAddress
);
| 22,769
|
5
|
// only allow claiming a token once
|
require(balanceOf[_claimer][_tokenId] == 0, "You already claimed this token");
|
require(balanceOf[_claimer][_tokenId] == 0, "You already claimed this token");
| 19,394
|
307
|
// TODO: No spectral class for anyone else.
|
return SpectralType.NotApplicable;
|
return SpectralType.NotApplicable;
| 21,532
|
173
|
// address
|
address lyaconAddress;
address _owner;
|
address lyaconAddress;
address _owner;
| 10,021
|
58
|
// Ensure that the exchange percent is within the bounds we require
|
require(exchangeFeePercent < 100, "Exchange fee percent must be between 0 and 100");
|
require(exchangeFeePercent < 100, "Exchange fee percent must be between 0 and 100");
| 6,163
|
1
|
// A nonce used to ensure a certificate can be used only once
|
mapping(address => uint256) internal _checkCount;
event Checked(address sender);
|
mapping(address => uint256) internal _checkCount;
event Checked(address sender);
| 42,776
|
142
|
// the liquidation threshold of the reserve. Expressed in percentage (0-100)
|
uint256 liquidationThreshold;
|
uint256 liquidationThreshold;
| 9,530
|
47
|
// for example for conveting ALL tokens of user account to another tokens
|
function transferAllAndCall(address _to, bytes _extraData) public returns (bool success){
return transferAndCall(_to, balanceOf[msg.sender], _extraData);
}
|
function transferAllAndCall(address _to, bytes _extraData) public returns (bool success){
return transferAndCall(_to, balanceOf[msg.sender], _extraData);
}
| 42,821
|
39
|
// Used to terminate loop.We don't need to consider final 0 bits of sumIndex_
|
uint256 indexLSB = lsb(sumIndex_);
uint256 curIndex;
while (j >= indexLSB) {
curIndex = index + j;
|
uint256 indexLSB = lsb(sumIndex_);
uint256 curIndex;
while (j >= indexLSB) {
curIndex = index + j;
| 40,005
|
84
|
// token to forex
|
else if (freeRateTokenSymbols[fromSymb] != 0x0 && freeRateTokenSymbols[toSymb] == 0x0) {
uint256 toRate2 = getTokenToSynthOutputAmount(ERC20(freeRateTokenSymbols[fromSymb]), freeRateForexBytes[toSymb], amount);
return toRate2.mul(rateMultiply2).div(rateDivide2);
}
|
else if (freeRateTokenSymbols[fromSymb] != 0x0 && freeRateTokenSymbols[toSymb] == 0x0) {
uint256 toRate2 = getTokenToSynthOutputAmount(ERC20(freeRateTokenSymbols[fromSymb]), freeRateForexBytes[toSymb], amount);
return toRate2.mul(rateMultiply2).div(rateDivide2);
}
| 41,846
|
234
|
// Convert quadruple precision number into signed 64.64 bit fixed pointnumber.Revert on overflow.x quadruple precision numberreturn signed 64.64 bit fixed point number /
|
function to64x64 (bytes16 x) internal pure returns (int128) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x80000000000000000000000000000000);
return -int128 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (result);
}
}
|
function to64x64 (bytes16 x) internal pure returns (int128) {
uint256 exponent = uint128 (x) >> 112 & 0x7FFF;
require (exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result = uint256 (uint128 (x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128 (x) >= 0x80000000000000000000000000000000) { // Negative
require (result <= 0x80000000000000000000000000000000);
return -int128 (result); // We rely on overflow behavior here
} else {
require (result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (result);
}
}
| 31,178
|
6
|
// The total supply for any given type (int) /
|
mapping(uint => uint256) public carTypeTotalSupply;
|
mapping(uint => uint256) public carTypeTotalSupply;
| 566
|
132
|
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. For more discussion about choosing the value of `magnitude`,see https:github.com/ethereum/EIPs/issues/1726issuecomment-472352728
|
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
|
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
| 16,270
|
0
|
// Thrown when an allowance on a token has expired./deadline The timestamp at which the allowed amount is no longer valid
|
error AllowanceExpired(uint256 deadline);
|
error AllowanceExpired(uint256 deadline);
| 33,486
|
3
|
// 首先授权借的 dai 给 V2 router
|
IERC20(asset).approve(SWAP_V2_ROUTER, amount);
|
IERC20(asset).approve(SWAP_V2_ROUTER, amount);
| 21,699
|
91
|
// [MIT License]/Base64/Provides a function for encoding some bytes in base64/Brecht Devos <brecht@loopring.org>
|
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
|
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
| 7,898
|
45
|
// This is a burn
|
require(state == STATE_RUN, "ONLY_DURING_RUN");
|
require(state == STATE_RUN, "ONLY_DURING_RUN");
| 4,203
|
31
|
// transfer the reward tokens
|
IRW(RW).sendRewards(msg.sender, claimableReward);
emit RewardClaimed(msg.sender, claimableReward);
|
IRW(RW).sendRewards(msg.sender, claimableReward);
emit RewardClaimed(msg.sender, claimableReward);
| 22,157
|
2
|
// initialize a request with a callback function
|
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("n", "bitcoin"); // add query parameter n(name) in data json
request.add("p", "m"); // add query parameter p(period) in data json
|
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("n", "bitcoin"); // add query parameter n(name) in data json
request.add("p", "m"); // add query parameter p(period) in data json
| 31,235
|
1
|
// Calls burn function to "burn" specified amount of tokens./ from The address to burn tokens on./ amount The amount of tokens to burn.
|
function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
_burn(from, amount);
}
|
function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
_burn(from, amount);
}
| 37,914
|
5
|
// с альтернативной формой множественного числа именительного падежа ЛАГЕРЬ-ЛАГЕРЯ/ЛАГЕРИ
|
#define x1010(Слово) \
#begin
entry Слово : СУЩЕСТВИТЕЛЬНОЕ
|
#define x1010(Слово) \
#begin
entry Слово : СУЩЕСТВИТЕЛЬНОЕ
| 15,892
|
4
|
// Breed Corgis /
|
function breedCorgis(uint256 _parent1, uint256 _parent2, uint64 expireTime, bytes memory sig) external isSecured(1) {
bytes32 digest = keccak256(abi.encodePacked(msg.sender,expireTime));
require(isAuthorized(sig,digest),"CONTRACT_MINT_NOT_ALLOWED");
require(numberOfBreedTimes[_parent1] < numberOfAllowedBreeding, "REACHED_MAXIMUM_BREED_ALLOWED_P1");
require(numberOfBreedTimes[_parent2] < numberOfAllowedBreeding, "REACHED_MAXIMUM_BREED_ALLOWED_P1");
addressBlockBought[msg.sender] = block.timestamp;
hatchDate[totalSupply()] = block.timestamp + incubationPeriod;
parents[totalSupply()] = Genes(_parent1, _parent2);
numberOfBreedTimes[_parent1] += 1;
numberOfBreedTimes[_parent2] += 1;
_ownedTokens[msg.sender].push(totalSupply());
_safeMint( msg.sender, 1 );
}
|
function breedCorgis(uint256 _parent1, uint256 _parent2, uint64 expireTime, bytes memory sig) external isSecured(1) {
bytes32 digest = keccak256(abi.encodePacked(msg.sender,expireTime));
require(isAuthorized(sig,digest),"CONTRACT_MINT_NOT_ALLOWED");
require(numberOfBreedTimes[_parent1] < numberOfAllowedBreeding, "REACHED_MAXIMUM_BREED_ALLOWED_P1");
require(numberOfBreedTimes[_parent2] < numberOfAllowedBreeding, "REACHED_MAXIMUM_BREED_ALLOWED_P1");
addressBlockBought[msg.sender] = block.timestamp;
hatchDate[totalSupply()] = block.timestamp + incubationPeriod;
parents[totalSupply()] = Genes(_parent1, _parent2);
numberOfBreedTimes[_parent1] += 1;
numberOfBreedTimes[_parent2] += 1;
_ownedTokens[msg.sender].push(totalSupply());
_safeMint( msg.sender, 1 );
}
| 25,791
|
11
|
// Gets Iterate through the list of existing tokens and return the indexes and balances of the tokens owner by the user _owner The adddress we are checkingreturn indexes The tokenIdsreturn balances The balances of each token /
|
function tokensOwned(address _owner) public view returns (uint256[] indexes, uint256[] balances) {
uint256 numTokens = totalSupply();
uint256[] memory tokenIndexes = new uint256[](numTokens);
uint256[] memory tempTokens = new uint256[](numTokens);
uint256 count;
for (uint256 i = 0; i < numTokens; i++) {
uint256 tokenId = allTokens[i];
if (balanceOf(_owner, tokenId) > 0) {
tempTokens[count] = balanceOf(_owner, tokenId);
tokenIndexes[count] = tokenId;
count++;
}
}
// copy over the data to a correct size array
uint256[] memory _ownedTokens = new uint256[](count);
uint256[] memory _ownedTokensIndexes = new uint256[](count);
for (i = 0; i < count; i++) {
_ownedTokens[i] = tempTokens[i];
_ownedTokensIndexes[i] = tokenIndexes[i];
}
return (_ownedTokensIndexes, _ownedTokens);
}
|
function tokensOwned(address _owner) public view returns (uint256[] indexes, uint256[] balances) {
uint256 numTokens = totalSupply();
uint256[] memory tokenIndexes = new uint256[](numTokens);
uint256[] memory tempTokens = new uint256[](numTokens);
uint256 count;
for (uint256 i = 0; i < numTokens; i++) {
uint256 tokenId = allTokens[i];
if (balanceOf(_owner, tokenId) > 0) {
tempTokens[count] = balanceOf(_owner, tokenId);
tokenIndexes[count] = tokenId;
count++;
}
}
// copy over the data to a correct size array
uint256[] memory _ownedTokens = new uint256[](count);
uint256[] memory _ownedTokensIndexes = new uint256[](count);
for (i = 0; i < count; i++) {
_ownedTokens[i] = tempTokens[i];
_ownedTokensIndexes[i] = tokenIndexes[i];
}
return (_ownedTokensIndexes, _ownedTokens);
}
| 5,742
|
92
|
// Returns true if `_owner` has a balance allocated_owner The account that the balance is allocated forreturn True if there is a balance that belongs to `_owner` /
|
function hasBalance(address _owner) public view returns (bool) {
return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index];
}
|
function hasBalance(address _owner) public view returns (bool) {
return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index];
}
| 6,363
|
227
|
// solhint-disable reason-string contains comments that are checked in tests
|
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
relayHubOnly
|
function preRelayedCall(
GsnTypes.RelayRequest calldata relayRequest,
bytes calldata signature,
bytes calldata approvalData,
uint256 maxPossibleGas
)
external
override
relayHubOnly
| 151
|
5
|
// transfer token and mint
|
payable(campaign.payeeAddress).transfer(totalPrice);
ILaunchpadNFT(contractAddress).mintTo(msg.sender, batchSize);
emit Mint(campaign.contractAddress, campaign.payeeAddress, batchSize, campaign.price);
|
payable(campaign.payeeAddress).transfer(totalPrice);
ILaunchpadNFT(contractAddress).mintTo(msg.sender, batchSize);
emit Mint(campaign.contractAddress, campaign.payeeAddress, batchSize, campaign.price);
| 59,098
|
37
|
// accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFreshAdmin function to accrue interest and set a new reserve factor return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
|
function _setReserveFactor(uint newReserveFactorMantissa) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setReserveFactor(uint256)", newReserveFactorMantissa));
return abi.decode(data, (uint));
}
|
function _setReserveFactor(uint newReserveFactorMantissa) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setReserveFactor(uint256)", newReserveFactorMantissa));
return abi.decode(data, (uint));
}
| 3,475
|
6
|
// TIME VARıABLES
|
uint finalSalaryTime;
uint finalDividendTime;
uint finalCarExpensesTime;
|
uint finalSalaryTime;
uint finalDividendTime;
uint finalCarExpensesTime;
| 5,588
|
2
|
// The kind and positions of celestial items on the map. This does NOT include many attributes of celestials, which must be queried through theirspecific contract (e.g. `Planet` for `CelestialKind.Planet`). The reason is that the map is just a flat list (not indexed by position) intended to be usedwhen loading the game. /
|
struct CelestialMapEntry {
CelestialKind kind;
uint128 x;
uint128 y;
}
|
struct CelestialMapEntry {
CelestialKind kind;
uint128 x;
uint128 y;
}
| 38,141
|
47
|
// Make sure the oracle info is present already
|
require(oracle_cr_infos[token_address].oracle_address != address(0), "Add Oracle info first");
address[] memory tracked_token_arr = tokens_for_address[tracked_address];
for (uint i = 0; i < tracked_token_arr.length; i++){
if (tracked_token_arr[i] == tracked_address) {
revert("Token already present");
}
|
require(oracle_cr_infos[token_address].oracle_address != address(0), "Add Oracle info first");
address[] memory tracked_token_arr = tokens_for_address[tracked_address];
for (uint i = 0; i < tracked_token_arr.length; i++){
if (tracked_token_arr[i] == tracked_address) {
revert("Token already present");
}
| 48,019
|
61
|
// Modified Wrappers over Solidity's arithmetic operations with added overflowchecks. Arithmetic operations in Solidity wrap on overflow. This can easily resultin bugs, because programmers usually assume that an overflow raises anerror, which is the standard behavior in high level programming languages.`SafeMath` restores this intuition by reverting the transaction when anoperation overflows. Using this library instead of the unchecked operations eliminates an entireclass of bugs, so it's recommended to use it always. /
|
library SafeMath_Chainlink {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
|
library SafeMath_Chainlink {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
| 14,331
|
130
|
// Adjust token supply for 18 decimals
|
uint256 supply = _tokenSupply * 1 ether;
swapThreshold = Math.mulDiv(supply, 3, 1000);
marketingFeeReceiver = msg.sender;
buyTax = _buyTax;
sellTax = _sellTax;
|
uint256 supply = _tokenSupply * 1 ether;
swapThreshold = Math.mulDiv(supply, 3, 1000);
marketingFeeReceiver = msg.sender;
buyTax = _buyTax;
sellTax = _sellTax;
| 3,407
|
57
|
// Gets some distributed asset. _amount Amount that user wants to claim. /
|
function claim(uint _amount) external {
address _src = msg.sender;
require(getCurrentClaimableAmount(_src) >= _amount, "claim(uint): Too large amount to claim!");
claim(_src, _amount);
}
|
function claim(uint _amount) external {
address _src = msg.sender;
require(getCurrentClaimableAmount(_src) >= _amount, "claim(uint): Too large amount to claim!");
claim(_src, _amount);
}
| 44,177
|
22
|
// Calculates the binary exponent of x using the binary fraction method.//See https:ethereum.stackexchange.com/q/79903/24693.// Requirements:/ - x must be 192 or less./ - The result must fit within `MAX_UD60x18`.//x The exponent as an UD60x18 number./ return result The result as an UD60x18 number.
|
function exp2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = unwrap(x);
// Numbers greater than or equal to 2^192 don't fit within the 192.64-bit format.
if (xUint >= 192e18) {
revert PRBMath_UD60x18_Exp2_InputTooBig(x);
}
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = (xUint << 64) / uUNIT;
// Pass x to the `prbExp2` function, which uses the 192.64-bit fixed-point number representation.
result = wrap(prbExp2(x_192x64));
}
|
function exp2(UD60x18 x) pure returns (UD60x18 result) {
uint256 xUint = unwrap(x);
// Numbers greater than or equal to 2^192 don't fit within the 192.64-bit format.
if (xUint >= 192e18) {
revert PRBMath_UD60x18_Exp2_InputTooBig(x);
}
// Convert x to the 192.64-bit fixed-point format.
uint256 x_192x64 = (xUint << 64) / uUNIT;
// Pass x to the `prbExp2` function, which uses the 192.64-bit fixed-point number representation.
result = wrap(prbExp2(x_192x64));
}
| 16,815
|
2
|
// owner = 0x275255B3F0651C4594b24bf00E68d32154D960bc;
|
owner = 0x26D68F3d9e2A94464aA582D7c82a2fD92515B78f; //Address of Hospital
|
owner = 0x26D68F3d9e2A94464aA582D7c82a2fD92515B78f; //Address of Hospital
| 18,787
|
531
|
// prevent transferring too much
|
redeemStablecoinAmount = stablecoinBalance;
|
redeemStablecoinAmount = stablecoinBalance;
| 59,572
|
57
|
// Cancel an option on behalf of an address. This will burn the option ERC1155 and withdraw collateral./Requires approval of the option contract/This is only doable by an address which wrote an amount of options >= _amount/Must be called before expiration/_from Address on behalf of which the option is cancelled/_optionId The id of the option to cancel/_amount Amount to cancel
|
function cancelOptionFrom(address _from, uint256 _optionId, uint256 _amount) external {
require(isApprovedForAll(_from, msg.sender), "Not approved");
_cancelOption(_from, _optionId, _amount);
}
|
function cancelOptionFrom(address _from, uint256 _optionId, uint256 _amount) external {
require(isApprovedForAll(_from, msg.sender), "Not approved");
_cancelOption(_from, _optionId, _amount);
}
| 37,947
|
102
|
// Note: the ERC-165 identifier for this interface is 0xf0b9e5ba
|
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
|
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
| 17,245
|
526
|
// Resolution for all fixed point numeric parameters which represent percents. The resolution allows for a/ granularity of 0.01% increments.
|
uint256 public constant PERCENT_RESOLUTION = 10000;
|
uint256 public constant PERCENT_RESOLUTION = 10000;
| 3,204
|
29
|
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with`errorMessage` as a fallback revert reason when `target` reverts. _Available since v3.1._ /
|
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
|
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
| 921
|
0
|
// normalise price precision
|
uint256 _priceDecimals = s.priceDecimals[_token];
return price.mul(PRICE_PRECISION).div(10**_priceDecimals);
|
uint256 _priceDecimals = s.priceDecimals[_token];
return price.mul(PRICE_PRECISION).div(10**_priceDecimals);
| 24,485
|
83
|
// Private function to ensure that a timelock is complete or expiredand to clear the existing timelock if it is complete so it cannot later bereused. functionSelector function to be called. arguments The abi-encoded arguments of the function to be called. /
|
function _enforceTimelockPrivate(
bytes4 functionSelector, bytes memory arguments
|
function _enforceTimelockPrivate(
bytes4 functionSelector, bytes memory arguments
| 4,839
|
335
|
// Internal Functions//Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." _in Input bytes32 value.return Bytes32 as a boolean. /
|
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
|
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
| 71,696
|
14
|
// check address có nằm trong whitelist hay ko ?
|
require(isWhitelistAddress(_msgSender()), "Not in whitelist");
|
require(isWhitelistAddress(_msgSender()), "Not in whitelist");
| 6,212
|
296
|
// Creator needs to deposit
|
uint256 internal constant MIN_CONTRIBUTION = 1;
|
uint256 internal constant MIN_CONTRIBUTION = 1;
| 67,901
|
15
|
// solhint-disable-next-line no-inline-assembly
|
assembly {
switch x case 0 {switch n case 0 {z := b} default {z := 0}}
|
assembly {
switch x case 0 {switch n case 0 {z := b} default {z := 0}}
| 51,886
|
74
|
// /
|
library WadRayMath {
using SafeMath for uint256;
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
function ray() internal pure returns (uint256) {
return _RAY;
}
function wad() internal pure returns (uint256) {
return _WAD;
}
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_WAD.add(a.mul(b)).div(_WAD);
}
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_WAD)).div(b);
}
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_RAY.add(a.mul(b)).div(_RAY);
}
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_RAY)).div(b);
}
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
return halfRatio.add(a).div(_WAD_RAY_RATIO);
}
function wadToRay(uint256 a) internal pure returns (uint256) {
return a.mul(_WAD_RAY_RATIO);
}
/**
* @dev calculates x^n, in ray. The code uses the ModExp precompile
* @param x base
* @param n exponent
* @return z = x^n, in ray
*/
function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : _RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
}
}
|
library WadRayMath {
using SafeMath for uint256;
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
function ray() internal pure returns (uint256) {
return _RAY;
}
function wad() internal pure returns (uint256) {
return _WAD;
}
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_WAD.add(a.mul(b)).div(_WAD);
}
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_WAD)).div(b);
}
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_RAY.add(a.mul(b)).div(_RAY);
}
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_RAY)).div(b);
}
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
return halfRatio.add(a).div(_WAD_RAY_RATIO);
}
function wadToRay(uint256 a) internal pure returns (uint256) {
return a.mul(_WAD_RAY_RATIO);
}
/**
* @dev calculates x^n, in ray. The code uses the ModExp precompile
* @param x base
* @param n exponent
* @return z = x^n, in ray
*/
function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : _RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
}
}
| 20,824
|
161
|
// solhint-disable-next-line no-inline-assembly
|
assembly { size := extcodesize(account) }
|
assembly { size := extcodesize(account) }
| 158
|
51
|
// Here we are redeeming unclaimed token from iToken contract to this contractsthen allocating claimedTokens with rebalancingEveryone should be incentivized in calling this methodNOTE: this method can be paused_clientProtocolAmounts : client side calculated amounts to put on each lending protocolreturn claimedTokens : amount of underlying tokens claimed /
|
function claimITokens(uint256[] calldata _clientProtocolAmounts)
external whenNotPaused whenITokenPriceHasNotDecreased
|
function claimITokens(uint256[] calldata _clientProtocolAmounts)
external whenNotPaused whenITokenPriceHasNotDecreased
| 36,838
|
104
|
// governance settings
|
if (prop.proposalType == ProposalType.PERIOD)
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint8(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint8(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
|
if (prop.proposalType == ProposalType.PERIOD)
if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]);
if (prop.proposalType == ProposalType.QUORUM)
if (prop.amounts[0] != 0) quorum = uint8(prop.amounts[0]);
if (prop.proposalType == ProposalType.SUPERMAJORITY)
if (prop.amounts[0] != 0) supermajority = uint8(prop.amounts[0]);
if (prop.proposalType == ProposalType.TYPE)
| 5,621
|
6
|
// returns a UQ112x112 which represents the ratio of the numerator to the denominator equivalent to encode(numerator).div(denominator)
|
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
|
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
| 4,157
|
34
|
// __ _ _/ _\ |_ _ __ _ ____| |_ _ _ _ __ ___ \ \| __| '__| | | |/ __| __| | | | '__/ _ \_\ \ |_| || |_| | (__| |_| |_| | | |__/\__/\__|_| \__,_|\___|\__|\__,_|_|\___| /
|
struct transaction
|
struct transaction
| 47,067
|
410
|
// If no rate oracle is set, then set this to the identity
|
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
|
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
| 63,121
|
7
|
// throws on failure
|
parentAddress.transfer(msg.value);
|
parentAddress.transfer(msg.value);
| 11,475
|
171
|
// CoFiToken with Governance. It offers possibilities to adopt off-chain gasless governance infra.
|
contract CoFiToken is ERC20("CoFi Token", "CoFi") {
address public governance;
mapping (address => bool) public minters;
// Copied and modified from SUSHI code:
// https://github.com/sushiswap/sushiswap/blob/master/contracts/SushiToken.sol
// Which is copied and modified from YAM code and COMPOUND:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// 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;
uint 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,uint 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,uint nonce,uint expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @dev An event thats emitted when a new governance account is set
/// @param _new The new governance address
event NewGovernance(address _new);
/// @dev An event thats emitted when a new minter account is added
/// @param _minter The new minter address added
event MinterAdded(address _minter);
/// @dev An event thats emitted when a minter account is removed
/// @param _minter The minter address removed
event MinterRemoved(address _minter);
modifier onlyGovernance() {
require(msg.sender == governance, "CoFi: !governance");
_;
}
constructor() {
governance = msg.sender;
}
function setGovernance(address _new) external onlyGovernance {
require(_new != address(0), "CoFi: zero addr");
require(_new != governance, "CoFi: same addr");
governance = _new;
emit NewGovernance(_new);
}
function addMinter(address _minter) external onlyGovernance {
minters[_minter] = true;
emit MinterAdded(_minter);
}
function removeMinter(address _minter) external onlyGovernance {
minters[_minter] = false;
emit MinterRemoved(_minter);
}
/// @notice mint is used to distribute CoFi token to users, minters are CoFi mining pools
function mint(address _to, uint _amount) external {
require(minters[msg.sender], "CoFi: !minter");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/// @notice SUSHI has a vote governance bug in its token implementation, CoFi fixed it here
/// read https://blog.peckshield.com/2020/09/08/sushi/
function transfer(address _recipient, uint _amount) public override returns (bool) {
super.transfer(_recipient, _amount);
_moveDelegates(_delegates[msg.sender], _delegates[_recipient], _amount);
return true;
}
/// @notice override original transferFrom to fix vote issue
function transferFrom(address _sender, address _recipient, uint _amount) public override returns (bool) {
super.transferFrom(_sender, _recipient, _amount);
_moveDelegates(_delegates[_sender], _delegates[_recipient], _amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CoFi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CoFi::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "CoFi::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 (uint)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint)
{
require(blockNumber < block.number, "CoFi::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];
uint delegatorBalance = balanceOf(delegator); // balance of underlying CoFis (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint srcRepNew = srcRepOld - (amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint dstRepNew = dstRepOld + (amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint oldVotes,
uint newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CoFi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
contract CoFiToken is ERC20("CoFi Token", "CoFi") {
address public governance;
mapping (address => bool) public minters;
// Copied and modified from SUSHI code:
// https://github.com/sushiswap/sushiswap/blob/master/contracts/SushiToken.sol
// Which is copied and modified from YAM code and COMPOUND:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// 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;
uint 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,uint 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,uint nonce,uint expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @dev An event thats emitted when a new governance account is set
/// @param _new The new governance address
event NewGovernance(address _new);
/// @dev An event thats emitted when a new minter account is added
/// @param _minter The new minter address added
event MinterAdded(address _minter);
/// @dev An event thats emitted when a minter account is removed
/// @param _minter The minter address removed
event MinterRemoved(address _minter);
modifier onlyGovernance() {
require(msg.sender == governance, "CoFi: !governance");
_;
}
constructor() {
governance = msg.sender;
}
function setGovernance(address _new) external onlyGovernance {
require(_new != address(0), "CoFi: zero addr");
require(_new != governance, "CoFi: same addr");
governance = _new;
emit NewGovernance(_new);
}
function addMinter(address _minter) external onlyGovernance {
minters[_minter] = true;
emit MinterAdded(_minter);
}
function removeMinter(address _minter) external onlyGovernance {
minters[_minter] = false;
emit MinterRemoved(_minter);
}
/// @notice mint is used to distribute CoFi token to users, minters are CoFi mining pools
function mint(address _to, uint _amount) external {
require(minters[msg.sender], "CoFi: !minter");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/// @notice SUSHI has a vote governance bug in its token implementation, CoFi fixed it here
/// read https://blog.peckshield.com/2020/09/08/sushi/
function transfer(address _recipient, uint _amount) public override returns (bool) {
super.transfer(_recipient, _amount);
_moveDelegates(_delegates[msg.sender], _delegates[_recipient], _amount);
return true;
}
/// @notice override original transferFrom to fix vote issue
function transferFrom(address _sender, address _recipient, uint _amount) public override returns (bool) {
super.transferFrom(_sender, _recipient, _amount);
_moveDelegates(_delegates[_sender], _delegates[_recipient], _amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CoFi::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CoFi::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "CoFi::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 (uint)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint)
{
require(blockNumber < block.number, "CoFi::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];
uint delegatorBalance = balanceOf(delegator); // balance of underlying CoFis (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint srcRepNew = srcRepOld - (amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint dstRepNew = dstRepOld + (amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint oldVotes,
uint newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CoFi::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 1,192
|
251
|
// Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE/ TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE/ THEY MAY BE PERMANENTLY LOST/Throws unless `msg.sender` is the current owner, an authorized/operator, or the approved address for this NFT. Throws if `_from` is/not the current owner. Throws if `_to` is the zero address. Throws if/`_tokenId` is not a valid NFT./_from The current owner of the NFT/_to The new owner/_tokenId The NFT to transfer
|
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public;
|
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public;
| 33,752
|
5
|
// keep track of all our loans
|
outstandingBalance += amount;
|
outstandingBalance += amount;
| 1,475
|
26
|
// 10^3010^37 = 10^67
|
if (sellVolume * priceNum < sellVolume) return false;
int outstandingVolume = int((sellVolume * priceNum) / priceDen) - int(buyVolume);
if (outstandingVolume >= int(srcQty)) return true;
return false;
|
if (sellVolume * priceNum < sellVolume) return false;
int outstandingVolume = int((sellVolume * priceNum) / priceDen) - int(buyVolume);
if (outstandingVolume >= int(srcQty)) return true;
return false;
| 49,086
|
15
|
// oods_coefficients[7]/ mload(add(context, 0x5160)), res += c_8(f_0(x) - f_0(g^8z)) / (x - g^8z).
|
res := add(
res,
mulmod(mulmod(/*(x - g^8 * z)^(-1)*/ mload(add(denominatorsPtr, 0x100)),
|
res := add(
res,
mulmod(mulmod(/*(x - g^8 * z)^(-1)*/ mload(add(denominatorsPtr, 0x100)),
| 47,010
|
141
|
// At the first round, currentBalance=0, pendingAmount>0 so we just do not charge anything on the first round
|
uint256 lockedBalanceSansPending =
currentBalance > pendingAmount
? currentBalance.sub(pendingAmount)
: 0;
uint256 _performanceFeeInAsset;
uint256 _managementFeeInAsset;
uint256 _vaultFee;
|
uint256 lockedBalanceSansPending =
currentBalance > pendingAmount
? currentBalance.sub(pendingAmount)
: 0;
uint256 _performanceFeeInAsset;
uint256 _managementFeeInAsset;
uint256 _vaultFee;
| 48,122
|
5
|
// Error for if not minter
|
error NotMinter();
|
error NotMinter();
| 10,283
|
126
|
// RefundVault This contract is used for storing TOKENS AND ETHER while a crowd sale is in progress for a period of 3 DAYS.Supporter can ask for a full/part refund for his/her ether against token. Once tokens are Claimed by the supporter, they cannot be refunded.After 3 days, all ether will be withdrawn from the vault`s wallet, leaving all tokens to be claimed by the their owners. /
|
contract RefundVault is Claimable {
using SafeMath for uint256;
// =================================================================================================================
// Enums
// =================================================================================================================
enum State { Active, Refunding, Closed }
// =================================================================================================================
// Members
// =================================================================================================================
// Refund time frame
uint256 public constant REFUND_TIME_FRAME = 3 days;
mapping (address => uint256) public depositedETH;
mapping (address => uint256) public depositedToken;
address public etherWallet;
BitMEDSmartToken public token;
State public state;
uint256 public refundStartTime;
// =================================================================================================================
// Events
// =================================================================================================================
event Active();
event Closed();
event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount);
event RefundsEnabled();
event RefundedETH(address beneficiary, uint256 weiAmount);
event TokensClaimed(address indexed beneficiary, uint256 weiAmount);
// =================================================================================================================
// Modifiers
// =================================================================================================================
modifier isActiveState() {
require(state == State.Active);
_;
}
modifier isRefundingState() {
require(state == State.Refunding);
_;
}
modifier isCloseState() {
require(state == State.Closed);
_;
}
modifier isRefundingOrCloseState() {
require(state == State.Refunding || state == State.Closed);
_;
}
modifier isInRefundTimeFrame() {
require(refundStartTime <= block.timestamp && refundStartTime + REFUND_TIME_FRAME > block.timestamp);
_;
}
modifier isRefundTimeFrameExceeded() {
require(refundStartTime + REFUND_TIME_FRAME < block.timestamp);
_;
}
// =================================================================================================================
// Ctors
// =================================================================================================================
function RefundVault(address _etherWallet, BitMEDSmartToken _token) public {
require(_etherWallet != address(0));
require(_token != address(0));
etherWallet = _etherWallet;
token = _token;
state = State.Active;
Active();
}
// =================================================================================================================
// Public Functions
// =================================================================================================================
function deposit(address supporter, uint256 tokensAmount) isActiveState onlyOwner public payable {
depositedETH[supporter] = depositedETH[supporter].add(msg.value);
depositedToken[supporter] = depositedToken[supporter].add(tokensAmount);
Deposit(supporter, msg.value, tokensAmount);
}
function close() isRefundingState onlyOwner isRefundTimeFrameExceeded public {
state = State.Closed;
Closed();
etherWallet.transfer(address(this).balance);
}
function enableRefunds() isActiveState onlyOwner public {
state = State.Refunding;
refundStartTime = block.timestamp;
RefundsEnabled();
}
//@dev Refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet
function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public {
require(ETHToRefundAmountWei != 0);
uint256 depositedTokenValue = depositedToken[msg.sender];
uint256 depositedETHValue = depositedETH[msg.sender];
require(ETHToRefundAmountWei <= depositedETHValue);
uint256 refundTokens = ETHToRefundAmountWei.mul(depositedTokenValue).div(depositedETHValue);
assert(refundTokens > 0);
depositedETH[msg.sender] = depositedETHValue.sub(ETHToRefundAmountWei);
depositedToken[msg.sender] = depositedTokenValue.sub(refundTokens);
token.destroy(address(this),refundTokens);
msg.sender.transfer(ETHToRefundAmountWei);
RefundedETH(msg.sender, ETHToRefundAmountWei);
}
//@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet.
//Can be triggerd by the supporter only
function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public {
require(tokensToClaim != 0);
address supporter = msg.sender;
require(depositedToken[supporter] > 0);
uint256 depositedTokenValue = depositedToken[supporter];
uint256 depositedETHValue = depositedETH[supporter];
require(tokensToClaim <= depositedTokenValue);
uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue);
assert(claimedETH > 0);
depositedETH[supporter] = depositedETHValue.sub(claimedETH);
depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim);
token.transfer(supporter, tokensToClaim);
if(state != State.Closed) {
etherWallet.transfer(claimedETH);
}
TokensClaimed(supporter, tokensToClaim);
}
//@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet.
//Can be triggerd by the owner of the vault (in our case - BitMED`s owner after 3 days)
function claimAllSupporterTokensByOwner(address supporter) isCloseState onlyOwner public {
uint256 depositedTokenValue = depositedToken[supporter];
require(depositedTokenValue > 0);
token.transfer(supporter, depositedTokenValue);
TokensClaimed(supporter, depositedTokenValue);
}
// @dev supporter can claim tokens by calling the function
// @param tokenToClaimAmount - amount of the token to claim
function claimAllTokens() isRefundingOrCloseState public {
uint256 depositedTokenValue = depositedToken[msg.sender];
claimTokens(depositedTokenValue);
}
}
|
contract RefundVault is Claimable {
using SafeMath for uint256;
// =================================================================================================================
// Enums
// =================================================================================================================
enum State { Active, Refunding, Closed }
// =================================================================================================================
// Members
// =================================================================================================================
// Refund time frame
uint256 public constant REFUND_TIME_FRAME = 3 days;
mapping (address => uint256) public depositedETH;
mapping (address => uint256) public depositedToken;
address public etherWallet;
BitMEDSmartToken public token;
State public state;
uint256 public refundStartTime;
// =================================================================================================================
// Events
// =================================================================================================================
event Active();
event Closed();
event Deposit(address indexed beneficiary, uint256 etherWeiAmount, uint256 tokenWeiAmount);
event RefundsEnabled();
event RefundedETH(address beneficiary, uint256 weiAmount);
event TokensClaimed(address indexed beneficiary, uint256 weiAmount);
// =================================================================================================================
// Modifiers
// =================================================================================================================
modifier isActiveState() {
require(state == State.Active);
_;
}
modifier isRefundingState() {
require(state == State.Refunding);
_;
}
modifier isCloseState() {
require(state == State.Closed);
_;
}
modifier isRefundingOrCloseState() {
require(state == State.Refunding || state == State.Closed);
_;
}
modifier isInRefundTimeFrame() {
require(refundStartTime <= block.timestamp && refundStartTime + REFUND_TIME_FRAME > block.timestamp);
_;
}
modifier isRefundTimeFrameExceeded() {
require(refundStartTime + REFUND_TIME_FRAME < block.timestamp);
_;
}
// =================================================================================================================
// Ctors
// =================================================================================================================
function RefundVault(address _etherWallet, BitMEDSmartToken _token) public {
require(_etherWallet != address(0));
require(_token != address(0));
etherWallet = _etherWallet;
token = _token;
state = State.Active;
Active();
}
// =================================================================================================================
// Public Functions
// =================================================================================================================
function deposit(address supporter, uint256 tokensAmount) isActiveState onlyOwner public payable {
depositedETH[supporter] = depositedETH[supporter].add(msg.value);
depositedToken[supporter] = depositedToken[supporter].add(tokensAmount);
Deposit(supporter, msg.value, tokensAmount);
}
function close() isRefundingState onlyOwner isRefundTimeFrameExceeded public {
state = State.Closed;
Closed();
etherWallet.transfer(address(this).balance);
}
function enableRefunds() isActiveState onlyOwner public {
state = State.Refunding;
refundStartTime = block.timestamp;
RefundsEnabled();
}
//@dev Refund ether back to the supporter in returns of proportional amount of BXM back to the BitMED`s wallet
function refundETH(uint256 ETHToRefundAmountWei) isInRefundTimeFrame isRefundingState public {
require(ETHToRefundAmountWei != 0);
uint256 depositedTokenValue = depositedToken[msg.sender];
uint256 depositedETHValue = depositedETH[msg.sender];
require(ETHToRefundAmountWei <= depositedETHValue);
uint256 refundTokens = ETHToRefundAmountWei.mul(depositedTokenValue).div(depositedETHValue);
assert(refundTokens > 0);
depositedETH[msg.sender] = depositedETHValue.sub(ETHToRefundAmountWei);
depositedToken[msg.sender] = depositedTokenValue.sub(refundTokens);
token.destroy(address(this),refundTokens);
msg.sender.transfer(ETHToRefundAmountWei);
RefundedETH(msg.sender, ETHToRefundAmountWei);
}
//@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet.
//Can be triggerd by the supporter only
function claimTokens(uint256 tokensToClaim) isRefundingOrCloseState public {
require(tokensToClaim != 0);
address supporter = msg.sender;
require(depositedToken[supporter] > 0);
uint256 depositedTokenValue = depositedToken[supporter];
uint256 depositedETHValue = depositedETH[supporter];
require(tokensToClaim <= depositedTokenValue);
uint256 claimedETH = tokensToClaim.mul(depositedETHValue).div(depositedTokenValue);
assert(claimedETH > 0);
depositedETH[supporter] = depositedETHValue.sub(claimedETH);
depositedToken[supporter] = depositedTokenValue.sub(tokensToClaim);
token.transfer(supporter, tokensToClaim);
if(state != State.Closed) {
etherWallet.transfer(claimedETH);
}
TokensClaimed(supporter, tokensToClaim);
}
//@dev Transfer tokens from the vault to the supporter while releasing proportional amount of ether to BitMED`s wallet.
//Can be triggerd by the owner of the vault (in our case - BitMED`s owner after 3 days)
function claimAllSupporterTokensByOwner(address supporter) isCloseState onlyOwner public {
uint256 depositedTokenValue = depositedToken[supporter];
require(depositedTokenValue > 0);
token.transfer(supporter, depositedTokenValue);
TokensClaimed(supporter, depositedTokenValue);
}
// @dev supporter can claim tokens by calling the function
// @param tokenToClaimAmount - amount of the token to claim
function claimAllTokens() isRefundingOrCloseState public {
uint256 depositedTokenValue = depositedToken[msg.sender];
claimTokens(depositedTokenValue);
}
}
| 66,496
|
18
|
// Validate order parameters (does not check signature validity) order Order to validate /
|
function validateOrderParameters(Order memory order)
internal
view
returns (bool)
|
function validateOrderParameters(Order memory order)
internal
view
returns (bool)
| 7,061
|
9
|
// Gets remaining payment balance accumulated from transfer of agiven token that has not been withdrawnCalls the overloaded `withdrawPayment` with defaults of `start` as the last withdrawn payment index, and `count` as the remaining payment length Used by `withdrawPayment` to calculate how much a franchisor is owed.tokenId The identifier for an NFT franchisor address to get the payment balance of return uint256 representing the balance in wei accumulated for a token /
|
function paymentBalanceOf(address franchisor, uint256 tokenId)
public view notZeroAddr(franchisor) returns (uint256)
|
function paymentBalanceOf(address franchisor, uint256 tokenId)
public view notZeroAddr(franchisor) returns (uint256)
| 46,129
|
0
|
// Events//Constructor/
|
address payable oracleContract ) public UsingTellor(oracleContract) {
_interestRate = interestRate;
_originationFee = originationFee;
_collateralizationRatio = collateralizationRatio;
_liquidationPenalty = liquidationPenalty;
_collateralToken = collateralToken;
_debtToken = debtToken;
_oracleContract = oracleContract;
_debtTokenPrice = debtTokenPrice;
_debtTokenPriceGranularity = debtTokenPriceGranularity;
_debtTokenTellorRequestId = debtTokenTellorRequestId;
_collateralTokenPrice = collateralTokenPrice;
_collateralTokenPriceGranularity = collateralTokenPriceGranularity;
_collateralTokenTellorRequestId = collateralTokenTellorRequestId;
}
|
address payable oracleContract ) public UsingTellor(oracleContract) {
_interestRate = interestRate;
_originationFee = originationFee;
_collateralizationRatio = collateralizationRatio;
_liquidationPenalty = liquidationPenalty;
_collateralToken = collateralToken;
_debtToken = debtToken;
_oracleContract = oracleContract;
_debtTokenPrice = debtTokenPrice;
_debtTokenPriceGranularity = debtTokenPriceGranularity;
_debtTokenTellorRequestId = debtTokenTellorRequestId;
_collateralTokenPrice = collateralTokenPrice;
_collateralTokenPriceGranularity = collateralTokenPriceGranularity;
_collateralTokenTellorRequestId = collateralTokenTellorRequestId;
}
| 43,657
|
87
|
// _wallet Address where collected funds will be forwarded to _token Address of reward token _tokenDecimals The decimal of reward token _ethRatePerToken How many token units a buy get per Dai token. /
|
constructor(
address payable _wallet,
IERC20 _token,
uint256 _tokenDecimals,
uint256 _ethRatePerToken
|
constructor(
address payable _wallet,
IERC20 _token,
uint256 _tokenDecimals,
uint256 _ethRatePerToken
| 66,654
|
7
|
// Emitted by the pool for increases to the number of observations that can be stored/observationCardinalityNext is not the observation cardinality until an observation is written at the index/ just before a mint/swap/burn./observationCardinalityNextOld The previous value of the next observation cardinality/observationCardinalityNextNew The updated value of the next observation cardinality
|
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
|
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
| 1,551
|
567
|
// Fires a Redeemed event/ We append the sender, which is the deposit contract that called.
|
function logRedeemed(bytes32 _txid) external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit Redeemed(msg.sender, _txid, block.timestamp);
}
|
function logRedeemed(bytes32 _txid) external {
require(
approvedToLog(msg.sender),
"Caller is not approved to log events"
);
emit Redeemed(msg.sender, _txid, block.timestamp);
}
| 31,757
|
5
|
// Delegate DAO to sender
|
getContractsOf[_client].push(dao);
Builded(_client, dao);
dao.setOwner(_client);
dao.setHammer(_client);
return dao;
|
getContractsOf[_client].push(dao);
Builded(_client, dao);
dao.setOwner(_client);
dao.setHammer(_client);
return dao;
| 15,295
|
54
|
// File: contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol
|
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
|
interface IUniswapV2ERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
}
| 27,974
|
6
|
// check whether address `who` is given meta-transaction execution rights./who The address to query./ return whether the address has meta-transaction execution rights.
|
function isMetaTransactionProcessor(address who) external view returns(bool) {
return _metaTransactionContracts[who];
}
|
function isMetaTransactionProcessor(address who) external view returns(bool) {
return _metaTransactionContracts[who];
}
| 43,625
|
2
|
// Callback function /
|
function fulfillWeatherTemperature(bytes32 _requestId, uint256 _result) public recordChainlinkFulfillment(_requestId) {
result = _result;
}
|
function fulfillWeatherTemperature(bytes32 _requestId, uint256 _result) public recordChainlinkFulfillment(_requestId) {
result = _result;
}
| 3,014
|
61
|
// Get a certain number of an addresses blocks in ascending order. /
|
function getBlocksByOwner(uint _bid, uint _len, address _owner) external view returns(uint[])
|
function getBlocksByOwner(uint _bid, uint _len, address _owner) external view returns(uint[])
| 7,991
|
242
|
// Converts a uint into a base-10, UTF-8 representation stored in a `string` type. /
|
function toUtf8BytesUint(uint256 x) internal pure returns (bytes memory) {
if (x == 0) {
return "0";
}
uint256 j = x;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (x != 0) {
k = k - 1;
uint8 temp = (48 + uint8(x - (x / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
x /= 10;
}
return bstr;
}
|
function toUtf8BytesUint(uint256 x) internal pure returns (bytes memory) {
if (x == 0) {
return "0";
}
uint256 j = x;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (x != 0) {
k = k - 1;
uint8 temp = (48 + uint8(x - (x / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
x /= 10;
}
return bstr;
}
| 29,990
|
255
|
// Query if a contract implements an interface _interfaceID The interface identifier, as specified in ERC-165return `true` if the contract implements `_interfaceID` /
|
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
returns (bool)
|
function supportsInterface(bytes4 _interfaceID)
public
pure
virtual
returns (bool)
| 55,783
|
484
|
// pending rewards awaiting anyone to massUpdate
|
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
address public ENCOREETHLPBurnAddress;
mapping(address=>bool) public voidWithdrawList;
|
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
address public ENCOREETHLPBurnAddress;
mapping(address=>bool) public voidWithdrawList;
| 47,465
|
11
|
// Set proven hash of metadata /
|
function provenHash(bytes32 _proven) public onlyOwner {
proven = _proven;
}
|
function provenHash(bytes32 _proven) public onlyOwner {
proven = _proven;
}
| 786
|
174
|
// key: LPID, value: totalSupply of that LP.
|
mapping(uint256 => uint256) public totalSupply;
|
mapping(uint256 => uint256) public totalSupply;
| 79,043
|
60
|
// ====== POLICY FUNCTIONS ====== // /
|
function addRecipient( address _recipient, uint _rewardRate ) external onlyOwner {
require( _recipient != address(0), "IA" );
require(info.length <= 4, "limit recipients max to 5");
info.push( Info({
recipient: _recipient,
rate: _rewardRate
}));
emit LogAddRecipient(_recipient, _rewardRate);
}
|
function addRecipient( address _recipient, uint _rewardRate ) external onlyOwner {
require( _recipient != address(0), "IA" );
require(info.length <= 4, "limit recipients max to 5");
info.push( Info({
recipient: _recipient,
rate: _rewardRate
}));
emit LogAddRecipient(_recipient, _rewardRate);
}
| 28,296
|
94
|
// Burn the fuel of a `boostedSend`. Returns a `FuelBurn` struct containing information about the burn. /
|
function _burnBoostedSendFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal virtual returns (FuelBurn memory);
|
function _burnBoostedSendFuel(
address from,
BoosterFuel memory fuel,
UnpackedData memory unpacked
) internal virtual returns (FuelBurn memory);
| 36,039
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.