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
|
|---|---|---|---|---|
18
|
// _to {address} address or recipient_value {uint} amount to transfer return{bool} true if successful
|
function transfer(address _to, uint _value) public onlyUnlocked returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
|
function transfer(address _to, uint _value) public onlyUnlocked returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 13,288
|
96
|
// Sets a new contract that implements the `InterestRate` interface.newInterestRateInterfaceThe new contract that implements the `InterestRateInterface` interface. /
|
function setInterestRateInterface(address newInterestRateInterface) external;
|
function setInterestRateInterface(address newInterestRateInterface) external;
| 39,887
|
52
|
// Return true or false if the account is whitelisted or notaccount The account of the userproof The Merkle Proof return true or false if the account is whitelisted or not/
|
function isWhiteListed(address account, bytes32[] calldata proof) internal view returns(bool) {
return _verify(_leaf(account), proof);
}
|
function isWhiteListed(address account, bytes32[] calldata proof) internal view returns(bool) {
return _verify(_leaf(account), proof);
}
| 35,192
|
118
|
// AT LAUNCH - Only allow 0.75% of total supply per transaction
|
maxPerTransaction = (totalSupply * 69) / 10000;
maxAllowedPerWallet = (totalSupply * 69) / 10000; // 0.75%
swapTokensAtAmount = (totalSupply * 1) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTax = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
|
maxPerTransaction = (totalSupply * 69) / 10000;
maxAllowedPerWallet = (totalSupply * 69) / 10000; // 0.75%
swapTokensAtAmount = (totalSupply * 1) / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTax = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
| 16,597
|
24
|
// Deduct burn amount from totalSupply
|
totalSupply=totalSupply.sub(_value,"ERC20: Burn Amount exceeds totalSupply");
emit Burn(Account, _value);
emit Transfer(Account, address(0), _value);
return true;
|
totalSupply=totalSupply.sub(_value,"ERC20: Burn Amount exceeds totalSupply");
emit Burn(Account, _value);
emit Transfer(Account, address(0), _value);
return true;
| 32,017
|
10
|
// This is the provenance record of all artwork in existence
|
string public constant ENTROPYSEEDS_PROVENANCE = "51aab9a30a64f0b1f8325ccfa7e80cbcc20b9dbab4b4e6765c3e5178e507d210";
|
string public constant ENTROPYSEEDS_PROVENANCE = "51aab9a30a64f0b1f8325ccfa7e80cbcc20b9dbab4b4e6765c3e5178e507d210";
| 54,718
|
17
|
// PaymentSplitter This contract allows to split Ether payments among a group of accounts. The sender does not need to be awarethat the Ether will be split in this way, since it is handled transparently by the contract. The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning eachaccount to a number of shares. Of all the Ether that this contract receives, each account will then be able to claiman amount proportional to the percentage of total shares they were assigned. `PaymentSplitter` follows a _pull payment_ model. This means that
|
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract MoneyHandler is Context, AccessControl{
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
IERC20 private token;
// uint256 public _totalShares;
uint256 public _totalReleased;
// uint256 public amu = 1;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
mapping(address => uint256) public collectionMoney;
address[] private _payees;
uint256 private _totalCllcAmnt;
bytes32 public constant COLLECTION_ROLE = bytes32(keccak256("COLLECTION_ROLE"));
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
/**
* @dev Getter for the total shares held by payees.
*/
// function totalShares() public view returns (uint256) {
// return _totalShares;
// }
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
function collecMny(address collection) public view returns (uint256) {
return collectionMoney[collection];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
function updateCollecMny(address collection, uint256 amount) public onlyRole(COLLECTION_ROLE) {
collectionMoney[collection] = collectionMoney[collection].add(amount);
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address account, address collection, address _token) private {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
_released[account] = _released[account].add(_shares[account]);
_totalReleased = _totalReleased.add(_shares[account]);
IERC20 token = IERC20(_token);
token.transfer(account, _shares[account]);
collectionMoney[collection] = collectionMoney[collection].sub(_shares[account]);
emit PaymentReleased(account, _shares[account]);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* // shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 sharePerc_, address collection, address _token) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
uint256 shares_ = getAmountPer(_totalCllcAmnt,sharePerc_);
_shares[account] = shares_;
_payees.push(account);
release(account, collection, _token);
// emit PayeeAdded(account, shares_);
}
//Get amount per person
function getAmountPer(uint256 totalAmount,uint256 sharePerc) private pure returns(uint256){
uint256 sharesmul_ = SafeMath.mul(totalAmount,sharePerc);
uint256 shares_ = SafeMath.div(sharesmul_,10**18);
return shares_;
}
function recoverToken(address _token)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
uint amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(msg.sender, amount);
}
function redeem (address collection, address _token, address[] memory payees, uint256 [] memory sharePerc_) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(payees.length > 0, "redeem: no payees");
require(payees.length == sharePerc_.length, "redeem: no payees");
_totalCllcAmnt = collectionMoney[collection];
require(_totalCllcAmnt > 0,"redeem: insufficient funds");
uint256 totalShareAmount;
for (uint256 i = 0; i < sharePerc_.length; i++) {
totalShareAmount = totalShareAmount.add(getAmountPer(_totalCllcAmnt, sharePerc_[i]));
}
require(_totalCllcAmnt >= totalShareAmount, "redeem: the total amount in the contract must be equal to or greater than the amount to be withdraw");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], sharePerc_[i], collection, _token);
}
}
}
|
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract MoneyHandler is Context, AccessControl{
using SafeMath for uint256;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
IERC20 private token;
// uint256 public _totalShares;
uint256 public _totalReleased;
// uint256 public amu = 1;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
mapping(address => uint256) public collectionMoney;
address[] private _payees;
uint256 private _totalCllcAmnt;
bytes32 public constant COLLECTION_ROLE = bytes32(keccak256("COLLECTION_ROLE"));
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
/**
* @dev Getter for the total shares held by payees.
*/
// function totalShares() public view returns (uint256) {
// return _totalShares;
// }
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
function collecMny(address collection) public view returns (uint256) {
return collectionMoney[collection];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
function updateCollecMny(address collection, uint256 amount) public onlyRole(COLLECTION_ROLE) {
collectionMoney[collection] = collectionMoney[collection].add(amount);
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address account, address collection, address _token) private {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
_released[account] = _released[account].add(_shares[account]);
_totalReleased = _totalReleased.add(_shares[account]);
IERC20 token = IERC20(_token);
token.transfer(account, _shares[account]);
collectionMoney[collection] = collectionMoney[collection].sub(_shares[account]);
emit PaymentReleased(account, _shares[account]);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* // shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 sharePerc_, address collection, address _token) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
uint256 shares_ = getAmountPer(_totalCllcAmnt,sharePerc_);
_shares[account] = shares_;
_payees.push(account);
release(account, collection, _token);
// emit PayeeAdded(account, shares_);
}
//Get amount per person
function getAmountPer(uint256 totalAmount,uint256 sharePerc) private pure returns(uint256){
uint256 sharesmul_ = SafeMath.mul(totalAmount,sharePerc);
uint256 shares_ = SafeMath.div(sharesmul_,10**18);
return shares_;
}
function recoverToken(address _token)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
uint amount = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(msg.sender, amount);
}
function redeem (address collection, address _token, address[] memory payees, uint256 [] memory sharePerc_) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(payees.length > 0, "redeem: no payees");
require(payees.length == sharePerc_.length, "redeem: no payees");
_totalCllcAmnt = collectionMoney[collection];
require(_totalCllcAmnt > 0,"redeem: insufficient funds");
uint256 totalShareAmount;
for (uint256 i = 0; i < sharePerc_.length; i++) {
totalShareAmount = totalShareAmount.add(getAmountPer(_totalCllcAmnt, sharePerc_[i]));
}
require(_totalCllcAmnt >= totalShareAmount, "redeem: the total amount in the contract must be equal to or greater than the amount to be withdraw");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], sharePerc_[i], collection, _token);
}
}
}
| 8,111
|
48
|
// De-affiliates a validator, removing it from the group for which it is a member.return True upon success. Fails if the account is not a validator with non-zero affiliation. /
|
function deaffiliate() external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(validator.affiliation != address(0), "deaffiliate: not affiliated");
_deaffiliate(validator, account);
return true;
}
|
function deaffiliate() external nonReentrant returns (bool) {
address account = getAccounts().validatorSignerToAccount(msg.sender);
require(isValidator(account), "Not a validator");
Validator storage validator = validators[account];
require(validator.affiliation != address(0), "deaffiliate: not affiliated");
_deaffiliate(validator, account);
return true;
}
| 14,651
|
1
|
// Handle the receipt of an NFT The BAC002 smart contract calls this function on the recipient /
|
function onBAC002Received(address operator, address from, uint256 assetId, bytes calldata data)
external returns (bytes4);
|
function onBAC002Received(address operator, address from, uint256 assetId, bytes calldata data)
external returns (bytes4);
| 31,778
|
111
|
// Updates the currently active fork to given block number This is similar to `roll` but for the currently active fork
|
function rollFork(uint256 blockNumber) external;
|
function rollFork(uint256 blockNumber) external;
| 12,936
|
56
|
// don't allow 0 transferFrom if no approval:
|
require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount");
|
require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount");
| 36,564
|
216
|
// adjustments[8] = point^degreeAdjustment(composition_degree_bound, 2(trace_length - 1), 1, trace_length / 4).
|
mstore(0x4f00,
expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f20), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 4)), PRIME))
|
mstore(0x4f00,
expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f20), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 4)), PRIME))
| 4,354
|
11
|
// GelatoCore canExec Gate
|
function providerCanExec(
address _userProxy,
Provider memory _provider,
Task memory _task,
uint256 _gelatoGasPrice
)
public
view
override
returns(string memory)
|
function providerCanExec(
address _userProxy,
Provider memory _provider,
Task memory _task,
uint256 _gelatoGasPrice
)
public
view
override
returns(string memory)
| 15,369
|
142
|
// The state after closed by the `beneficiary` account from STATE_INIT
|
uint internal constant STATE_CANCEL = 3;
|
uint internal constant STATE_CANCEL = 3;
| 46,458
|
76
|
// if the calculated collateral amount exceeds the amount still up for sale, adjust it to the remaining amount
|
boughtCollateral = (boughtCollateral > bids[id].amountToSell) ? bids[id].amountToSell : boughtCollateral;
return boughtCollateral;
|
boughtCollateral = (boughtCollateral > bids[id].amountToSell) ? bids[id].amountToSell : boughtCollateral;
return boughtCollateral;
| 47,454
|
30
|
// Only an owner can grant transfer approval.
|
require(_owns(msg.sender, _tokenId));
|
require(_owns(msg.sender, _tokenId));
| 60,125
|
49
|
// File: contracts/uniswapv2/UniswapV2Factory.sol
|
pragma solidity =0.6.12;
contract UniswapV2Factory is IUniswapV2Factory {
address public override feeTo;
address public override feeToSetter;
address public override migrator;
|
pragma solidity =0.6.12;
contract UniswapV2Factory is IUniswapV2Factory {
address public override feeTo;
address public override feeToSetter;
address public override migrator;
| 6,995
|
13
|
// Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of theL1 ERC20 token.This call will fail if the initialized withdrawal from L2 has not been finalized._l1Token Address of L1 token to finalizeWithdrawal for. _l2Token Address of L2 token where withdrawal was initiated. _from L2 address initiating the transfer. _to L1 address to credit the withdrawal to. _amount Amount of the ERC20 to deposit. _data Data provided by the sender on L2. This data is providedsolely as a convenience for external contracts. Aside from enforcing a maximumlength, these contracts provide no guarantees about its content. /
|
function finalizeERC20Withdrawal(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
|
function finalizeERC20Withdrawal(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
| 22,431
|
3
|
// Calculate sqrt(s) using Babylonian method
|
function sqrt(s) -> z {
switch gt(s, 3)
|
function sqrt(s) -> z {
switch gt(s, 3)
| 38,667
|
56
|
// Attributes byte pos - Definition 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. 00000010 - Producible - Product of a factory and/or factory contract. 00000100 - Explorable- Product of exploration. 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. 00010000 - Permanent - Cannot be removed, always owned by a user. 00100000 - Consumable - Destroyed after N exploration expeditions. 01000000 - Tradable - Buyable and sellable on the market. 10000000 - Hot Potato - Automatically gets put up
|
bytes2 attributes;
|
bytes2 attributes;
| 63,122
|
153
|
// Transfer COMP to the user, if they are above the threshold Note: If there is not enough COMP, we do not perform the transfer all. user The address of the user to transfer COMP to userAccrued The amount of COMP to (possibly) transferreturn The amount of COMP which was NOT transferred to the user /
|
function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Comp comp = Comp(getCompAddress());
uint compRemaining = comp.balanceOf(address(this));
if (userAccrued <= compRemaining) {
comp.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
|
function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Comp comp = Comp(getCompAddress());
uint compRemaining = comp.balanceOf(address(this));
if (userAccrued <= compRemaining) {
comp.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
| 17,025
|
20
|
// ======== Custom Errors ======== /
|
error Guarded__notRoot();
error Guarded__notGranted();
|
error Guarded__notRoot();
error Guarded__notGranted();
| 1,140
|
87
|
// 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 unsigned 60.18-decimal fixed-point number./ return result The result as an unsigned 60.18-decimal fixed-point number.
|
function exp2(uint256 x) internal pure returns (uint256 result) {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathUD60x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (x << 64) / SCALE;
// Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.
result = PRBMath.exp2(x192x64);
}
}
|
function exp2(uint256 x) internal pure returns (uint256 result) {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathUD60x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (x << 64) / SCALE;
// Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.
result = PRBMath.exp2(x192x64);
}
}
| 36,338
|
26
|
// Destroys tokens for an accountaccount Account whose tokens are destroyedvalue Amount of tokens to destroy
|
function burnTokens(address account, uint value) internal;
event Burned(address account, uint value);
|
function burnTokens(address account, uint value) internal;
event Burned(address account, uint value);
| 44,255
|
3
|
// Initializes a new buffer from an existing bytes object.Changes to the buffer may mutate the original value.b The bytes object to initialize the buffer with. return A new buffer./
|
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
|
function fromBytes(bytes memory b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
| 30,950
|
26
|
// _userWeekCursor is already at/beyond _maxClaimTimestamp meaning nothing to be claimed for this user. This can be: 1) User just lock their GF less than 1 week 2) User already claimed their rewards
|
if (_userWeekCursor >= _maxClaimTimestamp) {
return (0, _userEpoch, _userWeekCursor, _maxUserEpoch);
}
|
if (_userWeekCursor >= _maxClaimTimestamp) {
return (0, _userEpoch, _userWeekCursor, _maxUserEpoch);
}
| 39,119
|
708
|
// transfering Ethers to newly created quotation contract. /
|
function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy {
uint amount = address(this).balance;
IERC20 erc20;
if (amount > 0) {
// newAdd.transfer(amount);
Quotation newQT = Quotation(newAdd);
newQT.sendEther.value(amount)();
}
uint currAssetLen = pd.getAllCurrenciesLen();
for (uint64 i = 1; i < currAssetLen; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
address currAddr = pd.getCurrencyAssetAddress(currName);
erc20 = IERC20(currAddr); //solhint-disable-line
if (erc20.balanceOf(address(this)) > 0) {
require(erc20.transfer(newAdd, erc20.balanceOf(address(this))));
}
}
}
|
function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy {
uint amount = address(this).balance;
IERC20 erc20;
if (amount > 0) {
// newAdd.transfer(amount);
Quotation newQT = Quotation(newAdd);
newQT.sendEther.value(amount)();
}
uint currAssetLen = pd.getAllCurrenciesLen();
for (uint64 i = 1; i < currAssetLen; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
address currAddr = pd.getCurrencyAssetAddress(currName);
erc20 = IERC20(currAddr); //solhint-disable-line
if (erc20.balanceOf(address(this)) > 0) {
require(erc20.transfer(newAdd, erc20.balanceOf(address(this))));
}
}
}
| 33,572
|
63
|
// Loads the deposit term associated with the given term ID.
|
TermDeposit storage _term = deposit_terms[_term_id];
|
TermDeposit storage _term = deposit_terms[_term_id];
| 44,863
|
343
|
// Used to withdraw accumulated protocol fees. /
|
function collectProtocolFees(
uint256 amount0,
uint256 amount1
|
function collectProtocolFees(
uint256 amount0,
uint256 amount1
| 4,241
|
154
|
// Claim rewardToken from lender and convert it into DAI
|
function _claimRewardsAndConvertTo(address _toToken) internal virtual override {
uint256 _vspAmount = IERC20(VSP).balanceOf(address(this));
if (_vspAmount > 0) {
_safeSwap(VSP, _toToken, _vspAmount, 1);
}
}
|
function _claimRewardsAndConvertTo(address _toToken) internal virtual override {
uint256 _vspAmount = IERC20(VSP).balanceOf(address(this));
if (_vspAmount > 0) {
_safeSwap(VSP, _toToken, _vspAmount, 1);
}
}
| 61,654
|
1
|
// BTC Marketcap Storage
|
uint public btcMarketCap;
|
uint public btcMarketCap;
| 35,640
|
16
|
// We increase the counter.
|
characterCounter++;
|
characterCounter++;
| 3,964
|
44
|
// Mint token with no extension /
|
function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the extension that minted the token
_tokensExtension[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
|
function _mintBase(address to, string memory uri) internal virtual returns(uint256 tokenId) {
_tokenCount++;
tokenId = _tokenCount;
// Track the extension that minted the token
_tokensExtension[tokenId] = address(this);
_safeMint(to, tokenId);
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
// Call post mint
_postMintBase(to, tokenId);
return tokenId;
}
| 24,643
|
0
|
// @custom:oz-upgrades-unsafe-allow constructor
|
constructor() {
_disableInitializers();
}
|
constructor() {
_disableInitializers();
}
| 2,987
|
29
|
// transfer the ownership to other - Only the owner can operate /
|
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
|
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
| 4,817
|
13
|
// @inheritdoc ERC721Enumerable /
|
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
|
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
| 52,174
|
32
|
// The `getTotalDonations()` retrieve the Ether balance collected so far in Wei.
|
function getTotalDonations() public view returns (uint256) {
return convertToEther(finalized ? totalSencCollected : getSencBalance());
}
|
function getTotalDonations() public view returns (uint256) {
return convertToEther(finalized ? totalSencCollected : getSencBalance());
}
| 38,613
|
32
|
// Release tokens
|
if (unlockableTokens > 0)
this.transfer(_of, unlockableTokens);
|
if (unlockableTokens > 0)
this.transfer(_of, unlockableTokens);
| 16,934
|
158
|
// Cancel bet and relase all the bets back to the betters if, for any reason, payouts cannot be completed. (For example Oracle fails.) Triggered by owners.
|
function cancel() private {
canceled = true;
completed = false;
}
|
function cancel() private {
canceled = true;
completed = false;
}
| 25,090
|
39
|
// Function to check the amount of tokens that an owner allowed to a spender. /
|
function BecToken() {
totalSupply = 7000000000 * (10**(uint256(decimals)));
balances[msg.sender] = totalSupply; // Give the creator all initial tokens
}
|
function BecToken() {
totalSupply = 7000000000 * (10**(uint256(decimals)));
balances[msg.sender] = totalSupply; // Give the creator all initial tokens
}
| 58,818
|
126
|
// Get the balance of want held idle in the Strategy
|
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
|
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
| 25,082
|
0
|
// Grants `OPERATOR_ROLE` to the account that deploys the contract. /
|
function initialize(
string calldata _uri,
string calldata _name,
string calldata _symbol,
string calldata _description
)
public
initializer
|
function initialize(
string calldata _uri,
string calldata _name,
string calldata _symbol,
string calldata _description
)
public
initializer
| 77,672
|
123
|
// Set the system field and make it a system token
|
return setTokenType(setTokenSystem(token, uint16(index)), TOKEN_TYPE_SYSTEM);
|
return setTokenType(setTokenSystem(token, uint16(index)), TOKEN_TYPE_SYSTEM);
| 21,391
|
128
|
// Registers the delivery of an amount of funds to be returned as `_drawableFunds`.
|
function _returnFunds() internal returns (uint256 fundsReturned_) {
_drawableFunds += (fundsReturned_ = _getUnaccountedAmount(_fundsAsset));
}
|
function _returnFunds() internal returns (uint256 fundsReturned_) {
_drawableFunds += (fundsReturned_ = _getUnaccountedAmount(_fundsAsset));
}
| 82,854
|
176
|
// Add a partition to the total partitions collection. _partition Name of the partition. /
|
function _addPartitionToTotalPartitions(bytes32 _partition) internal {
_totalPartitions.push(_partition);
_indexOfTotalPartitions[_partition] = _totalPartitions.length;
}
|
function _addPartitionToTotalPartitions(bytes32 _partition) internal {
_totalPartitions.push(_partition);
_indexOfTotalPartitions[_partition] = _totalPartitions.length;
}
| 27,288
|
30
|
// tokenSums[0] is allowed sum
|
tokenSums[0] = tokenSums[0].add(allowedAmountForThisLockup);
|
tokenSums[0] = tokenSums[0].add(allowedAmountForThisLockup);
| 51,407
|
4
|
// HecoPool address /
|
address public hecoPool;
|
address public hecoPool;
| 46,940
|
2
|
// Allows user to send tokens to another account
|
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value, 'not enough in balance');
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
|
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value, 'not enough in balance');
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
| 22,133
|
56
|
// Returns a given node's last reward date. /
|
function getNodeLastRewardDate(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
|
function getNodeLastRewardDate(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (uint)
| 9,985
|
13
|
// Function is used to distribute insurance and close pool after period to start auction passed
|
function allowWithdrawalAfterNoAuction() external {
_accrueInterest();
bool isDefaulting = _state(_info) == State.Default;
bool auctionNotStarted = IAuction(factory.auction()).state(
address(this)
) == IAuction.State.NotStarted;
bool periodToStartPassed = block.timestamp >=
_info.lastAccrual + periodToStartAuction;
require(
isDefaulting && auctionNotStarted && periodToStartPassed,
"CDC"
);
_info.insurance = 0;
debtClaimed = true;
_close();
}
|
function allowWithdrawalAfterNoAuction() external {
_accrueInterest();
bool isDefaulting = _state(_info) == State.Default;
bool auctionNotStarted = IAuction(factory.auction()).state(
address(this)
) == IAuction.State.NotStarted;
bool periodToStartPassed = block.timestamp >=
_info.lastAccrual + periodToStartAuction;
require(
isDefaulting && auctionNotStarted && periodToStartPassed,
"CDC"
);
_info.insurance = 0;
debtClaimed = true;
_close();
}
| 37,723
|
154
|
// only if new end time in future
|
require(now < _endTime);
require(_endTime > openingTime);
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
closingTime = _endTime;
|
require(now < _endTime);
require(_endTime > openingTime);
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
closingTime = _endTime;
| 13,823
|
161
|
// query if an address is an authorized operator for another address/_owner the address that owns the NFTs/_operator the address that acts on behalf of the owner/ return true if `_operator` is an approved operator for `_owner`, false otherwise
|
function isApprovedForAll(address _owner, address _operator)
override
public
view
returns (bool)
|
function isApprovedForAll(address _owner, address _operator)
override
public
view
returns (bool)
| 24,007
|
28
|
// Frozen event
|
event FrozenFunds(address target, bool frozen);
|
event FrozenFunds(address target, bool frozen);
| 44,852
|
0
|
// Outstanding balance
|
mapping(address => uint256) public balance;
address public token;
event Deposit(address indexed _from, uint _value);
|
mapping(address => uint256) public balance;
address public token;
event Deposit(address indexed _from, uint _value);
| 26,128
|
48
|
// load invocations into memory
|
uint24 invocationsBefore = project.invocations;
uint24 invocationsAfter;
unchecked {
|
uint24 invocationsBefore = project.invocations;
uint24 invocationsAfter;
unchecked {
| 33,300
|
197
|
// StableMathmStableA library providing safe mathematical operations to multiply and divide with standardised precision. Derives from OpenZeppelin's SafeMath lib and uses generic system wide variables for managing precision. /
|
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e36 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
|
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e36 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
| 28,586
|
108
|
// Next line also asserts that (balances[id][token] >= amount);
|
balances[id][token] = balances[id][token].sub(amount);
|
balances[id][token] = balances[id][token].sub(amount);
| 45,909
|
27
|
// Unallocated
|
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
|
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
| 36,533
|
34
|
// Внутренние кошельки компании
|
address public walletICO = 0x8ffF4a8c4F1bd333a215f072ef9AEF934F677bFa;
uint public tokenICO = 31450000*10**decimals;
address public walletTeam = 0x7eF1ac89B028A9Bc20Ce418c1e6973F4c7977eB0;
uint public tokenTeam = 2960000*10**decimals;
address public walletAdvisor = 0xB6B01233cE7794D004aF238b3A53A0FcB1c5D8BD;
uint public tokenAdvisor = 1480000*10**decimals;
|
address public walletICO = 0x8ffF4a8c4F1bd333a215f072ef9AEF934F677bFa;
uint public tokenICO = 31450000*10**decimals;
address public walletTeam = 0x7eF1ac89B028A9Bc20Ce418c1e6973F4c7977eB0;
uint public tokenTeam = 2960000*10**decimals;
address public walletAdvisor = 0xB6B01233cE7794D004aF238b3A53A0FcB1c5D8BD;
uint public tokenAdvisor = 1480000*10**decimals;
| 44,632
|
13
|
// loanPosition.loanTokenAmountUsed = 0; <- not used yet
|
loanPosition.active = false;
_removePosition(
loanOrder.loanOrderHash,
loanPosition.trader
);
emit LogLoanClosed(
lender,
loanPosition.trader,
|
loanPosition.active = false;
_removePosition(
loanOrder.loanOrderHash,
loanPosition.trader
);
emit LogLoanClosed(
lender,
loanPosition.trader,
| 46,556
|
53
|
// Revokes the right to issue new tokens from the address specified. This function can be called by the owner only. addr The destination address /
|
function revokeMinter (address addr) public onlyOwner {
require(_authorizedMinters[addr], "Address was never authorized");
_authorizedMinters[addr] = false;
emit OnMinterRevoked(addr);
}
|
function revokeMinter (address addr) public onlyOwner {
require(_authorizedMinters[addr], "Address was never authorized");
_authorizedMinters[addr] = false;
emit OnMinterRevoked(addr);
}
| 43,849
|
124
|
// nofeeQty not counted
|
uint256 oldBalance = balanceOf(usr).sub(qty).sub(userNoFeeQty[usr]);
uint256 newQty = qty.sub(userNoFeeQtyFrom);
|
uint256 oldBalance = balanceOf(usr).sub(qty).sub(userNoFeeQty[usr]);
uint256 newQty = qty.sub(userNoFeeQtyFrom);
| 22,854
|
6
|
// Only the current owner can transfer the token.
|
if (msg.sender != owner) return;
|
if (msg.sender != owner) return;
| 5,866
|
652
|
// Import fee period from existing fee pool at index 0;
|
importFeePeriod_0();
|
importFeePeriod_0();
| 37,569
|
21
|
// 1
|
_structHash = keccak256(
abi.encode(
_blockhash,
totalAddresses,
_gasleft,
_externalRandomNumber
)
);
_randomNumber = uint256(_structHash);
|
_structHash = keccak256(
abi.encode(
_blockhash,
totalAddresses,
_gasleft,
_externalRandomNumber
)
);
_randomNumber = uint256(_structHash);
| 20,977
|
9
|
// array of Education structs
|
Education[] private _education;
Project[] private _projects;
|
Education[] private _education;
Project[] private _projects;
| 9,134
|
132
|
// To make sure that governance cannot come in and take away the coins
|
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
|
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
| 12,358
|
70
|
// active invest/reinvest deposits
|
for(uint i=0; i<user.deposits.length; i++) {
if(_isDepositDeceased(_user,i)) continue;
o_planInfo.dividends += _calculateDepositDividends(_user,i);
if(!user.deposits[i].isReinvest){ o_planInfo.mActive++; }
|
for(uint i=0; i<user.deposits.length; i++) {
if(_isDepositDeceased(_user,i)) continue;
o_planInfo.dividends += _calculateDepositDividends(_user,i);
if(!user.deposits[i].isReinvest){ o_planInfo.mActive++; }
| 16,907
|
3
|
// konstruktorfunction Lesson02()
|
constructor() public {
}
|
constructor() public {
}
| 11,555
|
91
|
// Hook on `transfer` and call `Withdraw.beforeBalanceChange` function. _to The recipient address. _value The transfer amount. /
|
function transfer(address _to, uint256 _value) public returns (bool) {
/**
* Validates the destination is not 0 address.
*/
require(_to != address(0), "this is illegal address");
require(_value != 0, "illegal transfer value");
/**
* Calls Withdraw contract via Allocator contract.
* Passing through the Allocator contract is due to the historical reason for the old Property contract.
*/
IAllocator(config().allocator()).beforeBalanceChange(
address(this),
msg.sender,
_to
);
/**
* Calls the transfer of ERC20.
*/
_transfer(msg.sender, _to, _value);
return true;
}
|
function transfer(address _to, uint256 _value) public returns (bool) {
/**
* Validates the destination is not 0 address.
*/
require(_to != address(0), "this is illegal address");
require(_value != 0, "illegal transfer value");
/**
* Calls Withdraw contract via Allocator contract.
* Passing through the Allocator contract is due to the historical reason for the old Property contract.
*/
IAllocator(config().allocator()).beforeBalanceChange(
address(this),
msg.sender,
_to
);
/**
* Calls the transfer of ERC20.
*/
_transfer(msg.sender, _to, _value);
return true;
}
| 2,822
|
46
|
// Event that signals that a trash bag has been deposited to the station
|
event Deposited(uint id, address transporter, bool isRecyclable, uint weight, address generator, uint station_id);
|
event Deposited(uint id, address transporter, bool isRecyclable, uint weight, address generator, uint station_id);
| 23,360
|
44
|
// Pause the contract, blocks transfer() and transferFrom()./ Contract MUST NOT be paused to call this, caller must be "owner".
|
function pause() public onlyOwner whenNotPausedUni(msg.sender) {
_paused = true;
emit Paused(msg.sender);
}
|
function pause() public onlyOwner whenNotPausedUni(msg.sender) {
_paused = true;
emit Paused(msg.sender);
}
| 38,975
|
22
|
// auction time determined by callTimestamp
|
auctionStartTimestamp = callTimestamp.add(callTimeLimit).sub(auctionLength);
auctionEndTimestamp = callTimestamp.add(callTimeLimit);
|
auctionStartTimestamp = callTimestamp.add(callTimeLimit).sub(auctionLength);
auctionEndTimestamp = callTimestamp.add(callTimeLimit);
| 19,425
|
46
|
// The magical function! Assigns the tokenId to the caller's wallet address.
|
_safeMint(msg.sender, newItemId);
|
_safeMint(msg.sender, newItemId);
| 14,091
|
20
|
// @custom:security-contact ftrouw@protonmail.com
|
contract IkonDAOVectorCollectible is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, AccessControl, Constants {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
struct Metadata {
string image;
bytes32 category;
}
struct Category {
bytes32 name;
}
mapping(uint256 => Metadata) private tokenMetadata;
Category[] private categoryList;
mapping(bytes32 => bool) private isCategory;
address _DAO; /// maps category to list of tokens that belong to it
event DaoAddressChanged(address newAddress);
event VectorMinted(uint256 tokenId, address receiver);
constructor(address DAO) ERC721("IkonDAO Vector Collectible", "IKDVC") {
_setupRole(ADMIN_ROLE, _msgSender());
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(PAUSER_ROLE, _msgSender());
_setRoleAdmin(PAUSER_ROLE, ADMIN_ROLE);
_setupRole(MINTER_ROLE, _msgSender());
_setRoleAdmin(MINTER_ROLE, ADMIN_ROLE);
_DAO = DAO;
}
function _baseURI() internal pure override returns (string memory) {
return "";
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
/// @dev mints nft to a receiver
/// @param _to nft receiver
function safeMint(address _to) private {
_safeMint(_to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
/// @dev mints vector token for the icon dao
/// @param _imageHash of vector
/// @param _category category under which the vector falls
function safeMintVector(
string calldata _imageHash,
bytes32 _category
) external onlyRole(MINTER_ROLE) whenNotPaused {
uint256 tokenId = _tokenIdCounter.current();
if (tokenId != 0){ // only check after minting of the first token
require(!isImageTaken(_imageHash), NFT_ALREADY_EXISTS);
}
/// metadata
Metadata memory metadata = Metadata({
category: _category,
image: _imageHash
});
if (!isCategory[_category]){
safeMint(_DAO); // mint new nft
Category memory category = Category({
name: _category
}); // create new category
categoryList.push(category);
isCategory[_category] = true; // validate category
tokenMetadata[tokenId] = metadata; // adds metadata to tokenid
} else {
safeMint(_DAO);
tokenMetadata[tokenId] = metadata;
}
emit VectorMinted(tokenId, _DAO);
}
/// @dev returns true image hash of a to-be-minted nft already exists
/// @param imageHash ipfs hash of the image in in bytes32 format
/// @notice this functions acts as an extra check to make sure that only unique vectors (i.e. they must have a unique image hash) can
function isImageTaken(string calldata imageHash) private view returns (bool exists) {
for (uint i = 0; i < _tokenIdCounter.current(); i++){
if (keccak256(abi.encodePacked(tokenMetadata[i].image)) == keccak256(abi.encodePacked(imageHash))){
exists = true;
}
}
}
function getCategories() external view returns (Category[] memory) {
return(categoryList);
}
function getMetadata(uint256 tokenId) public view returns (Metadata memory){
return (tokenMetadata[tokenId]);
}
/// @dev returns dao address
function getDAOAddress() public view returns (address){
return _DAO;
}
/// @dev see _setDaoAddress
function setDAOAddress(address newAddress) external onlyRole(ADMIN_ROLE) whenNotPaused {
_setDaoAddress(newAddress);
emit DaoAddressChanged(newAddress);
}
/// @dev sets new dao address (address to which vectors will belong)
/// @param _new is the new address that will own the vectors
function _setDaoAddress(address _new) private {
_DAO = _new;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) onlyRole(ADMIN_ROLE) whenNotPaused {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
contract IkonDAOVectorCollectible is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, AccessControl, Constants {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
struct Metadata {
string image;
bytes32 category;
}
struct Category {
bytes32 name;
}
mapping(uint256 => Metadata) private tokenMetadata;
Category[] private categoryList;
mapping(bytes32 => bool) private isCategory;
address _DAO; /// maps category to list of tokens that belong to it
event DaoAddressChanged(address newAddress);
event VectorMinted(uint256 tokenId, address receiver);
constructor(address DAO) ERC721("IkonDAO Vector Collectible", "IKDVC") {
_setupRole(ADMIN_ROLE, _msgSender());
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setupRole(PAUSER_ROLE, _msgSender());
_setRoleAdmin(PAUSER_ROLE, ADMIN_ROLE);
_setupRole(MINTER_ROLE, _msgSender());
_setRoleAdmin(MINTER_ROLE, ADMIN_ROLE);
_DAO = DAO;
}
function _baseURI() internal pure override returns (string memory) {
return "";
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
/// @dev mints nft to a receiver
/// @param _to nft receiver
function safeMint(address _to) private {
_safeMint(_to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
/// @dev mints vector token for the icon dao
/// @param _imageHash of vector
/// @param _category category under which the vector falls
function safeMintVector(
string calldata _imageHash,
bytes32 _category
) external onlyRole(MINTER_ROLE) whenNotPaused {
uint256 tokenId = _tokenIdCounter.current();
if (tokenId != 0){ // only check after minting of the first token
require(!isImageTaken(_imageHash), NFT_ALREADY_EXISTS);
}
/// metadata
Metadata memory metadata = Metadata({
category: _category,
image: _imageHash
});
if (!isCategory[_category]){
safeMint(_DAO); // mint new nft
Category memory category = Category({
name: _category
}); // create new category
categoryList.push(category);
isCategory[_category] = true; // validate category
tokenMetadata[tokenId] = metadata; // adds metadata to tokenid
} else {
safeMint(_DAO);
tokenMetadata[tokenId] = metadata;
}
emit VectorMinted(tokenId, _DAO);
}
/// @dev returns true image hash of a to-be-minted nft already exists
/// @param imageHash ipfs hash of the image in in bytes32 format
/// @notice this functions acts as an extra check to make sure that only unique vectors (i.e. they must have a unique image hash) can
function isImageTaken(string calldata imageHash) private view returns (bool exists) {
for (uint i = 0; i < _tokenIdCounter.current(); i++){
if (keccak256(abi.encodePacked(tokenMetadata[i].image)) == keccak256(abi.encodePacked(imageHash))){
exists = true;
}
}
}
function getCategories() external view returns (Category[] memory) {
return(categoryList);
}
function getMetadata(uint256 tokenId) public view returns (Metadata memory){
return (tokenMetadata[tokenId]);
}
/// @dev returns dao address
function getDAOAddress() public view returns (address){
return _DAO;
}
/// @dev see _setDaoAddress
function setDAOAddress(address newAddress) external onlyRole(ADMIN_ROLE) whenNotPaused {
_setDaoAddress(newAddress);
emit DaoAddressChanged(newAddress);
}
/// @dev sets new dao address (address to which vectors will belong)
/// @param _new is the new address that will own the vectors
function _setDaoAddress(address _new) private {
_DAO = _new;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) onlyRole(ADMIN_ROLE) whenNotPaused {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| 21,826
|
45
|
// The `burnFromLockedPrps` call will fail, if not enough PRPS can be burned.
|
lockedPrpsToBurn += fuelBurn.amount;
|
lockedPrpsToBurn += fuelBurn.amount;
| 5,132
|
88
|
// Returns true if auto swap and liquify feature is enabled. /
|
function autoSwapAndLiquifyEnabled() public view virtual returns (bool) {
return _autoSwapAndLiquifyEnabled;
}
|
function autoSwapAndLiquifyEnabled() public view virtual returns (bool) {
return _autoSwapAndLiquifyEnabled;
}
| 33,472
|
12
|
// 代表计划
|
mapping(address => bool) internal ambassadors_; // 代表集合
uint256 constant internal ambassadorMaxPurchase_ = 1 ether; // 最大购买
uint256 constant internal ambassadorQuota_ = 20 ether; // 购买限额
|
mapping(address => bool) internal ambassadors_; // 代表集合
uint256 constant internal ambassadorMaxPurchase_ = 1 ether; // 最大购买
uint256 constant internal ambassadorQuota_ = 20 ether; // 购买限额
| 60,206
|
142
|
// now decrease the length
|
_cardsOf[fromAddress].length--;
|
_cardsOf[fromAddress].length--;
| 50,814
|
101
|
// The Ownable constructor sets the original `owner` of the contract to the senderaccount. /
|
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
|
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
| 6,447
|
35
|
// This function pays both the token on sale owner and it's referrer 1 UnitThis function is triggered 2 twice per exchange totaling to 3 unit cost
|
App storage a = AppData();
|
App storage a = AppData();
| 14,166
|
1
|
// The price of each NFT
|
uint256 public salePrice;
|
uint256 public salePrice;
| 15,594
|
33
|
// Generate a unique id for a game/secret hosts password for this game/move move played by host/puzzle combines the address of the host, / the contract, the secret and move provided by the host/ this generates a unique id for the game/ return gameId a hash generated from the input paramaters
|
function generateGameId(address host, bytes32 secret, Moves move)
public
validMove(move)
view
returns (bytes32 gameId)
|
function generateGameId(address host, bytes32 secret, Moves move)
public
validMove(move)
view
returns (bytes32 gameId)
| 26,156
|
56
|
// unstaking fee 0.00 percent
|
uint public constant unstakingFeeRate = 0;
|
uint public constant unstakingFeeRate = 0;
| 29,540
|
111
|
// Calculates and returns`_tree`'s current root given array of zerohashes _zeroes Array of zero hashesreturn _current Calculated root of `_tree` /
|
{
uint256 _index = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _tree.branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _zeroes[i]));
}
}
}
|
{
uint256 _index = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _tree.branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _zeroes[i]));
}
}
}
| 50,710
|
580
|
// 291
|
entry "oftused" : ENG_ADJECTIVE
|
entry "oftused" : ENG_ADJECTIVE
| 16,903
|
267
|
// For emergency /
|
function transferFromForAdmin(address from, address to, uint256 tokenId) external virtual onlyOwner {
require(balanceOf(to) == 0, "Receiver already has a badge");
_transfer(from, to, tokenId);
}
|
function transferFromForAdmin(address from, address to, uint256 tokenId) external virtual onlyOwner {
require(balanceOf(to) == 0, "Receiver already has a badge");
_transfer(from, to, tokenId);
}
| 57,258
|
7
|
// _secondsUntilInactive The seconds that a user does not update will be seen as inactive. _onlyRewardActiveReferrers The flag to enable not paying to inactive uplines. _levelRate The bonus rate for each level. The max depth is 3. _refereeBonusRateMap The bonus rate mapping to each referree amount. The max depth is 3.The map should be pass as [<lower amount>, <rate>, ....]. For example, you should pass [1, 2500, 5, 5000, 10, 10000].25% 50% 100%| ----- | ----- |-----> 1ppl5ppl10pplrefereeBonusRateMap's lower amount should be ascending /
|
function _setReferral(
uint24 _secondsUntilInactive,
bool _onlyRewardActiveReferrers,
uint16[3] calldata _levelRate,
uint16[6] calldata _refereeBonusRateMap
|
function _setReferral(
uint24 _secondsUntilInactive,
bool _onlyRewardActiveReferrers,
uint16[3] calldata _levelRate,
uint16[6] calldata _refereeBonusRateMap
| 8,200
|
74
|
// This return state of initialSupply function:'false' means that initialSupply is not done yet.'true' means that it's locked forever. /
|
function isInitialSupplyFinished () public view returns (bool) {
return InitialSupplyFinished;
}
|
function isInitialSupplyFinished () public view returns (bool) {
return InitialSupplyFinished;
}
| 44,521
|
148
|
// solhint-disable func-order
|
contract DistributionToken is ERC20, ERC20Mintable {
using SafeMath for uint256;
uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60;
event DistributionCreated(uint256 amount, uint256 totalSupply);
event DistributionsClaimed(address account, uint256 amount, uint256 fromDistribution, uint256 toDistribution);
event DistributionAccumulatorIncreased(uint256 amount);
struct Distribution {
uint256 amount; // Amount of tokens being distributed during the event
uint256 totalSupply; // Total supply before distribution
}
Distribution[] public distributions; // Array of all distributions
mapping(address => uint256) public nextDistributions; // Map account to first distribution not yet processed
uint256 public nextDistributionTimestamp; //Timestamp when next distribuition should be fired regardles of accumulated tokens
uint256 public distributionAccumulator; //Tokens accumulated for next distribution
function distribute(uint256 amount) external onlyMinter {
distributionAccumulator = distributionAccumulator.add(amount);
emit DistributionAccumulatorIncreased(amount);
_createDistributionIfReady();
}
function createDistribution() external onlyMinter {
require(distributionAccumulator > 0, "DistributionToken: nothing to distribute");
_createDistribution();
}
function claimDistributions(address account) external returns(uint256) {
_createDistributionIfReady();
uint256 amount = _updateUserBalance(account, distributions.length);
if (amount > 0) userBalanceChanged(account);
return amount;
}
/**
* @notice Claims distributions and allows to specify how many distributions to process.
* This allows limit gas usage.
* One can do this for others
*/
function claimDistributions(address account, uint256 toDistribution) external returns(uint256) {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
require(nextDistributions[account] < toDistribution, "DistributionToken: no distributions to claim");
uint256 amount = _updateUserBalance(account, toDistribution);
if (amount > 0) userBalanceChanged(account);
return amount;
}
function claimDistributions(address[] calldata accounts) external {
_createDistributionIfReady();
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], distributions.length);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
function claimDistributions(address[] calldata accounts, uint256 toDistribution) external {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], toDistribution);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
/**
* @notice Full balance of account includes:
* - balance of tokens account holds himself (0 for addresses of locking contracts)
* - balance of tokens locked in contracts
* - tokens not yet claimed from distributions
*/
function fullBalanceOf(address account) public view returns(uint256){
if (account == address(this)) return 0; //Token itself only holds tokens for others
uint256 distributionBalance = distributionBalanceOf(account);
uint256 unclaimed = calculateClaimAmount(account);
return distributionBalance.add(unclaimed);
}
/**
* @notice How many tokens are not yet claimed from distributions
* @param account Account to check
* @return Amount of tokens available to claim
*/
function calculateUnclaimedDistributions(address account) public view returns(uint256) {
return calculateClaimAmount(account);
}
/**
* @notice Calculates amount of tokens distributed to inital amount between startDistribution and nextDistribution
* @param fromDistribution index of first Distribution to start calculations
* @param toDistribution index of distribuition next to the last processed
* @param initialBalance amount of tokens before startDistribution
* @return amount of tokens distributed
*/
function calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) public view returns(uint256) {
require(fromDistribution < toDistribution, "DistributionToken: startDistribution is too high");
require(toDistribution <= distributions.length, "DistributionToken: nextDistribution is too high");
return _calculateDistributedAmount(fromDistribution, toDistribution, initialBalance);
}
function nextDistribution() public view returns(uint256){
return distributions.length;
}
/**
* @notice Balance of account, which is counted for distributions
* It only represents already distributed balance.
* @dev This function should be overloaded to include balance of tokens stored in proposals
*/
function distributionBalanceOf(address account) public view returns(uint256) {
return balanceOf(account);
}
/**
* @notice Total supply which is counted for distributions
* It only represents already distributed tokens
* @dev This function should be overloaded to exclude tokens locked in loans
*/
function distributionTotalSupply() public view returns(uint256){
return totalSupply();
}
// Override functions that change user balance
function _transfer(address sender, address recipient, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(sender);
_updateUserBalance(recipient);
super._transfer(sender, recipient, amount);
userBalanceChanged(sender);
userBalanceChanged(recipient);
}
function _mint(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._mint(account, amount);
userBalanceChanged(account);
}
function _burn(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._burn(account, amount);
userBalanceChanged(account);
}
function _updateUserBalance(address account) internal returns(uint256) {
return _updateUserBalance(account, distributions.length);
}
function _updateUserBalance(address account, uint256 toDistribution) internal returns(uint256) {
uint256 fromDistribution = nextDistributions[account];
if (fromDistribution >= toDistribution) return 0;
uint256 distributionAmount = calculateClaimAmount(account, toDistribution);
nextDistributions[account] = toDistribution;
if (distributionAmount == 0) return 0;
super._transfer(address(this), account, distributionAmount);
emit DistributionsClaimed(account, distributionAmount, fromDistribution, toDistribution);
return distributionAmount;
}
function _createDistributionIfReady() internal {
if (!isReadyForDistribution()) return;
_createDistribution();
}
function _createDistribution() internal {
uint256 currentTotalSupply = distributionTotalSupply();
distributions.push(Distribution({
amount:distributionAccumulator,
totalSupply: currentTotalSupply
}));
super._mint(address(this), distributionAccumulator); //Use super because we overloaded _mint in this contract and need old behaviour
emit DistributionCreated(distributionAccumulator, currentTotalSupply);
// Clear data for next distribution
distributionAccumulator = 0;
nextDistributionTimestamp = now.sub(now % DISTRIBUTION_AGGREGATION_PERIOD).add(DISTRIBUTION_AGGREGATION_PERIOD);
}
/**
* @dev This is a placeholder, which may be overrided to notify other contracts of PTK balance change
*/
function userBalanceChanged(address /*account*/) internal {
}
/**
* @notice Calculates amount of account's tokens to be claimed from distributions
*/
function calculateClaimAmount(address account) internal view returns(uint256) {
if (nextDistributions[account] >= distributions.length) return 0;
return calculateClaimAmount(account, distributions.length);
}
function calculateClaimAmount(address account, uint256 toDistribution) internal view returns(uint256) {
assert(toDistribution <= distributions.length);
return _calculateDistributedAmount(nextDistributions[account], toDistribution, distributionBalanceOf(account));
}
function _calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) internal view returns(uint256) {
uint256 next = fromDistribution;
uint256 balance = initialBalance;
if (initialBalance == 0) return 0;
while (next < toDistribution) {
uint256 da = balance.mul(distributions[next].amount).div(distributions[next].totalSupply);
balance = balance.add(da);
next++;
}
return balance.sub(initialBalance);
}
/**
* @dev Calculates if conditions for creating new distribution are met
*/
function isReadyForDistribution() internal view returns(bool) {
return (distributionAccumulator > 0) && (now >= nextDistributionTimestamp);
}
}
|
contract DistributionToken is ERC20, ERC20Mintable {
using SafeMath for uint256;
uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60;
event DistributionCreated(uint256 amount, uint256 totalSupply);
event DistributionsClaimed(address account, uint256 amount, uint256 fromDistribution, uint256 toDistribution);
event DistributionAccumulatorIncreased(uint256 amount);
struct Distribution {
uint256 amount; // Amount of tokens being distributed during the event
uint256 totalSupply; // Total supply before distribution
}
Distribution[] public distributions; // Array of all distributions
mapping(address => uint256) public nextDistributions; // Map account to first distribution not yet processed
uint256 public nextDistributionTimestamp; //Timestamp when next distribuition should be fired regardles of accumulated tokens
uint256 public distributionAccumulator; //Tokens accumulated for next distribution
function distribute(uint256 amount) external onlyMinter {
distributionAccumulator = distributionAccumulator.add(amount);
emit DistributionAccumulatorIncreased(amount);
_createDistributionIfReady();
}
function createDistribution() external onlyMinter {
require(distributionAccumulator > 0, "DistributionToken: nothing to distribute");
_createDistribution();
}
function claimDistributions(address account) external returns(uint256) {
_createDistributionIfReady();
uint256 amount = _updateUserBalance(account, distributions.length);
if (amount > 0) userBalanceChanged(account);
return amount;
}
/**
* @notice Claims distributions and allows to specify how many distributions to process.
* This allows limit gas usage.
* One can do this for others
*/
function claimDistributions(address account, uint256 toDistribution) external returns(uint256) {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
require(nextDistributions[account] < toDistribution, "DistributionToken: no distributions to claim");
uint256 amount = _updateUserBalance(account, toDistribution);
if (amount > 0) userBalanceChanged(account);
return amount;
}
function claimDistributions(address[] calldata accounts) external {
_createDistributionIfReady();
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], distributions.length);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
function claimDistributions(address[] calldata accounts, uint256 toDistribution) external {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], toDistribution);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
/**
* @notice Full balance of account includes:
* - balance of tokens account holds himself (0 for addresses of locking contracts)
* - balance of tokens locked in contracts
* - tokens not yet claimed from distributions
*/
function fullBalanceOf(address account) public view returns(uint256){
if (account == address(this)) return 0; //Token itself only holds tokens for others
uint256 distributionBalance = distributionBalanceOf(account);
uint256 unclaimed = calculateClaimAmount(account);
return distributionBalance.add(unclaimed);
}
/**
* @notice How many tokens are not yet claimed from distributions
* @param account Account to check
* @return Amount of tokens available to claim
*/
function calculateUnclaimedDistributions(address account) public view returns(uint256) {
return calculateClaimAmount(account);
}
/**
* @notice Calculates amount of tokens distributed to inital amount between startDistribution and nextDistribution
* @param fromDistribution index of first Distribution to start calculations
* @param toDistribution index of distribuition next to the last processed
* @param initialBalance amount of tokens before startDistribution
* @return amount of tokens distributed
*/
function calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) public view returns(uint256) {
require(fromDistribution < toDistribution, "DistributionToken: startDistribution is too high");
require(toDistribution <= distributions.length, "DistributionToken: nextDistribution is too high");
return _calculateDistributedAmount(fromDistribution, toDistribution, initialBalance);
}
function nextDistribution() public view returns(uint256){
return distributions.length;
}
/**
* @notice Balance of account, which is counted for distributions
* It only represents already distributed balance.
* @dev This function should be overloaded to include balance of tokens stored in proposals
*/
function distributionBalanceOf(address account) public view returns(uint256) {
return balanceOf(account);
}
/**
* @notice Total supply which is counted for distributions
* It only represents already distributed tokens
* @dev This function should be overloaded to exclude tokens locked in loans
*/
function distributionTotalSupply() public view returns(uint256){
return totalSupply();
}
// Override functions that change user balance
function _transfer(address sender, address recipient, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(sender);
_updateUserBalance(recipient);
super._transfer(sender, recipient, amount);
userBalanceChanged(sender);
userBalanceChanged(recipient);
}
function _mint(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._mint(account, amount);
userBalanceChanged(account);
}
function _burn(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._burn(account, amount);
userBalanceChanged(account);
}
function _updateUserBalance(address account) internal returns(uint256) {
return _updateUserBalance(account, distributions.length);
}
function _updateUserBalance(address account, uint256 toDistribution) internal returns(uint256) {
uint256 fromDistribution = nextDistributions[account];
if (fromDistribution >= toDistribution) return 0;
uint256 distributionAmount = calculateClaimAmount(account, toDistribution);
nextDistributions[account] = toDistribution;
if (distributionAmount == 0) return 0;
super._transfer(address(this), account, distributionAmount);
emit DistributionsClaimed(account, distributionAmount, fromDistribution, toDistribution);
return distributionAmount;
}
function _createDistributionIfReady() internal {
if (!isReadyForDistribution()) return;
_createDistribution();
}
function _createDistribution() internal {
uint256 currentTotalSupply = distributionTotalSupply();
distributions.push(Distribution({
amount:distributionAccumulator,
totalSupply: currentTotalSupply
}));
super._mint(address(this), distributionAccumulator); //Use super because we overloaded _mint in this contract and need old behaviour
emit DistributionCreated(distributionAccumulator, currentTotalSupply);
// Clear data for next distribution
distributionAccumulator = 0;
nextDistributionTimestamp = now.sub(now % DISTRIBUTION_AGGREGATION_PERIOD).add(DISTRIBUTION_AGGREGATION_PERIOD);
}
/**
* @dev This is a placeholder, which may be overrided to notify other contracts of PTK balance change
*/
function userBalanceChanged(address /*account*/) internal {
}
/**
* @notice Calculates amount of account's tokens to be claimed from distributions
*/
function calculateClaimAmount(address account) internal view returns(uint256) {
if (nextDistributions[account] >= distributions.length) return 0;
return calculateClaimAmount(account, distributions.length);
}
function calculateClaimAmount(address account, uint256 toDistribution) internal view returns(uint256) {
assert(toDistribution <= distributions.length);
return _calculateDistributedAmount(nextDistributions[account], toDistribution, distributionBalanceOf(account));
}
function _calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) internal view returns(uint256) {
uint256 next = fromDistribution;
uint256 balance = initialBalance;
if (initialBalance == 0) return 0;
while (next < toDistribution) {
uint256 da = balance.mul(distributions[next].amount).div(distributions[next].totalSupply);
balance = balance.add(da);
next++;
}
return balance.sub(initialBalance);
}
/**
* @dev Calculates if conditions for creating new distribution are met
*/
function isReadyForDistribution() internal view returns(bool) {
return (distributionAccumulator > 0) && (now >= nextDistributionTimestamp);
}
}
| 45,535
|
6
|
// https:github.com/makerdao/dss/blob/master/src/spot.sol
|
interface SpotAbstract {
function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY664(address) external; //inject NONSTANDARD NAMING
function DENY283(address) external; //inject NONSTANDARD NAMING
function ILKS778(bytes32) external view returns (address, uint256); //inject NONSTANDARD NAMING
function VAT142() external view returns (address); //inject NONSTANDARD NAMING
function PAR826() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function POKE311(bytes32) external; //inject NONSTANDARD NAMING
function CAGE3() external; //inject NONSTANDARD NAMING
}
|
interface SpotAbstract {
function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY664(address) external; //inject NONSTANDARD NAMING
function DENY283(address) external; //inject NONSTANDARD NAMING
function ILKS778(bytes32) external view returns (address, uint256); //inject NONSTANDARD NAMING
function VAT142() external view returns (address); //inject NONSTANDARD NAMING
function PAR826() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function POKE311(bytes32) external; //inject NONSTANDARD NAMING
function CAGE3() external; //inject NONSTANDARD NAMING
}
| 30,396
|
148
|
// Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for alltransfers. /
|
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
|
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
| 1,438
|
476
|
// Burn tokens from account
|
_transferTokensBurn(_account, amount);
|
_transferTokensBurn(_account, amount);
| 34,992
|
65
|
// payable function that allow token purchases beneficiary Address of the purchaser /
|
function buyTokens(address beneficiary)
public
whenNotPaused
whitelisted(beneficiary)
payable
|
function buyTokens(address beneficiary)
public
whenNotPaused
whitelisted(beneficiary)
payable
| 41,764
|
17
|
// requires the sender to be one of the contract owners
|
modifier onlyOwner { require(isOwner[msg.sender], "invalid sender; must be owner"); _; }
/// @notice list all accounts with an owner access
function getOwners() public view returns (address[] memory) { return owners; }
/// @notice authorize an `account` with owner access
function addOwner(address owner) external onlyOwner { addOwner_(owner); }
function addOwner_(address owner) private validAddress(owner) {
if (!isOwner[owner]) {
isOwner[owner] = true;
owners.push(owner);
emit OwnerAdded(owner);
}
}
|
modifier onlyOwner { require(isOwner[msg.sender], "invalid sender; must be owner"); _; }
/// @notice list all accounts with an owner access
function getOwners() public view returns (address[] memory) { return owners; }
/// @notice authorize an `account` with owner access
function addOwner(address owner) external onlyOwner { addOwner_(owner); }
function addOwner_(address owner) private validAddress(owner) {
if (!isOwner[owner]) {
isOwner[owner] = true;
owners.push(owner);
emit OwnerAdded(owner);
}
}
| 3,505
|
17
|
// Create record of userDetails
|
userDetails memory newUserDetails = userDetails({
userFullName : _userFullName,
userAge : _userAge,
userLevel : _userLevel,
userAadharNumber : _userAadharNumber,
userPayId : _userPayId,
userPincode : _userPincode,
userOneChangeId : _newUserOneChangeId,
userStatus : true,
additionalInformation : ""
|
userDetails memory newUserDetails = userDetails({
userFullName : _userFullName,
userAge : _userAge,
userLevel : _userLevel,
userAadharNumber : _userAadharNumber,
userPayId : _userPayId,
userPincode : _userPincode,
userOneChangeId : _newUserOneChangeId,
userStatus : true,
additionalInformation : ""
| 22,357
|
26
|
// Set Uint value in InstaMemory Contract./
|
function setUint(uint setId, uint val) internal {
if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val);
}
|
function setUint(uint setId, uint val) internal {
if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val);
}
| 738
|
38
|
// don't allow invalid picks.
|
for (uint8 i = 0; i < 4; i++) {
if (picks[i] & PICK_MASK != picks[i]) {
throw;
}
|
for (uint8 i = 0; i < 4; i++) {
if (picks[i] & PICK_MASK != picks[i]) {
throw;
}
| 11,428
|
309
|
// Skip iterating over `newReceivers` if no new dripping is started
|
uint256 newIdx = newEndTime > _currTimestamp() ? 0 : newReceivers.length;
while (true) {
|
uint256 newIdx = newEndTime > _currTimestamp() ? 0 : newReceivers.length;
while (true) {
| 14,778
|
52
|
// Calculate with internal swap pool.
|
uint8 tokenIndexIn = getTokenIndexFromStableSwapPool(_key, _asset);
uint8 tokenIndexOut = getTokenIndexFromStableSwapPool(_key, adopted);
return (ipool.calculateSwap(tokenIndexIn, tokenIndexOut, _amount), adopted);
|
uint8 tokenIndexIn = getTokenIndexFromStableSwapPool(_key, _asset);
uint8 tokenIndexOut = getTokenIndexFromStableSwapPool(_key, adopted);
return (ipool.calculateSwap(tokenIndexIn, tokenIndexOut, _amount), adopted);
| 30,155
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.