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
|
|---|---|---|---|---|
9
|
// Approve tokens to bridge contract
|
_approveTokens(bridgeStep, amount);
|
_approveTokens(bridgeStep, amount);
| 17,601
|
10
|
// used when inviting new members or when a new contract is created
|
function registerContractMember(address _contract, address _member, bytes32 _contractType) public auth {
// set address in members index
bytes32 label = keccak256(abi.encodePacked(MEMBER_LABEL, keccak256(abi.encodePacked(bytes32(_member)))));
DataStoreIndex userIndex = DataStoreIndex(db.indexGet(label));
db.indexMakeModerator(label);
userIndex.listEntryAdd(_contractType, bytes32(_contract));
userIndex.removeModeratorship();
// notify about new members
getEventHub().sendContractEvent(
uint(EventHubBusinessCenter.BusinessCenterEventType.New), _contractType, _contract, _member);
}
|
function registerContractMember(address _contract, address _member, bytes32 _contractType) public auth {
// set address in members index
bytes32 label = keccak256(abi.encodePacked(MEMBER_LABEL, keccak256(abi.encodePacked(bytes32(_member)))));
DataStoreIndex userIndex = DataStoreIndex(db.indexGet(label));
db.indexMakeModerator(label);
userIndex.listEntryAdd(_contractType, bytes32(_contract));
userIndex.removeModeratorship();
// notify about new members
getEventHub().sendContractEvent(
uint(EventHubBusinessCenter.BusinessCenterEventType.New), _contractType, _contract, _member);
}
| 9,055
|
13
|
// Event to show ownership has been transferredpreviousOwner representing the address of the previous ownernewOwner representing the address of the new owner/
|
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
|
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
| 2,034
|
21
|
// Emits a {CallScheduled} event. Requirements: - the caller must have the 'proposer' role. /
|
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
|
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
| 25,934
|
261
|
// Tells the proxy type (EIP 897)return proxyTypeId Proxy type, 2 for forwarding proxy /
|
function proxyType() override public pure returns (uint256 proxyTypeId) {
|
function proxyType() override public pure returns (uint256 proxyTypeId) {
| 6,870
|
3
|
// emitted when `assetIds` are minted successfully to `to` addressesand uri is set for each of `assetIds` using `tokenURIs`. /
|
event bulkMintSuccessful(
|
event bulkMintSuccessful(
| 40,133
|
253
|
// Update balances and level
|
multiplierTokenDevFund = multiplierTokenDevFund.add(finalCost);
spentMultiplierTokens[msg.sender] = spentMultiplierTokens[msg.sender]
.add(finalCost);
boostLevel[msg.sender] = level;
|
multiplierTokenDevFund = multiplierTokenDevFund.add(finalCost);
spentMultiplierTokens[msg.sender] = spentMultiplierTokens[msg.sender]
.add(finalCost);
boostLevel[msg.sender] = level;
| 22,502
|
43
|
// The recipient must be the caller of this function
|
address recipient = giftIdToGift[giftId].recipient;
require(recipient == msg.sender);
|
address recipient = giftIdToGift[giftId].recipient;
require(recipient == msg.sender);
| 46,018
|
61
|
// event for token switch activate logging/
|
event TokenSwitchActivated();
|
event TokenSwitchActivated();
| 13,466
|
10
|
// ID of the artist who is owner of the song. =userID in struct Artist
|
string artistID;
|
string artistID;
| 6,315
|
304
|
// Common sub-expressions
|
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
|
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
| 63,380
|
119
|
// Ensure balances of tokenIn remained
|
if(payment.tokenInAddress == NATIVE) {
if(address(this).balance < balanceInBefore) {
revert InsufficientBalanceInAfterPayment();
}
|
if(payment.tokenInAddress == NATIVE) {
if(address(this).balance < balanceInBefore) {
revert InsufficientBalanceInAfterPayment();
}
| 11,904
|
182
|
// Return if an authority address is registered | This also checks the status of the registered issuer firm self Internal storage proxying TokenIOStorage contract authorityAddress Ethereum address of the firm authority to query
|
* @return { "registered" : "Return if the authority is registered" }
*/
function isRegisteredAuthority(Data storage self, address authorityAddress) internal view returns (bool registered) {
bytes32 id = keccak256(abi.encodePacked('registered.authority', getFirmFromAuthority(self, getForwardedAccount(self, authorityAddress)), getForwardedAccount(self, authorityAddress)));
return self.Storage.getBool(id);
}
|
* @return { "registered" : "Return if the authority is registered" }
*/
function isRegisteredAuthority(Data storage self, address authorityAddress) internal view returns (bool registered) {
bytes32 id = keccak256(abi.encodePacked('registered.authority', getFirmFromAuthority(self, getForwardedAccount(self, authorityAddress)), getForwardedAccount(self, authorityAddress)));
return self.Storage.getBool(id);
}
| 26,822
|
20
|
// when buy
|
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWallet, "Max Wallet Exceeded");
}
|
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy.");
require(amount + balanceOf(to) <= maxWallet, "Max Wallet Exceeded");
}
| 27,449
|
21
|
// Assign balance to a new variable.
|
uint value_ = (uint) (balance);
|
uint value_ = (uint) (balance);
| 44,600
|
13
|
// transfer, transferFrom must respect the result of verifyTransfer
|
function verifyTransfer(address _from, address _to, uint256 _value) external returns (bool success);
|
function verifyTransfer(address _from, address _to, uint256 _value) external returns (bool success);
| 3,317
|
71
|
// disallow ETH payments to TimeVault
|
function() payable {
throw;
}
|
function() payable {
throw;
}
| 38,648
|
9
|
// 删除一个管理员 /
|
function removeAdmin(address admin) public returns(bool){
require(_initialized);
bool sucess;
bytes memory result;
(sucess,result)= logicVersion.delegatecall(abi.encodeWithSignature("removeAdmin(address)",admin));
if(!sucess){
require(sucess,parseErrMsg(result));
}
return (sucess && bytesToBool(result));
}
|
function removeAdmin(address admin) public returns(bool){
require(_initialized);
bool sucess;
bytes memory result;
(sucess,result)= logicVersion.delegatecall(abi.encodeWithSignature("removeAdmin(address)",admin));
if(!sucess){
require(sucess,parseErrMsg(result));
}
return (sucess && bytesToBool(result));
}
| 6,140
|
20
|
// Adds multiple addresses as controllers in the contract. _addresses An array of addresses to be added as controllers. /
|
function addControllers(address[] calldata _addresses) external onlyOwner {
for (uint256 i = 0; i < _addresses.length; i++) {
_controller[_addresses[i]] = true;
}
}
|
function addControllers(address[] calldata _addresses) external onlyOwner {
for (uint256 i = 0; i < _addresses.length; i++) {
_controller[_addresses[i]] = true;
}
}
| 31,978
|
175
|
// This is the maximum amount that participant1 can receive at settlement time
|
participant1_net_max_received = (
participant2_max_transferred -
participant1_max_transferred
);
|
participant1_net_max_received = (
participant2_max_transferred -
participant1_max_transferred
);
| 68,274
|
28
|
// Validate the rule
|
require(
|
require(
| 33,332
|
6
|
// adding to array, string always with memory or storage
|
function addPerson(string memory _name, uint256 _favoriteNumber) public {
people.push(People(_favoriteNumber,_name));
nameToFavoriteNumber[_name] = _favoriteNumber;
}
|
function addPerson(string memory _name, uint256 _favoriteNumber) public {
people.push(People(_favoriteNumber,_name));
nameToFavoriteNumber[_name] = _favoriteNumber;
}
| 24,897
|
6
|
// Returns a list of all the identifiersreturn a lit of all the identifiers /
|
function getIds() public view returns(uint256[] memory) {
return _ids;
}
|
function getIds() public view returns(uint256[] memory) {
return _ids;
}
| 51,816
|
88
|
// Returns auction info for an FT (ERC-20) on auction./_tokenAddress - Address of FT (ERC-20) on auction./_auctionNumber - Auction Number for the token
|
function getAuction(address _tokenAddress, uint256 _auctionNumber)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt,
|
function getAuction(address _tokenAddress, uint256 _auctionNumber)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt,
| 28,231
|
207
|
// Get the price of the current request for a random number
|
uint256 QUERY_EXECUTION_DELAY = 0;
uint256 GAS_FOR_CALLBACK = 350000;
provable_setCustomGasPrice(_gasprice * 10**9);
queryPrice = provable_getPrice("random", GAS_FOR_CALLBACK);
|
uint256 QUERY_EXECUTION_DELAY = 0;
uint256 GAS_FOR_CALLBACK = 350000;
provable_setCustomGasPrice(_gasprice * 10**9);
queryPrice = provable_getPrice("random", GAS_FOR_CALLBACK);
| 46,958
|
23
|
// May emit a {RoleGranted} event/_address address to grant ArtistManager role/ return true if the role was successfully granted
|
function addArtistManager(address _address)
external
onlyManager
returns (bool)
{
_grantRole(ARTIST_MANAGER_ROLE, _address);
return true;
}
|
function addArtistManager(address _address)
external
onlyManager
returns (bool)
{
_grantRole(ARTIST_MANAGER_ROLE, _address);
return true;
}
| 11,913
|
16
|
// withrawal eth
|
uint256 ownerShareEth = _getOwnerEth();
if (ownerShareEth > 0) {
payable(creatorWallet).transfer(ownerShareEth);
}
|
uint256 ownerShareEth = _getOwnerEth();
if (ownerShareEth > 0) {
payable(creatorWallet).transfer(ownerShareEth);
}
| 11,973
|
228
|
// calculate ppt for round mask
|
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
|
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
| 5,214
|
56
|
// Utility method to handle ether or token transfers./Reverts if transfer fails/tokenAddress address of token to transfer/recipient recipient of the ether / token transfer/amount amount of ether / token to transfer in wei
|
function _transferFunds(address tokenAddress, address recipient, uint256 amount) internal {
if (tokenAddress != ETHAddress) {
IERC20Upgradeable(tokenAddress).safeTransfer(recipient, amount);
} else {
assembly {
// (bool success, ) = recipient.call{ value: amount }("");
// if (!success)
if iszero(call(gas(), recipient, amount, 0, 0, 0, 0)) {
mstore(0x00, 0x90b8ec18) // revert TransferFailed();
revert(0x1c, 0x04)
}
}
}
}
|
function _transferFunds(address tokenAddress, address recipient, uint256 amount) internal {
if (tokenAddress != ETHAddress) {
IERC20Upgradeable(tokenAddress).safeTransfer(recipient, amount);
} else {
assembly {
// (bool success, ) = recipient.call{ value: amount }("");
// if (!success)
if iszero(call(gas(), recipient, amount, 0, 0, 0, 0)) {
mstore(0x00, 0x90b8ec18) // revert TransferFailed();
revert(0x1c, 0x04)
}
}
}
}
| 48,014
|
67
|
// How much you must pay to claim the throne now, in finney.
|
function currentClaimPriceInFinney() constant
|
function currentClaimPriceInFinney() constant
| 42,369
|
10
|
// approve(_to, _order.itemId);
|
owner.transfer(_order.price * _amount * (1 - fee_percent / 100));
fee_addr.transfer(_order.price * _amount * (fee_percent / 100));
safeTransferFrom(owner, _to, _order.itemId, _amount, "");
_order.amount -= _amount;
|
owner.transfer(_order.price * _amount * (1 - fee_percent / 100));
fee_addr.transfer(_order.price * _amount * (fee_percent / 100));
safeTransferFrom(owner, _to, _order.itemId, _amount, "");
_order.amount -= _amount;
| 39,865
|
61
|
// Add ethereum to send to Bankroll
|
totalEthBankrollCollected = SafeMath.add(totalEthBankrollCollected, _bankrollPayout);
|
totalEthBankrollCollected = SafeMath.add(totalEthBankrollCollected, _bankrollPayout);
| 35,666
|
19
|
// Increase both counters by 32 bytes each iteration.
|
mc := add(mc, 0x20)
cc := add(cc, 0x20)
|
mc := add(mc, 0x20)
cc := add(cc, 0x20)
| 58,839
|
7
|
// This contract cannot stake Ether.
|
receive() external payable {
revert("cannot stake Ether");
}
|
receive() external payable {
revert("cannot stake Ether");
}
| 55,483
|
37
|
// the number of owners that must confirm the same operation before it is run.
|
uint public m_required;
|
uint public m_required;
| 76,951
|
16
|
// BİTİŞ
|
function finishTheGameAndStoreGameData() private {
Game memory finishedGame = Game({ //GAME STRUCT kayıt olarak kullanılacak. Oyun bittikten sonra oluşturulacak.
gameID: gameCounter,
luckyNumber: luckyNumber,
participants: gameParticipants, //Get participants from function as array
totalReward: getTotalReward(),
winners: winners // getWinners()
});
games[gameCounter] = finishedGame;
keysOfGames.push(gameCounter);
gameCounter++;
emit GameEnd(gameCounter, luckyNumber, winners);
beReadyToNewGame();
}
|
function finishTheGameAndStoreGameData() private {
Game memory finishedGame = Game({ //GAME STRUCT kayıt olarak kullanılacak. Oyun bittikten sonra oluşturulacak.
gameID: gameCounter,
luckyNumber: luckyNumber,
participants: gameParticipants, //Get participants from function as array
totalReward: getTotalReward(),
winners: winners // getWinners()
});
games[gameCounter] = finishedGame;
keysOfGames.push(gameCounter);
gameCounter++;
emit GameEnd(gameCounter, luckyNumber, winners);
beReadyToNewGame();
}
| 6,670
|
38
|
// Set whitelisted status
|
isWhitelisted[_evilOwner] = true;
|
isWhitelisted[_evilOwner] = true;
| 39,713
|
21
|
// Compute λ, which is the linear scale factor between the currentutility and the utility of the identity curve λ =utility / utilityOfIdentityCurve use λ to compute x', which is the projection of the current balance of x onto the identity curve. x' = balanceOfX / λReordering these operations: x' = balanceOfX / utilityutilityOfIdentityCurve
|
int128 xPrime = balanceOfX.divu(currentUtility).mul(utilityOfIdentityCurve);
require(xPrime > 0, "UtilityError :: Invalid x'");
|
int128 xPrime = balanceOfX.divu(currentUtility).mul(utilityOfIdentityCurve);
require(xPrime > 0, "UtilityError :: Invalid x'");
| 39,298
|
17
|
// Caller withdraws the staking token and its pending rewards, if any _amount amount of staking token to withdraw /
|
function withdraw(uint256 _amount) external override nonReentrant {
updateAllRewards();
uint256 _currentAmount = userAmount[msg.sender];
require(_currentAmount >= _amount, "withdraw: not good");
uint256 newUserAmount = _currentAmount - _amount;
if (!isStopped) {
for (uint256 i = 0; i < rewardInfo.length; i++) {
RewardInfo memory _reward = rewardInfo[i];
uint256 _pending =
((_currentAmount * _reward.accTokenPerShare) / 1e18) -
rewardDebt[i][msg.sender];
rewardDebt[i][msg.sender] =
(newUserAmount * _reward.accTokenPerShare) /
1e18;
rewardPaid[i][msg.sender] += _pending;
_reward.rewardToken.safeTransfer(msg.sender, _pending);
}
}
userAmount[msg.sender] = newUserAmount;
stakingToken.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _amount);
}
|
function withdraw(uint256 _amount) external override nonReentrant {
updateAllRewards();
uint256 _currentAmount = userAmount[msg.sender];
require(_currentAmount >= _amount, "withdraw: not good");
uint256 newUserAmount = _currentAmount - _amount;
if (!isStopped) {
for (uint256 i = 0; i < rewardInfo.length; i++) {
RewardInfo memory _reward = rewardInfo[i];
uint256 _pending =
((_currentAmount * _reward.accTokenPerShare) / 1e18) -
rewardDebt[i][msg.sender];
rewardDebt[i][msg.sender] =
(newUserAmount * _reward.accTokenPerShare) /
1e18;
rewardPaid[i][msg.sender] += _pending;
_reward.rewardToken.safeTransfer(msg.sender, _pending);
}
}
userAmount[msg.sender] = newUserAmount;
stakingToken.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _amount);
}
| 48,071
|
0
|
// Internal state to the contract
|
string private greeting;
|
string private greeting;
| 8,373
|
100
|
// Checks if the proxy address already existed and dst address is still the owner
|
if (proxy == address(0) || ProxyLike(proxy).owner() != dst) {
uint csize;
assembly {
csize := extcodesize(dst)
}
|
if (proxy == address(0) || ProxyLike(proxy).owner() != dst) {
uint csize;
assembly {
csize := extcodesize(dst)
}
| 2,876
|
27
|
// Sets the base tokenURI. /
|
function setBaseTokenURI(string calldata newBaseTokenURI) public virtual onlyRole(DEFAULT_STEERING_ROLE) {
MythicsStorage.layout().baseTokenURI = newBaseTokenURI;
}
|
function setBaseTokenURI(string calldata newBaseTokenURI) public virtual onlyRole(DEFAULT_STEERING_ROLE) {
MythicsStorage.layout().baseTokenURI = newBaseTokenURI;
}
| 7,643
|
15
|
// An event emitted when the voting period is set
|
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
|
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
| 68,707
|
183
|
// Write the first 32 bytes
|
mstore(dest, first)
|
mstore(dest, first)
| 18,011
|
18
|
// OPERATOR ONLY: Remove a new module from the SetToken._module Module to remove /
|
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
|
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
| 18,224
|
20
|
// Function to create a smart contract of the Health centers
|
function FactoryHealthCenter () public {
//Filtered so that only validated health centers are capable of executing this function
require (Validate_HealthCenter[msg.sender] == true, "You do not have permission.");
//Generate a smart Contract --> Generate address
address contract_HealthCenter = address (new ContractHealthCenter(msg.sender));
//save the address of the new contract in to array
address_contracts_health.push(contract_HealthCenter);
//Related the HealthCenter with the contract
CenterHealth_Contract[msg.sender] = contract_HealthCenter;
//Emit event
emit NewContract (contract_HealthCenter , msg.sender);
}
|
function FactoryHealthCenter () public {
//Filtered so that only validated health centers are capable of executing this function
require (Validate_HealthCenter[msg.sender] == true, "You do not have permission.");
//Generate a smart Contract --> Generate address
address contract_HealthCenter = address (new ContractHealthCenter(msg.sender));
//save the address of the new contract in to array
address_contracts_health.push(contract_HealthCenter);
//Related the HealthCenter with the contract
CenterHealth_Contract[msg.sender] = contract_HealthCenter;
//Emit event
emit NewContract (contract_HealthCenter , msg.sender);
}
| 41,131
|
44
|
// 15 IN DATA / SET DATA / GET DATA / STRING / PUBLIC / ONLY OWNER / CONSTANT
|
string inCCH_edit_15 = " une première phrase " ;
|
string inCCH_edit_15 = " une première phrase " ;
| 53,624
|
11
|
// EscapeRequested: :point has requested a new :sponsor
|
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
|
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
| 57,559
|
0
|
// Compatible address
|
address public compatibleToken;
address public compatibleB;
|
address public compatibleToken;
address public compatibleB;
| 27,199
|
56
|
// Only COUPON_ADMIN_ROLE holders can add and modify a coupon.
|
bytes32 private couponAdminRole;
function addCoupon(
string calldata _couponid,
uint8 _discount,
uint256 _totalSupply,
uint256 _expireTimestamp,
string calldata _opt_tier
)
public virtual
|
bytes32 private couponAdminRole;
function addCoupon(
string calldata _couponid,
uint8 _discount,
uint256 _totalSupply,
uint256 _expireTimestamp,
string calldata _opt_tier
)
public virtual
| 13,417
|
29
|
// A contract implementing all standard ERC20 functionality for the Beercoin /
|
contract ERC20Beercoin is ExplorableBeercoin {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowances;
/**
* Beercoin's name
*/
function name() public pure returns (string) {
return "Beercoin";
}
/**
* Beercoin's symbol
*/
function symbol() public pure returns (string) {
return "🍺";
}
/**
* Beercoin's decimal places
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* The current total supply of Beercoins
*/
function totalSupply() public view returns (uint256) {
uint256 caps = packedScannedCaps;
uint256 supply = INITIAL_SUPPLY;
supply += (caps >> 192) * DIAMOND_VALUE;
supply += ((caps >> 128) & 0xFFFFFFFFFFFFFFFF) * GOLD_VALUE;
supply += ((caps >> 64) & 0xFFFFFFFFFFFFFFFF) * SILVER_VALUE;
supply += (caps & 0xFFFFFFFFFFFFFFFF) * BRONZE_VALUE;
return supply - burntValue;
}
/**
* Check the balance of a Beercoin user
*
* @param _owner the user to check
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* Transfer Beercoins to another user
*
* @param _to the address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != 0x0);
uint256 balanceFrom = balances[msg.sender];
require(_value <= balanceFrom);
uint256 oldBalanceTo = balances[_to];
uint256 newBalanceTo = oldBalanceTo + _value;
require(oldBalanceTo <= newBalanceTo);
balances[msg.sender] = balanceFrom - _value;
balances[_to] = newBalanceTo;
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer Beercoins from other address if a respective allowance exists
*
* @param _from the address of the sender
* @param _to the address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != 0x0);
uint256 balanceFrom = balances[_from];
uint256 allowanceFrom = allowances[_from][msg.sender];
require(_value <= balanceFrom);
require(_value <= allowanceFrom);
uint256 oldBalanceTo = balances[_to];
uint256 newBalanceTo = oldBalanceTo + _value;
require(oldBalanceTo <= newBalanceTo);
balances[_from] = balanceFrom - _value;
balances[_to] = newBalanceTo;
allowances[_from][msg.sender] = allowanceFrom - _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Allow another user to spend a certain amount of Beercoins on your behalf
*
* @param _spender the address of the user authorized to spend
* @param _value the maximum amount that can be spent on your behalf
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* The amount of Beercoins that can be spent by a user on behalf of another
*
* @param _owner the address of the user user whose Beercoins are spent
* @param _spender the address of the user who executes the transaction
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances[_owner][_spender];
}
}
|
contract ERC20Beercoin is ExplorableBeercoin {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowances;
/**
* Beercoin's name
*/
function name() public pure returns (string) {
return "Beercoin";
}
/**
* Beercoin's symbol
*/
function symbol() public pure returns (string) {
return "🍺";
}
/**
* Beercoin's decimal places
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* The current total supply of Beercoins
*/
function totalSupply() public view returns (uint256) {
uint256 caps = packedScannedCaps;
uint256 supply = INITIAL_SUPPLY;
supply += (caps >> 192) * DIAMOND_VALUE;
supply += ((caps >> 128) & 0xFFFFFFFFFFFFFFFF) * GOLD_VALUE;
supply += ((caps >> 64) & 0xFFFFFFFFFFFFFFFF) * SILVER_VALUE;
supply += (caps & 0xFFFFFFFFFFFFFFFF) * BRONZE_VALUE;
return supply - burntValue;
}
/**
* Check the balance of a Beercoin user
*
* @param _owner the user to check
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* Transfer Beercoins to another user
*
* @param _to the address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != 0x0);
uint256 balanceFrom = balances[msg.sender];
require(_value <= balanceFrom);
uint256 oldBalanceTo = balances[_to];
uint256 newBalanceTo = oldBalanceTo + _value;
require(oldBalanceTo <= newBalanceTo);
balances[msg.sender] = balanceFrom - _value;
balances[_to] = newBalanceTo;
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer Beercoins from other address if a respective allowance exists
*
* @param _from the address of the sender
* @param _to the address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != 0x0);
uint256 balanceFrom = balances[_from];
uint256 allowanceFrom = allowances[_from][msg.sender];
require(_value <= balanceFrom);
require(_value <= allowanceFrom);
uint256 oldBalanceTo = balances[_to];
uint256 newBalanceTo = oldBalanceTo + _value;
require(oldBalanceTo <= newBalanceTo);
balances[_from] = balanceFrom - _value;
balances[_to] = newBalanceTo;
allowances[_from][msg.sender] = allowanceFrom - _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Allow another user to spend a certain amount of Beercoins on your behalf
*
* @param _spender the address of the user authorized to spend
* @param _value the maximum amount that can be spent on your behalf
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* The amount of Beercoins that can be spent by a user on behalf of another
*
* @param _owner the address of the user user whose Beercoins are spent
* @param _spender the address of the user who executes the transaction
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances[_owner][_spender];
}
}
| 41,919
|
81
|
// _token Address of the token being sold /
|
constructor (AvailComToken _token) public {
require(_token != address(0));
// 0000 is added to the rate because decimal 4
rate = 167000000;
wallet = msg.sender;
token = _token;
}
|
constructor (AvailComToken _token) public {
require(_token != address(0));
// 0000 is added to the rate because decimal 4
rate = 167000000;
wallet = msg.sender;
token = _token;
}
| 32,860
|
124
|
// Convert the RCN into MANA using the designated and save the received MANA
|
uint256 boughtMana = convertSafe(mortgage.tokenConverter, rcn, mana, loanAmount);
delete mortgage.tokenConverter;
|
uint256 boughtMana = convertSafe(mortgage.tokenConverter, rcn, mana, loanAmount);
delete mortgage.tokenConverter;
| 20,392
|
218
|
// Send the remain money back
|
if(amount < _amount) {
SavingLib.send(globalConfig, _amount.sub(amount), _token);
}
|
if(amount < _amount) {
SavingLib.send(globalConfig, _amount.sub(amount), _token);
}
| 15,077
|
117
|
// Calculate burn amount and Special amount
|
uint256 burnAmt = amount.mul(_burnFee).div(100);
uint256 SpecialAmt = amount.mul(_SpecialFee).div(100);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, (amount.sub(burnAmt).sub(SpecialAmt)));
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
|
uint256 burnAmt = amount.mul(_burnFee).div(100);
uint256 SpecialAmt = amount.mul(_SpecialFee).div(100);
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, (amount.sub(burnAmt).sub(SpecialAmt)));
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
| 12,092
|
21
|
// Follow a similar pattern to reentency guard from OZ
|
destinationChecked_[TributeType.ERC721] = NOTCHECKED_;
destinationChecked_[TributeType.ERC1155] = NOTCHECKED_;
|
destinationChecked_[TributeType.ERC721] = NOTCHECKED_;
destinationChecked_[TributeType.ERC1155] = NOTCHECKED_;
| 78,209
|
338
|
// profit remains unchanged unless there is not enough to pay it
|
if (amountRequired.sub(_debtPayment) < _profit) {
_profit = amountRequired.sub(_debtPayment);
}
|
if (amountRequired.sub(_debtPayment) < _profit) {
_profit = amountRequired.sub(_debtPayment);
}
| 38,164
|
177
|
// ander paid
|
require(mintedAmount + quantity <= maxMintSupply, "MAXL");
require(
minterToTokenAmount[msg.sender] + quantity <= maxAmountWallet,
"MAXP"
);
require(msg.value >= cost * quantity, "SETH");
|
require(mintedAmount + quantity <= maxMintSupply, "MAXL");
require(
minterToTokenAmount[msg.sender] + quantity <= maxAmountWallet,
"MAXP"
);
require(msg.value >= cost * quantity, "SETH");
| 85,177
|
14
|
// Implements ERC 20 Token standard: https:github.com/ethereum/EIPs/issues/20
|
contract StandardToken is AbstractToken, Owned {
/*
* Data structures
*/
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
/*
* Read and write storage functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/*
* Read storage functions
*/
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
|
contract StandardToken is AbstractToken, Owned {
/*
* Data structures
*/
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
/*
* Read and write storage functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/*
* Read storage functions
*/
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
| 46,761
|
49
|
// get list of vault and balance where user can get reimbursement
|
function getVaultsBalance(address user) external view returns(address[] memory vault, uint256[] memory balance) {
vault = vaults[user]._values;
balance = new uint256[](vault.length);
for (uint i = 0; i < vault.length; i++) {
balance[i] = balances[vault[i]][user];
}
}
|
function getVaultsBalance(address user) external view returns(address[] memory vault, uint256[] memory balance) {
vault = vaults[user]._values;
balance = new uint256[](vault.length);
for (uint i = 0; i < vault.length; i++) {
balance[i] = balances[vault[i]][user];
}
}
| 32,874
|
0
|
// IOniProfile. /
|
interface IOniProfile {
function createProfile(
uint256 _teamId,
address _nftAddress,
uint256 _tokenId
) external;
/**
* @dev To pause user profile. It releases the NFT.
* Callable only by registered users.
*/
function pauseProfile() external;
/**
* @dev To update user profile.
* Callable only by registered users.
*/
function updateProfile() external;
/**
* @dev To reactivate user profile.
* Callable only by registered users.
*/
function reactivateProfile(address _nftAddress, uint256 _tokenId) external;
/**
* @dev To increase the number of points for a user.
* Callable only by point admins
*/
function increaseUserPoints(
address _userAddress,
uint256 _numberPoints,
uint256 _campaignId
) external;
/**
* @dev To increase the number of points for a set of users.
* Callable only by point admins
*/
function increaseUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints,
uint256 _campaignId
) external;
/**
* @dev To increase the number of points for a team.
* Callable only by point admins
*/
function increaseTeamPoints(
uint256 _teamId,
uint256 _numberPoints,
uint256 _campaignId
) external;
/**
* @dev To remove the number of points for a user.
* Callable only by point admins
*/
function removeUserPoints(address _userAddress, uint256 _numberPoints)
external;
/**
* @dev To remove a set number of points for a set of users.
*/
function removeUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints
) external;
/**
* @dev To remove the number of points for a team.
* Callable only by point admins
*/
function removeTeamPoints(uint256 _teamId, uint256 _numberPoints) external;
/**
* @dev To add a NFT contract address for users to set their profile.
* Callable only by owner admins.
*/
function addNftAddress(address _nftAddress) external;
/**
* @dev Add a new teamId
* Callable only by owner admins.
*/
function addTeam() external;
/**
* @dev Function to change team.
* Callable only by special admins.
*/
function changeTeam(address _userAddress, uint256 _newTeamId) external;
/**
* @dev Claim ONI to burn later.
* Callable only by owner admins.
*/
function claimFee(uint256 _amount) external;
/**
* @dev Make a team joinable again.
* Callable only by owner admins.
*/
function makeTeamJoinable(uint256 _teamId) external;
/**
* @dev Make a team not joinable.
* Callable only by owner admins.
*/
function makeTeamNotJoinable(uint256 _teamId) external;
/**
* @dev Rename a team
* Callable only by owner admins.
*/
function renameTeam() external;
/**
* @dev Update the number of ONI to register
* Callable only by owner admins.
*/
function updateNumberCake() external;
/**
* @dev Check the user's profile for a given address
*/
function getUserProfile(address _userAddress)
external
view
returns (
uint256,
uint256,
uint256,
address,
uint256,
bool
);
/**
* @dev Check the user's status for a given address
*/
function getUserStatus(address _userAddress) external view returns (bool);
/**
* @dev Check a team's profile
*/
function getTeamProfile(uint256 _teamId)
external
view
returns (
string memory,
string memory,
uint256,
uint256,
bool
);
}
|
interface IOniProfile {
function createProfile(
uint256 _teamId,
address _nftAddress,
uint256 _tokenId
) external;
/**
* @dev To pause user profile. It releases the NFT.
* Callable only by registered users.
*/
function pauseProfile() external;
/**
* @dev To update user profile.
* Callable only by registered users.
*/
function updateProfile() external;
/**
* @dev To reactivate user profile.
* Callable only by registered users.
*/
function reactivateProfile(address _nftAddress, uint256 _tokenId) external;
/**
* @dev To increase the number of points for a user.
* Callable only by point admins
*/
function increaseUserPoints(
address _userAddress,
uint256 _numberPoints,
uint256 _campaignId
) external;
/**
* @dev To increase the number of points for a set of users.
* Callable only by point admins
*/
function increaseUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints,
uint256 _campaignId
) external;
/**
* @dev To increase the number of points for a team.
* Callable only by point admins
*/
function increaseTeamPoints(
uint256 _teamId,
uint256 _numberPoints,
uint256 _campaignId
) external;
/**
* @dev To remove the number of points for a user.
* Callable only by point admins
*/
function removeUserPoints(address _userAddress, uint256 _numberPoints)
external;
/**
* @dev To remove a set number of points for a set of users.
*/
function removeUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints
) external;
/**
* @dev To remove the number of points for a team.
* Callable only by point admins
*/
function removeTeamPoints(uint256 _teamId, uint256 _numberPoints) external;
/**
* @dev To add a NFT contract address for users to set their profile.
* Callable only by owner admins.
*/
function addNftAddress(address _nftAddress) external;
/**
* @dev Add a new teamId
* Callable only by owner admins.
*/
function addTeam() external;
/**
* @dev Function to change team.
* Callable only by special admins.
*/
function changeTeam(address _userAddress, uint256 _newTeamId) external;
/**
* @dev Claim ONI to burn later.
* Callable only by owner admins.
*/
function claimFee(uint256 _amount) external;
/**
* @dev Make a team joinable again.
* Callable only by owner admins.
*/
function makeTeamJoinable(uint256 _teamId) external;
/**
* @dev Make a team not joinable.
* Callable only by owner admins.
*/
function makeTeamNotJoinable(uint256 _teamId) external;
/**
* @dev Rename a team
* Callable only by owner admins.
*/
function renameTeam() external;
/**
* @dev Update the number of ONI to register
* Callable only by owner admins.
*/
function updateNumberCake() external;
/**
* @dev Check the user's profile for a given address
*/
function getUserProfile(address _userAddress)
external
view
returns (
uint256,
uint256,
uint256,
address,
uint256,
bool
);
/**
* @dev Check the user's status for a given address
*/
function getUserStatus(address _userAddress) external view returns (bool);
/**
* @dev Check a team's profile
*/
function getTeamProfile(uint256 _teamId)
external
view
returns (
string memory,
string memory,
uint256,
uint256,
bool
);
}
| 15,771
|
11
|
// Returns the current value of the investment portfolio /
|
function getInvestmentValue() public view virtual returns (uint256);
|
function getInvestmentValue() public view virtual returns (uint256);
| 23,403
|
10
|
// Error returned when attempting to create a publisher profile with an account already publisher
|
error ACCOUNT_ALREADY_PUBLISHER();
|
error ACCOUNT_ALREADY_PUBLISHER();
| 9,511
|
14
|
// compounds earnings and charges performance fee
|
function _harvest(address callFeeRecipient) internal whenNotPaused {
// IMasterChef(chef).deposit(poolId, 0);
// uint256 outputBal = IERC20(output).balanceOf(address(this));
// if (outputBal > 0) {
// chargeFees(callFeeRecipient);
// addLiquidity();
// uint256 wantHarvested = balanceOfWant();
// deposit();
// lastHarvest = block.timestamp;
// emit StratHarvest(msg.sender, wantHarvested, balanceOf());
// }
}
|
function _harvest(address callFeeRecipient) internal whenNotPaused {
// IMasterChef(chef).deposit(poolId, 0);
// uint256 outputBal = IERC20(output).balanceOf(address(this));
// if (outputBal > 0) {
// chargeFees(callFeeRecipient);
// addLiquidity();
// uint256 wantHarvested = balanceOfWant();
// deposit();
// lastHarvest = block.timestamp;
// emit StratHarvest(msg.sender, wantHarvested, balanceOf());
// }
}
| 19,960
|
225
|
// solhint-disable-next-line no-empty-blocks
|
interface IStableSwap3 is IStableSwap {
}
|
interface IStableSwap3 is IStableSwap {
}
| 12,843
|
88
|
// Assigns ownership of a specific Char to an address.
|
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of chars is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
charIndexToOwner[_tokenId] = _to;
// When creating new chars _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete charIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
//update trx count
addressToTrxCount[_to]++;
}
|
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of chars is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
charIndexToOwner[_tokenId] = _to;
// When creating new chars _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete charIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
//update trx count
addressToTrxCount[_to]++;
}
| 27,693
|
6
|
// brews tokens created per block.
|
uint256 public rewardPerBlock;
|
uint256 public rewardPerBlock;
| 20,639
|
45
|
// fees and burn the sold tokens
|
exchangefees.transfer(_feesEthereum);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
|
exchangefees.transfer(_feesEthereum);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
| 1,704
|
77
|
// message unnecessarily. For custom revert reasons use {tryMod}. Counterpart to Solidity's `%` operator. This function uses a `revert`opcode (which leaves remaining gas untouched) while Solidity uses aninvalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. /
|
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
|
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
| 784
|
21
|
// const name
|
bytes32 public constant override LINA = "LINA";
bytes32 public constant override LUSD = "lUSD";
|
bytes32 public constant override LINA = "LINA";
bytes32 public constant override LUSD = "lUSD";
| 30,684
|
100
|
// if the staking address is an LP, send 50% of penalty to redistributor, and 50% to lp lock address.
|
if(pool.isLP){
pool.stakingToken.safeTransfer(redistributor, penalty.div(2));
pool.stakingToken.safeTransfer(manager.getLpLock(), penalty.div(2));
}else {
|
if(pool.isLP){
pool.stakingToken.safeTransfer(redistributor, penalty.div(2));
pool.stakingToken.safeTransfer(manager.getLpLock(), penalty.div(2));
}else {
| 36,941
|
249
|
// Sets the risk parameters: collateral ratio and liquidation discount Owner function to set the risk parameters collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
|
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
|
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
| 26,092
|
171
|
// Returns whether tokenId exists.
|
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (_mint),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
|
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (_mint),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
| 17,557
|
17
|
// Pausable /
|
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
|
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
| 60,260
|
17
|
// add a sport vault address to count towards gamified staking volume/_sportVault address to set/value to set
|
function setSupportedSportVault(address _sportVault, bool value) external onlyOwner {
supportedSportVault[_sportVault] = value;
emit SupportedSportVaultSet(_sportVault, value);
}
|
function setSupportedSportVault(address _sportVault, bool value) external onlyOwner {
supportedSportVault[_sportVault] = value;
emit SupportedSportVaultSet(_sportVault, value);
}
| 18,869
|
27
|
// set fee to address.
|
function setFeeTo(address _feeTo) external;
|
function setFeeTo(address _feeTo) external;
| 16,642
|
139
|
// String operations. /
|
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
|
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
| 95
|
10
|
// Multiplier representing the discount on collateral that a liquidator receives /
|
uint public liquidationIncentiveMantissa;
|
uint public liquidationIncentiveMantissa;
| 27,962
|
18
|
// Submit a order-ring for validation and settlement./addressListList of each order's owner, tokenS, wallet, authAddr./ Note that next order's `tokenS` equals this order's/ `tokenB`./uintArgsList List of uint-type arguments in this order:/ amountS, amountB, validSince (second),/ validUntil (second), lrcFee, and rateAmountS./uint8ArgsList -/ List of unit8-type arguments, in this order:/ marginSplitPercentageList./buyNoMoreThanAmountBList -/ This indicates when a order should be considered/vListList of v for each order. This list is 1-larger than/ the previous lists, with the last element being the/ v value of the ring signature./rListList of r for each order. This list is 1-larger than/ the previous lists, with the last element being
|
function submitRing(
address[4][] addressList,
uint[6][] uintArgsList,
uint8[1][] uint8ArgsList,
bool[] buyNoMoreThanAmountBList,
uint8[] vList,
bytes32[] rList,
bytes32[] sList,
address miner,
uint16 feeSelections
|
function submitRing(
address[4][] addressList,
uint[6][] uintArgsList,
uint8[1][] uint8ArgsList,
bool[] buyNoMoreThanAmountBList,
uint8[] vList,
bytes32[] rList,
bytes32[] sList,
address miner,
uint16 feeSelections
| 47,528
|
4
|
// [ERC20 functions]
| 6,991
|
||
29
|
// Standard Token Smart Contract/
|
contract StandardToken is ERC20, SafeMath {
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) balances;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) internal allowed;
/**
* Mapping from addresses of token holders to the mapping of token amount spent.
* Use by the token holders to spend their utility tokens.
*/
mapping (address => mapping (address => uint256)) spentamount;
/**
* Mapping of the addition of the addresse of buyers.
*/
mapping (address => bool) buyerAppended;
/**
* Mapping of the addition of addresses of buyers.
*/
address[] buyers;
/**
* Mapping of the addresses of VIP token holders.
*/
address[] vips;
/**
* Mapping for VIP rank for qualified token holders
* Higher VIP ranking (with earlier timestamp) has higher bidding priority when
* competing for the same product or service on platform.
* Higher VIP ranking address can outbid other lower ranking addresses only once per
* selling window or promotion period.
* Usage of the VIP ranking and bid priority will be described on token website.
*/
mapping (address => uint256) viprank;
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != 0x0);
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != 0x0);
if(_from == _to) return false;
if (balances[_from] < _value) return false;
if (_value > allowed[_from][msg.sender]) return false;
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve(address _spender, uint256 _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
return false;
}
if (balances[msg.sender] < _value) {
return false;
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance(address _owner, address _spender) constant
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
|
contract StandardToken is ERC20, SafeMath {
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) balances;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) internal allowed;
/**
* Mapping from addresses of token holders to the mapping of token amount spent.
* Use by the token holders to spend their utility tokens.
*/
mapping (address => mapping (address => uint256)) spentamount;
/**
* Mapping of the addition of the addresse of buyers.
*/
mapping (address => bool) buyerAppended;
/**
* Mapping of the addition of addresses of buyers.
*/
address[] buyers;
/**
* Mapping of the addresses of VIP token holders.
*/
address[] vips;
/**
* Mapping for VIP rank for qualified token holders
* Higher VIP ranking (with earlier timestamp) has higher bidding priority when
* competing for the same product or service on platform.
* Higher VIP ranking address can outbid other lower ranking addresses only once per
* selling window or promotion period.
* Usage of the VIP ranking and bid priority will be described on token website.
*/
mapping (address => uint256) viprank;
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != 0x0);
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != 0x0);
if(_from == _to) return false;
if (balances[_from] < _value) return false;
if (_value > allowed[_from][msg.sender]) return false;
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve(address _spender, uint256 _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
return false;
}
if (balances[msg.sender] < _value) {
return false;
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance(address _owner, address _spender) constant
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
| 25,383
|
73
|
// return the unreleased balance at the moment /
|
function unreleasedBalance() public view returns (uint256) {
return _totalBenefit - releasedBalance();
}
|
function unreleasedBalance() public view returns (uint256) {
return _totalBenefit - releasedBalance();
}
| 8,141
|
30
|
// The starting fee on taker trades in basis points
|
feeBPS = 20;
|
feeBPS = 20;
| 41,731
|
1
|
// checks that the contract's current phase is the expected one/p expected phase
|
modifier check(Phase p) {
checkPhase(p);
_;
}
|
modifier check(Phase p) {
checkPhase(p);
_;
}
| 27,131
|
843
|
// Set the new implied interest rate after the trade has taken effect, this will be used to calculate the next trader's interest rate.
|
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
|
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
| 63,340
|
2
|
// Tracks collateral
|
uint256 public borrowed_collat_historical;
uint256 public returned_collat_historical;
|
uint256 public borrowed_collat_historical;
uint256 public returned_collat_historical;
| 36,154
|
1
|
// Function to increase `jadeMinted` value
|
function _increaseMinted() internal {
_jadeMinted += 1;
}
|
function _increaseMinted() internal {
_jadeMinted += 1;
}
| 11,906
|
114
|
// Pay back to user
|
uint256 originalAmount = _lendingAmounts[index][msg.sender];
_usdtContract.transfer(msg.sender, originalAmount);
_redeemed[index][msg.sender] = true;
emit Redeem(msg.sender, originalAmount, index);
|
uint256 originalAmount = _lendingAmounts[index][msg.sender];
_usdtContract.transfer(msg.sender, originalAmount);
_redeemed[index][msg.sender] = true;
emit Redeem(msg.sender, originalAmount, index);
| 16,435
|
221
|
// @inheritdoc UUPSUpgradeable /
|
function _authorizeUpgrade(address) internal virtual override onlyOwner {}
}
|
function _authorizeUpgrade(address) internal virtual override onlyOwner {}
}
| 43,137
|
182
|
// new slot Reservoir address
|
address public reservoir;
|
address public reservoir;
| 29,225
|
7
|
// payload
|
chain.emitterChainID = encoded.toUint16(index);
index += 2;
chain.emitterAddress = encoded.toBytes32(index);
index += 32;
require(encoded.length == index, "invalid RegisterChain: wrong length");
|
chain.emitterChainID = encoded.toUint16(index);
index += 2;
chain.emitterAddress = encoded.toBytes32(index);
index += 32;
require(encoded.length == index, "invalid RegisterChain: wrong length");
| 28,630
|
84
|
// Must be called after crowdsale ends, to do some extra finalizationwork. Calls the contract's finalization function. /
|
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
emit Finalized();
isFinalized = true;
}
|
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
emit Finalized();
isFinalized = true;
}
| 4,850
|
221
|
// mintKey initiates a request to mint _value TrueUSD for account _to _to the address to mint to _value the amount requested /
|
function requestMint(address _to, uint256 _value) external mintNotPaused onlyMintKeyOrOwner {
MintOperation memory op = MintOperation(_to, _value, block.number, 0, false);
emit RequestMint(_to, _value, mintOperations.length, msg.sender);
mintOperations.push(op);
}
|
function requestMint(address _to, uint256 _value) external mintNotPaused onlyMintKeyOrOwner {
MintOperation memory op = MintOperation(_to, _value, block.number, 0, false);
emit RequestMint(_to, _value, mintOperations.length, msg.sender);
mintOperations.push(op);
}
| 1,102
|
243
|
// Token sale bonus expressed as percentage integer (10% = 10). /
|
uint256 public bonusSale;
|
uint256 public bonusSale;
| 22,109
|
46
|
// Get claimable strip token amount of a beneficiary beneficiary address of beneficiary /
|
function getVested(address beneficiary) public view virtual returns (uint256 _amountVested) {
require(beneficiary != address(0x00), "getVested: Invalid address");
VestingSchedule memory _vestingSchedule = recipients[beneficiary];
if (
!isStartTimeSet ||
(_vestingSchedule.totalAmount == 0) ||
(block.timestamp < startTime) ||
(block.timestamp < startTime.add(INITIAL_LOCK_PERIOD))
) {
return 0;
}
uint256 vestedPercent = 0;
uint256 firstVestingPoint = startTime.add(INITIAL_LOCK_PERIOD);
uint256 vestingPeriod = 270 days;
uint256 secondVestingPoint = firstVestingPoint.add(vestingPeriod);
if (block.timestamp > firstVestingPoint && block.timestamp <= secondVestingPoint) {
vestedPercent = 10 + (block.timestamp - firstVestingPoint).mul(90).div(vestingPeriod);
} else if (block.timestamp > secondVestingPoint) {
vestedPercent = 100;
}
uint256 vestedAmount = _vestingSchedule.totalAmount.mul(vestedPercent).div(100);
if (vestedAmount > _vestingSchedule.totalAmount) {
return _vestingSchedule.totalAmount;
}
return vestedAmount;
}
|
function getVested(address beneficiary) public view virtual returns (uint256 _amountVested) {
require(beneficiary != address(0x00), "getVested: Invalid address");
VestingSchedule memory _vestingSchedule = recipients[beneficiary];
if (
!isStartTimeSet ||
(_vestingSchedule.totalAmount == 0) ||
(block.timestamp < startTime) ||
(block.timestamp < startTime.add(INITIAL_LOCK_PERIOD))
) {
return 0;
}
uint256 vestedPercent = 0;
uint256 firstVestingPoint = startTime.add(INITIAL_LOCK_PERIOD);
uint256 vestingPeriod = 270 days;
uint256 secondVestingPoint = firstVestingPoint.add(vestingPeriod);
if (block.timestamp > firstVestingPoint && block.timestamp <= secondVestingPoint) {
vestedPercent = 10 + (block.timestamp - firstVestingPoint).mul(90).div(vestingPeriod);
} else if (block.timestamp > secondVestingPoint) {
vestedPercent = 100;
}
uint256 vestedAmount = _vestingSchedule.totalAmount.mul(vestedPercent).div(100);
if (vestedAmount > _vestingSchedule.totalAmount) {
return _vestingSchedule.totalAmount;
}
return vestedAmount;
}
| 40,276
|
15
|
// Calculates the increase in balance since the last user interaction user The address of the user for which the interest is being accumulatedreturn The previous principal balance, the new principal balance and the balance increase /
|
{
uint256 previousPrincipalBalance = super.balanceOf(user);
if (previousPrincipalBalance == 0) {
return (0, 0, 0);
}
// Calculation of the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease
);
}
|
{
uint256 previousPrincipalBalance = super.balanceOf(user);
if (previousPrincipalBalance == 0) {
return (0, 0, 0);
}
// Calculation of the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease
);
}
| 5,663
|
89
|
// Test ERC20 token This is part of an implementation of the Test Ideal Money protocol. Test is a normal ERC20 token, but its supply can be adjusted by splitting and combining tokens proportionally across all wallets.uFragment balances are internally represented with a hidden denomination, 'gons'. We support splitting the currency in expansion and combining the currency on contraction by changing the exchange rate between the hidden 'gons' and the public 'fragments'. /
|
contract Test is ERC20Detailed, 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 gons that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert gons to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Gon balances converted into Test are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Test to address 'B'. A's resulting external balance will
// be decreased by precisely x Test, and B's external balance will be precisely
// increased by x Test.
//
// 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 LogRebasePaused(bool paused);
event LogTokenPaused(bool paused);
event LogTestPolicyUpdated(address TestPolicy);
// Used for authentication
address public TestPolicy;
modifier onlyTestPolicy() {
require(msg.sender == TestPolicy);
_;
}
// Precautionary emergency controls.
bool public rebasePaused;
bool public tokenPaused;
modifier whenRebaseNotPaused() {
require(!rebasePaused);
_;
}
modifier whenTokenNotPaused() {
require(!tokenPaused);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_Test_SUPPLY = 50000000 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_Test_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_Test_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Test, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedTest;
/**
* @param TestPolicy_ The address of the Test policy contract to use for authentication.
*/
function setTestPolicy(address TestPolicy_)
external
onlyOwner
{
TestPolicy = TestPolicy_;
emit LogTestPolicyUpdated(TestPolicy_);
}
/**
* @dev Pauses or unpauses the execution of rebase operations.
* @param paused Pauses rebase operations if this is true.
*/
function setRebasePaused(bool paused)
external
onlyOwner
{
rebasePaused = paused;
emit LogRebasePaused(paused);
}
/**
* @dev Pauses or unpauses execution of ERC-20 transactions.
* @param paused Pauses ERC-20 transactions if this is true.
*/
function setTokenPaused(bool paused)
external
onlyOwner
{
tokenPaused = paused;
emit LogTokenPaused(paused);
}
/**
* @dev Notifies Test contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyTestPolicy
whenRebaseNotPaused
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
function initialize(address owner_)
public
initializer
{
ERC20Detailed.initialize("Ramifi Token", "RAM", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePaused = false;
tokenPaused = false;
_totalSupply = INITIAL_Test_SUPPLY;
_gonBalances[owner_] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
emit Transfer(address(0x0), owner_, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedTest[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
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
_allowedTest[from][msg.sender] = _allowedTest[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
whenTokenNotPaused
returns (bool)
{
_allowedTest[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
whenTokenNotPaused
returns (bool)
{
_allowedTest[msg.sender][spender] =
_allowedTest[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedTest[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
whenTokenNotPaused
returns (bool)
{
uint256 oldValue = _allowedTest[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedTest[msg.sender][spender] = 0;
} else {
_allowedTest[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedTest[msg.sender][spender]);
return true;
}
}
|
contract Test is ERC20Detailed, 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 gons that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert gons to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Gon balances converted into Test are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Test to address 'B'. A's resulting external balance will
// be decreased by precisely x Test, and B's external balance will be precisely
// increased by x Test.
//
// 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 LogRebasePaused(bool paused);
event LogTokenPaused(bool paused);
event LogTestPolicyUpdated(address TestPolicy);
// Used for authentication
address public TestPolicy;
modifier onlyTestPolicy() {
require(msg.sender == TestPolicy);
_;
}
// Precautionary emergency controls.
bool public rebasePaused;
bool public tokenPaused;
modifier whenRebaseNotPaused() {
require(!rebasePaused);
_;
}
modifier whenTokenNotPaused() {
require(!tokenPaused);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_Test_SUPPLY = 50000000 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_Test_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_Test_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Test, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedTest;
/**
* @param TestPolicy_ The address of the Test policy contract to use for authentication.
*/
function setTestPolicy(address TestPolicy_)
external
onlyOwner
{
TestPolicy = TestPolicy_;
emit LogTestPolicyUpdated(TestPolicy_);
}
/**
* @dev Pauses or unpauses the execution of rebase operations.
* @param paused Pauses rebase operations if this is true.
*/
function setRebasePaused(bool paused)
external
onlyOwner
{
rebasePaused = paused;
emit LogRebasePaused(paused);
}
/**
* @dev Pauses or unpauses execution of ERC-20 transactions.
* @param paused Pauses ERC-20 transactions if this is true.
*/
function setTokenPaused(bool paused)
external
onlyOwner
{
tokenPaused = paused;
emit LogTokenPaused(paused);
}
/**
* @dev Notifies Test contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyTestPolicy
whenRebaseNotPaused
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
function initialize(address owner_)
public
initializer
{
ERC20Detailed.initialize("Ramifi Token", "RAM", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePaused = false;
tokenPaused = false;
_totalSupply = INITIAL_Test_SUPPLY;
_gonBalances[owner_] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
emit Transfer(address(0x0), owner_, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedTest[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
validRecipient(to)
whenTokenNotPaused
returns (bool)
{
_allowedTest[from][msg.sender] = _allowedTest[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
public
whenTokenNotPaused
returns (bool)
{
_allowedTest[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
whenTokenNotPaused
returns (bool)
{
_allowedTest[msg.sender][spender] =
_allowedTest[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedTest[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
whenTokenNotPaused
returns (bool)
{
uint256 oldValue = _allowedTest[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedTest[msg.sender][spender] = 0;
} else {
_allowedTest[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedTest[msg.sender][spender]);
return true;
}
}
| 52,820
|
39
|
// Function to check which interfaces are suported by this contract. _interfaceID Id of the interface.return True if _interfaceID is supported, false otherwise. /
|
function supportsInterface(
bytes4 _interfaceID
)
external
override
view
returns (bool)
|
function supportsInterface(
bytes4 _interfaceID
)
external
override
view
returns (bool)
| 18,856
|
9
|
// mapping of tokenId to merkle root of the allowlist of addresses eligible to claim.
|
mapping(uint256 => bytes32) public merkleRoot;
address public immutable OldContract;
/*///////////////////////////////////////////////////////////////
Constructor + initializer logic
|
mapping(uint256 => bytes32) public merkleRoot;
address public immutable OldContract;
/*///////////////////////////////////////////////////////////////
Constructor + initializer logic
| 23,614
|
64
|
// Returns amount of time passed since start/
|
function vestedTime() public view returns (uint) {
uint currentTime = block.timestamp;
return currentTime.sub(start);
}
|
function vestedTime() public view returns (uint) {
uint currentTime = block.timestamp;
return currentTime.sub(start);
}
| 53,404
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.