comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
/**
* Accepts money deposit and makes record
* minimum deposit is MINIMUM_DEPOSIT
* @param beneficiar - the address to receive Tokens
* @param countryCode - 3-digit country code
* @dev if `msg.value < MINIMUM_DEPOSIT` throws
*/
|
function deposit (address beneficiar, uint16 countryCode) payable {
require(msg.value >= MINIMUM_DEPOSIT);
require(state == State.Sale || state == State.Presale);
/* this should end any finished period before starting any operations */
tick();
/* check if have enough tokens for the current period
* if not, the call fails until tokens are deposited to the contract
*/
require(isActive());
uint256 tokensBought = msg.value / getTokenPrice();
if(periods[currentPeriod].tokensSold + tokensBought >= tokensForPeriod(currentPeriod)) {
tokensBought = tokensForPeriod(currentPeriod) - periods[currentPeriod].tokensSold;
}
uint256 moneySpent = getTokenPrice() * tokensBought;
investmentsByCountries[countryCode] += moneySpent;
if(tokensBought > 0) {
assert(moneySpent <= msg.value);
/* return the rest */
if(msg.value > moneySpent) {
msg.sender.transfer(msg.value - moneySpent);
}
periods[currentPeriod].tokensSold += tokensBought;
unclaimedTokensForInvestor[beneficiar] += tokensBought;
totalUnclaimedTokens += tokensBought;
totalTokensSold += tokensBought;
Deposited(msg.sender, moneySpent, tokensBought);
}
/* if all tokens are sold, get to the next period */
tick();
}
|
0.4.15
|
/**
* Set verification of a users challenge
* @param tokenId - the tokenId of the challenge
* @param completed - true if the challenge has been verified
* @return success - true if successful
*/
|
function setVerify(uint256 tokenId, bool completed)
public
returns (bool success)
{
require(!verificationPaused, "Verification is paused");
require(
tokenIdVerificationComplete[tokenId] == false,
"Token has already been verified"
);
require(
tokenIdToAccountabilityPartner[tokenId] == msg.sender,
"Only the accountability partner can verify"
);
tokenIdVerificationComplete[tokenId] = true;
tokenIdVerificationValue[tokenId] = completed;
emit Verified(
tokenId,
completed,
ownerOf(tokenId),
accountabilityPartnerOf(tokenId)
);
return true;
}
|
0.8.4
|
/**
* Remove the verification status from the challenge
* @param tokenId - the tokenId of the challenge
* @return success - true if successful
*/
|
function unverify(uint256 tokenId) public returns (bool success) {
require(!verificationPaused, "Verification is paused");
require(
tokenIdVerificationComplete[tokenId] == true,
"Token has not been verified"
);
require(
tokenIdToAccountabilityPartner[tokenId] == msg.sender,
"Only the accountability partner can unverify"
);
tokenIdVerificationComplete[tokenId] = false;
tokenIdVerificationValue[tokenId] = false;
emit Unverified(
tokenId,
ownerOf(tokenId),
accountabilityPartnerOf(tokenId)
);
return true;
}
|
0.8.4
|
/**
* Withdraw the balance of the contract
* @dev owner only
* @param _to - the address to send the balance to
* @param _amount - the amount to send
* @return sent - true if successful
* @return data - data from the call
*/
|
function withdraw(address payable _to, uint256 _amount)
external
onlyOwner
returns (bool sent, bytes memory data)
{
require(_amount < address(this).balance, "Not enough balance");
require(_amount > 0, "Amount must be greater than 0");
(sent, data) = _to.call{value: _amount}("");
return (sent, data);
}
|
0.8.4
|
/**
* Get the URI of a token
* @param tokenId - the tokenId of the token
* @return tokenURI - the uri of the token
*/
|
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = tokenIdToIpfsHash[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, return the base because this shouldn't happen
return string(abi.encodePacked(base));
}
|
0.8.4
|
/**
* Holder can withdraw the ETH when price >= box.openPrice or now >= box.openTime.
* After breaking the box, the box will be burned.
*/
|
function breakBox(uint _boxId) public {
require(_isApprovedOrOwner(_msgSender(), _boxId), "ERC721: transfer caller is not owner nor approved");
uint ether_price_now = getEthPrice();
MoonBox storage box = moonBoxs[_boxId];
require(box.etherNumber > 0, "This box has been opened");
if(box.openPrice <= ether_price_now || box.openTime <= now) {
super._burn(_boxId);
msg.sender.transfer(box.etherNumber);
emit BreakBox(_boxId, now);
} else {
revert("The break condition is not yet satisfied.");
}
}
|
0.5.12
|
/**
* Holder can withdraw the ETH when price >= box.openPrice or now >= box.openTime.
* After open the box, you still have the box.
* Developers will receive a fee of.1%.
*/
|
function openBox(uint _boxId) public {
require(_isApprovedOrOwner(_msgSender(), _boxId), "ERC721: transfer caller is not owner nor approved");
uint ether_price_now = getEthPrice();
MoonBox storage box = moonBoxs[_boxId];
require(box.etherNumber > 0, "This box has been opened");
if(box.openPrice <= ether_price_now || box.openTime <= now) {
uint fee = box.etherNumber / tipRatio;
uint payout = box.etherNumber.sub(fee);
box.etherNumber = 0;
msg.sender.transfer(payout);
owner.transfer(fee);
emit OpenBox(_boxId, now);
} else {
revert("The open condition is not yet satisfied.");
}
}
|
0.5.12
|
/**
* @dev Gets the list of token IDs of the requested owner.
* @param _owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
|
function getMoonBoxsByOwner(address _owner) external view returns(uint[] memory) {
uint boxNum = super.balanceOf(_owner);
uint[] memory result = new uint[](boxNum);
uint counter = 0;
for (uint i = 0; i < moonBoxs.length; i++) {
if (super._exists(i) && super._isApprovedOrOwner(_owner, i)) {
result[counter] = i;
counter++;
}
}
return result;
}
|
0.5.12
|
/**
* when developer changed the address of the oracle.
* Users have one week to opt out safely.
*/
|
function quit(uint _boxId) external {
require(_isApprovedOrOwner(_msgSender(), _boxId), "ERC721: transfer caller is not owner nor approved");
MoonBox storage box = moonBoxs[_boxId];
require(box.etherNumber > 0, "This box has been opened");
if(now < new_uniswap_address_effective_time) {
super._burn(_boxId);
msg.sender.transfer(box.etherNumber);
emit Quit(_boxId, now);
} else {
revert("The quit condition is not yet satisfied.");
}
}
|
0.5.12
|
///@dev Deposits alTokens into the transmuter
///
///@param amount the amount of alTokens to stake
|
function stake(uint256 amount)
public
noContractAllowed()
ensureUserActionDelay()
runPhasedDistribution()
updateAccount(msg.sender)
checkIfNewUser()
{
require(!pause, "emergency pause enabled");
// requires approval of AlToken first
address sender = msg.sender;
//require tokens transferred in;
IERC20Burnable(alToken).safeTransferFrom(sender, address(this), amount);
totalSupplyAltokens = totalSupplyAltokens.add(amount);
depositedAlTokens[sender] = depositedAlTokens[sender].add(amount);
emit AlUsdStaked(sender, amount);
}
|
0.6.12
|
/// @dev Sets the keeper list
///
/// This function reverts if the caller is not governance
///
/// @param _keepers the accounts to set states for.
/// @param _states the accounts states.
|
function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() {
uint256 n = _keepers.length;
for(uint256 i = 0; i < n; i++) {
keepers[_keepers[i]] = _states[i];
}
emit KeepersSet(_keepers, _states);
}
|
0.6.12
|
/// @dev Updates the active vault.
///
/// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts
/// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized.
///
/// @param _adapter the adapter for the new active vault.
|
function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal {
require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0.");
require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch.");
require(!adapters[_adapter], "Adapter already in use");
adapters[_adapter] = true;
_vaults.push(VaultWithIndirection.Data({
adapter: _adapter,
totalDeposited: 0
}));
emit ActiveVaultUpdated(_adapter);
}
|
0.6.12
|
/// @dev Recalls funds from active vault if less than amt exist locally
///
/// @param amt amount of funds that need to exist locally to fulfill pending request
|
function ensureSufficientFundsExistLocally(uint256 amt) internal {
uint256 currentBal = IERC20Burnable(token).balanceOf(address(this));
if (currentBal < amt) {
uint256 diff = amt - currentBal;
// get enough funds from active vault to replenish local holdings & fulfill claim request
_recallExcessFundsFromActiveVault(plantableThreshold.add(diff));
}
}
|
0.6.12
|
/// @dev Plants or recalls funds from the active vault
///
/// This function plants excess funds in an external vault, or recalls them from the external vault
/// Should only be called as part of distribute()
|
function _plantOrRecallExcessFunds() internal {
// check if the transmuter holds more funds than plantableThreshold
uint256 bal = IERC20Burnable(token).balanceOf(address(this));
uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100);
if (bal > plantableThreshold.add(marginVal)) {
uint256 plantAmt = bal - plantableThreshold;
// if total funds above threshold, send funds to vault
VaultWithIndirection.Data storage _activeVault = _vaults.last();
_activeVault.deposit(plantAmt);
} else if (bal < plantableThreshold.sub(marginVal)) {
// if total funds below threshold, recall funds from vault
// first check that there are enough funds in vault
uint256 harvestAmt = plantableThreshold - bal;
_recallExcessFundsFromActiveVault(harvestAmt);
}
}
|
0.6.12
|
/// @dev Recalls up to the harvestAmt from the active vault
///
/// This function will recall less than harvestAmt if only less is available
///
/// @param _recallAmt the amount to harvest from the active vault
|
function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal {
VaultWithIndirection.Data storage _activeVault = _vaults.last();
uint256 activeVaultVal = _activeVault.totalValue();
if (activeVaultVal < _recallAmt) {
_recallAmt = activeVaultVal;
}
if (_recallAmt > 0) {
_recallFundsFromActiveVault(_recallAmt);
}
}
|
0.6.12
|
/// @dev Sets the rewards contract.
///
/// This function reverts if the new rewards contract is the zero address or the caller is not the current governance.
///
/// @param _rewards the new rewards contract.
|
function setRewards(address _rewards) external onlyGov() {
// Check that the rewards address is not the zero address. Setting the rewards to the zero address would break
// transfers to the address because of `safeTransfer` checks.
require(_rewards != ZERO_ADDRESS, "Transmuter: rewards address cannot be 0x0.");
rewards = _rewards;
emit RewardsUpdated(_rewards);
}
|
0.6.12
|
/// @dev Migrates transmuter funds to a new transmuter
///
/// @param migrateTo address of the new transmuter
|
function migrateFunds(address migrateTo) external onlyGov() {
require(migrateTo != address(0), "cannot migrate to 0x0");
require(pause, "migrate: set emergency exit first");
// leave enough funds to service any pending transmutations
uint256 totalFunds = IERC20Burnable(token).balanceOf(address(this));
uint256 migratableFunds = totalFunds.sub(totalSupplyAltokens, "not enough funds to service stakes");
IERC20Burnable(token).approve(migrateTo, migratableFunds);
ITransmuter(migrateTo).distribute(address(this), migratableFunds);
emit MigrationComplete(migrateTo, migratableFunds);
}
|
0.6.12
|
/* acceptor mint one baby, left another baby for proposer to claim */
|
function breed(
MatingRequest calldata matingRequest,
uint16 acceptorTokenId,
bytes calldata sig
) external callerIsUser isAtSalePhase(SalePhase.Breed) {
validateMatingRequest(matingRequest, sig);
uint16 punkId;
uint16 baycId;
address punkOwnerAddress;
address baycOwnerAddress;
if (matingRequest.isProposerPunk) {
punkId = matingRequest.proposerTokenId;
punkOwnerAddress = matingRequest.proposerAddress;
baycId = acceptorTokenId;
baycOwnerAddress = msg.sender;
} else {
punkId = acceptorTokenId;
punkOwnerAddress = msg.sender;
baycId = matingRequest.proposerTokenId;
baycOwnerAddress = matingRequest.proposerAddress;
}
require(!punkBred(punkId), 'Punk already bred a baby.');
require(!baycBred(baycId), 'Bayc already bred a baby.');
bred.set(punkId2Index(punkId));
bred.set(baycId2Index(baycId));
// check ownership
verifyPunkOwnership(punkId, punkOwnerAddress);
verifyBaycOwnership(baycId, baycOwnerAddress);
uint16 babyTokenId = uint16(_currentIndex);
babyParents[babyTokenId] = Parents(
punkId,
baycId,
matingRequest.isProposerPunk,
false,
true
);
emit Breed(
matingRequest.proposerTokenId,
matingRequest.isProposerPunk,
acceptorTokenId,
msg.sender,
babyTokenId
);
// mint baby token for acceptor, proposer should claim the twin baby later.
_mint(msg.sender, 1, '', false);
}
|
0.8.7
|
/* For proposer to claim the baby. */
|
function claimBaby(uint16 siblingId)
external
callerIsUser
isAtSalePhase(SalePhase.Breed)
{
Parents storage parentsInfo = babyParents[siblingId];
require(parentsInfo.hasParents, 'No baby to be claimed.');
if (parentsInfo.isProposerPunk) {
verifyPunkOwnership(parentsInfo.punkTokenId, msg.sender);
} else {
verifyBaycOwnership(parentsInfo.baycTokenId, msg.sender);
}
require(!parentsInfo.proposerClaimed, 'Baby already claimed.');
parentsInfo.proposerClaimed = true;
uint16 babyTokenId = uint16(_currentIndex);
babyParents[babyTokenId] = parentsInfo;
emit Claim(babyTokenId, siblingId, msg.sender);
_mint(msg.sender, 1, '', false);
}
|
0.8.7
|
/**
* @notice Buy a license
* @dev Requires value to be equal to the price of the license.
* The _owner must not already own a license.
*/
|
function _buyFrom(address _licenseOwner) internal returns(uint) {
require(licenseDetails[_licenseOwner].creationTime == 0, "License already bought");
licenseDetails[_licenseOwner] = LicenseDetails({
price: price,
creationTime: block.timestamp
});
uint idx = licenseOwners.push(_licenseOwner);
idxLicenseOwners[_licenseOwner] = idx;
emit Bought(_licenseOwner, price);
require(_safeTransferFrom(token, _licenseOwner, burnAddress, price), "Unsuccessful token transfer");
return idx;
}
|
0.5.10
|
/**
* @notice Support for "approveAndCall". Callable only by `token()`.
* @param _from Who approved.
* @param _amount Amount being approved, need to be equal `price()`.
* @param _token Token being approved, need to be equal `token()`.
* @param _data Abi encoded data with selector of `buy(and)`.
*/
|
function receiveApproval(address _from, uint256 _amount, address _token, bytes memory _data) public {
require(_amount == price, "Wrong value");
require(_token == address(token), "Wrong token");
require(_token == address(msg.sender), "Wrong call");
require(_data.length == 4, "Wrong data length");
require(_abiDecodeBuy(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()"))
_buyFrom(_from);
}
|
0.5.10
|
/**
* @notice Change acceptAny parameter for arbitrator
* @param _acceptAny indicates does arbitrator allow to accept any seller/choose sellers
*/
|
function changeAcceptAny(bool _acceptAny) public {
require(isLicenseOwner(msg.sender), "Message sender should have a valid arbitrator license");
require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny,
"Message sender should pass parameter different from the current one");
arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny;
}
|
0.5.10
|
/**
* @notice Allows arbitrator to accept a seller
* @param _arbitrator address of a licensed arbitrator
*/
|
function requestArbitrator(address _arbitrator) public {
require(isLicenseOwner(_arbitrator), "Arbitrator should have a valid license");
require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases");
bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender));
RequestStatus _status = requests[_id].status;
require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status");
if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){
require(requests[_id].date + 3 days < block.timestamp,
"Must wait 3 days before requesting the arbitrator again");
}
requests[_id] = Request({
seller: msg.sender,
arbitrator: _arbitrator,
status: RequestStatus.AWAIT,
date: block.timestamp
});
emit ArbitratorRequested(_id, msg.sender, _arbitrator);
}
|
0.5.10
|
/**
* @notice Allows arbitrator to accept a seller's request
* @param _id request id
*/
|
function acceptRequest(bytes32 _id) public {
require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license");
require(requests[_id].status == RequestStatus.AWAIT, "This request is not pending");
require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator already accepts all cases");
require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator");
requests[_id].status = RequestStatus.ACCEPTED;
address _seller = requests[_id].seller;
permissions[msg.sender][_seller] = true;
emit RequestAccepted(_id, msg.sender, requests[_id].seller);
}
|
0.5.10
|
/**
* @notice Allows arbitrator to reject a request
* @param _id request id
*/
|
function rejectRequest(bytes32 _id) public {
require(isLicenseOwner(msg.sender), "Arbitrator should have a valid license");
require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED,
"Invalid request status");
require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator accepts all cases");
require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator");
requests[_id].status = RequestStatus.REJECTED;
requests[_id].date = block.timestamp;
address _seller = requests[_id].seller;
permissions[msg.sender][_seller] = false;
emit RequestRejected(_id, msg.sender, requests[_id].seller);
}
|
0.5.10
|
/**
* @notice Allows seller to cancel a request
* @param _id request id
*/
|
function cancelRequest(bytes32 _id) public {
require(requests[_id].seller == msg.sender, "This request id does not belong to the message sender");
require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status");
address arbitrator = requests[_id].arbitrator;
requests[_id].status = RequestStatus.CLOSED;
requests[_id].date = block.timestamp;
address _arbitrator = requests[_id].arbitrator;
permissions[_arbitrator][msg.sender] = false;
emit RequestCanceled(_id, arbitrator, requests[_id].seller);
}
|
0.5.10
|
/**
* @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`
* @param _signature Signature string
*/
|
function signatureSplit(bytes memory _signature)
internal
pure
returns (uint8 v, bytes32 r, bytes32 s)
{
require(_signature.length == 65, "Bad signature length");
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
// Here we are loading the last 32 bytes, including 31 bytes
// of 's'. There is no 'mload8' to do this.
//
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 27) {
v += 27;
}
require(v == 27 || v == 28, "Bad signature version");
}
|
0.5.10
|
/**
* @dev Adds or updates user information
* @param _user User address to update
* @param _contactData Contact Data ContactType:UserId
* @param _location New location
* @param _username New status username
*/
|
function _addOrUpdateUser(
address _user,
string memory _contactData,
string memory _location,
string memory _username
) internal {
User storage u = users[_user];
u.contactData = _contactData;
u.location = _location;
u.username = _username;
}
|
0.5.10
|
/**
* @notice Adds or updates user information via signature
* @param _signature Signature
* @param _contactData Contact Data ContactType:UserId
* @param _location New location
* @param _username New status username
* @return Signing user address
*/
|
function addOrUpdateUser(
bytes calldata _signature,
string calldata _contactData,
string calldata _location,
string calldata _username,
uint _nonce
) external returns(address payable _user) {
_user = address(uint160(_getSigner(_username, _contactData, _nonce, _signature)));
require(_nonce == user_nonce[_user], "Invalid nonce");
user_nonce[_user]++;
_addOrUpdateUser(_user, _contactData, _location, _username);
return _user;
}
|
0.5.10
|
/**
* @dev Add a new offer with a new user if needed to the list
* @param _asset The address of the erc20 to exchange, pass 0x0 for Eth
* @param _contactData Contact Data ContactType:UserId
* @param _location The location on earth
* @param _currency The currency the user want to receive (USD, EUR...)
* @param _username The username of the user
* @param _paymentMethods The list of the payment methods the user accept
* @param _limitL Lower limit accepted
* @param _limitU Upper limit accepted
* @param _margin The margin for the user
* @param _arbitrator The arbitrator used by the offer
*/
|
function addOffer(
address _asset,
string memory _contactData,
string memory _location,
string memory _currency,
string memory _username,
uint[] memory _paymentMethods,
uint _limitL,
uint _limitU,
int16 _margin,
address payable _arbitrator
) public payable {
//require(sellingLicenses.isLicenseOwner(msg.sender), "Not a license owner");
// @TODO: limit number of offers if the sender is unlicensed?
require(arbitrationLicenses.isAllowed(msg.sender, _arbitrator), "Arbitrator does not allow this transaction");
require(_limitL <= _limitU, "Invalid limits");
require(msg.sender != _arbitrator, "Cannot arbitrate own offers");
_addOrUpdateUser(
msg.sender,
_contactData,
_location,
_username
);
Offer memory newOffer = Offer(
_margin,
_paymentMethods,
_limitL,
_limitU,
_asset,
_currency,
msg.sender,
_arbitrator,
false
);
uint256 offerId = offers.push(newOffer) - 1;
offerWhitelist[msg.sender][offerId] = true;
addressToOffers[msg.sender].push(offerId);
emit OfferAdded(
msg.sender,
offerId,
_asset,
_location,
_currency,
_username,
_paymentMethods,
_limitL,
_limitU,
_margin);
_stake(offerId, msg.sender, _asset);
}
|
0.5.10
|
/**
* @notice Get the offer by Id
* @dev normally we'd access the offers array, but it would not return the payment methods
* @param _id Offer id
* @return Offer data (see Offer struct)
*/
|
function offer(uint256 _id) external view returns (
address asset,
string memory currency,
int16 margin,
uint[] memory paymentMethods,
uint limitL,
uint limitH,
address payable owner,
address payable arbitrator,
bool deleted
) {
Offer memory theOffer = offers[_id];
// In case arbitrator rejects the seller
address payable offerArbitrator = theOffer.arbitrator;
if(!arbitrationLicenses.isAllowed(theOffer.owner, offerArbitrator)){
offerArbitrator = address(0);
}
return (
theOffer.asset,
theOffer.currency,
theOffer.margin,
theOffer.paymentMethods,
theOffer.limitL,
theOffer.limitU,
theOffer.owner,
offerArbitrator,
theOffer.deleted
);
}
|
0.5.10
|
//-------------------------------------------------------------------------------------
//from StandardToken
|
function super_transfer(address _to, uint _value) /*public*/ internal returns (bool success) {
require(!isSendingLocked[msg.sender]);
require(_value <= oneTransferLimit);
require(balances[msg.sender] >= _value);
if(msg.sender == contrInitiator) {
//no restricton
} else {
require(!isAllTransfersLocked);
require(safeAdd(getLast24hSendingValue(msg.sender), _value) <= oneDayTransferLimit);
}
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
uint tc=transferInfo[msg.sender].tc;
transferInfo[msg.sender].ti[tc].value = _value;
transferInfo[msg.sender].ti[tc].time = now;
transferInfo[msg.sender].tc = safeAdd(transferInfo[msg.sender].tc, 1);
emit Transfer(msg.sender, _to, _value);
return true;
}
|
0.4.23
|
/*
function getTransferInfoValue(address _from, uint index) public view returns (uint value) {
return transferInfo[_from].ti[index].value;
}
*/
|
function getLast24hSendingValue(address _from) public view returns (uint totVal) {
totVal = 0; //declared above;
uint tc = transferInfo[_from].tc;
if(tc > 0) {
for(uint i = tc-1 ; i >= 0 ; i--) {
// if(now - transferInfo[_from].ti[i].time < 10 minutes) {
// if(now - transferInfo[_from].ti[i].time < 1 hours) {
if(now - transferInfo[_from].ti[i].time < 1 days) {
totVal = safeAdd(totVal, transferInfo[_from].ti[i].value );
} else {
break;
}
}
}
}
|
0.4.23
|
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
|
function mint(address _to, uint256 amount) public {
if (msg.sender != owner()) {
require(AssociatedContracts[msg.sender] == true, "Function is just for contract owner...");
}
require(canMint == true, "Mint Function is Disabled!");
require(totalSupply() + amount > totalSupply());
require(totalSupply() + amount < (MaxSupply * (10 ** _decimals)));
require(balanceOf(msg.sender) + amount > balanceOf(msg.sender));
_mint(_to, amount);
emit Minted(_to, amount);
}
|
0.8.7
|
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
|
function redeem(uint amount) public {
if (msg.sender != owner()) {
require(AssociatedContracts[msg.sender] == true, "Function is just for contract owner...");
}
require(totalSupply() >= amount);
require(balanceOf(msg.sender) >= amount);
_burn(msg.sender, amount);
emit Redeem(amount);
}
|
0.8.7
|
/*
* @notice Get the SF reward that can be sent to a function caller right now
*/
|
function getCallerReward(uint256 timeOfLastUpdate, uint256 defaultDelayBetweenCalls) public view returns (uint256) {
bool nullRewards = (baseUpdateCallerReward == 0 && maxUpdateCallerReward == 0);
if (either(timeOfLastUpdate >= now, nullRewards)) return 0;
uint256 timeElapsed = (timeOfLastUpdate == 0) ? defaultDelayBetweenCalls : subtract(now, timeOfLastUpdate);
if (either(timeElapsed < defaultDelayBetweenCalls, baseUpdateCallerReward == 0)) {
return 0;
}
uint256 adjustedTime = subtract(timeElapsed, defaultDelayBetweenCalls);
uint256 maxPossibleReward = minimum(maxUpdateCallerReward, treasuryAllowance() / RAY);
if (adjustedTime > maxRewardIncreaseDelay) {
return maxPossibleReward;
}
uint256 calculatedReward = baseUpdateCallerReward;
if (adjustedTime > 0) {
calculatedReward = rmultiply(rpower(perSecondCallerRewardIncrease, adjustedTime, RAY), calculatedReward);
}
if (calculatedReward > maxPossibleReward) {
calculatedReward = maxPossibleReward;
}
return calculatedReward;
}
|
0.6.7
|
/**
* @notice Send a stability fee reward to an address
* @param proposedFeeReceiver The SF receiver
* @param reward The system coin amount to send
**/
|
function rewardCaller(address proposedFeeReceiver, uint256 reward) internal {
if (address(treasury) == proposedFeeReceiver) return;
if (either(address(treasury) == address(0), reward == 0)) return;
address finalFeeReceiver = (proposedFeeReceiver == address(0)) ? msg.sender : proposedFeeReceiver;
try treasury.pullFunds(finalFeeReceiver, treasury.systemCoin(), reward) {}
catch(bytes memory revertReason) {
emit FailRewardCaller(revertReason, finalFeeReceiver, reward);
}
}
|
0.6.7
|
// --- Management ---
|
function modifyParameters(bytes32 parameter, address addr) external isAuthorized {
require(contractEnabled == 1, "RateSetter/contract-not-enabled");
if (parameter == "orcl") orcl = OracleLike(addr);
else if (parameter == "oracleRelayer") oracleRelayer = OracleRelayerLike(addr);
else if (parameter == "treasury") {
require(StabilityFeeTreasuryLike(addr).systemCoin() != address(0), "RateSetter/treasury-coin-not-set");
treasury = StabilityFeeTreasuryLike(addr);
}
else if (parameter == "pidCalculator") {
pidCalculator = PIDCalculator(addr);
}
else revert("RateSetter/modify-unrecognized-param");
emit ModifyParameters(
parameter,
addr
);
}
|
0.6.7
|
/**
* @dev See {IERC165-supportsInterface}.
*/
|
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId)
|| interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981
|| interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981;
}
|
0.8.4
|
/**
* @dev Retrieve a token's URI
*/
|
function _tokenURI(uint256 tokenId) internal view returns (string memory) {
if (bytes(_tokenURIs[tokenId]).length != 0) {
return _tokenURIs[tokenId];
}
uint256 creatorId;
if(tokenId > MAX_TOKEN_ID) {
creatorId = _creatorTokens[tokenId];
} else {
creatorId = tokenId / CREATOR_SCALE;
}
if (bytes(_creatorURIs[creatorId]).length != 0) {
return string(abi.encodePacked(_creatorURIs[creatorId], tokenId.toString()));
}
return string(abi.encodePacked(_creatorURIs[0], tokenId.toString()));
}
|
0.8.4
|
/**
* Helper to get royalty receivers for a token
*/
|
function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) {
uint256 creatorId;
if(tokenId > MAX_TOKEN_ID) {
creatorId = _creatorTokens[tokenId];
} else {
creatorId = tokenId / CREATOR_SCALE;
}
if (_tokenRoyaltyReceivers[tokenId].length > 0) {
return _tokenRoyaltyReceivers[tokenId];
} else if (_creatorRoyaltyReceivers[creatorId].length > 0) {
return _creatorRoyaltyReceivers[creatorId];
}
return _creatorRoyaltyReceivers[0];
}
|
0.8.4
|
/**
* Helper to get royalty basis points for a token
*/
|
function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) {
uint256 creatorId;
if(tokenId > MAX_TOKEN_ID) {
creatorId = _creatorTokens[tokenId];
} else {
creatorId = tokenId / CREATOR_SCALE;
}
if (_tokenRoyaltyBPS[tokenId].length > 0) {
return _tokenRoyaltyBPS[tokenId];
} else if (_creatorRoyaltyBPS[creatorId].length > 0) {
return _creatorRoyaltyBPS[creatorId];
}
return _creatorRoyaltyBPS[0];
}
|
0.8.4
|
/**
* Helper to shorten royalties arrays if it is too long
*/
|
function _shortenRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, uint256 targetLength) internal {
require(receivers.length == basisPoints.length, "CreatorCore: Invalid input");
if (targetLength < receivers.length) {
for (uint i = receivers.length; i > targetLength; i--) {
receivers.pop();
basisPoints.pop();
}
}
}
|
0.8.4
|
/**
* Helper to update royalites
*/
|
function _updateRoyalties(address payable[] storage receivers, uint256[] storage basisPoints, address payable[] calldata newReceivers, uint256[] calldata newBPS) internal {
require(receivers.length == basisPoints.length, "CreatorCore: Invalid input");
require(newReceivers.length == newBPS.length, "CreatorCore: Invalid input");
uint256 totalRoyalties;
for (uint i = 0; i < newReceivers.length; i++) {
if (i < receivers.length) {
receivers[i] = newReceivers[i];
basisPoints[i] = newBPS[i];
} else {
receivers.push(newReceivers[i]);
basisPoints.push(newBPS[i]);
}
totalRoyalties += newBPS[i];
}
require(totalRoyalties < 10000, "CreatorCore: Invalid total royalties");
}
|
0.8.4
|
/**
* Set royalties for all tokens of an extension
*/
|
function _setRoyaltiesCreator(uint256 creatorId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal {
require(receivers.length == basisPoints.length, "CreatorCore: Invalid input");
_shortenRoyalties(_creatorRoyaltyReceivers[creatorId], _creatorRoyaltyBPS[creatorId], receivers.length);
_updateRoyalties(_creatorRoyaltyReceivers[creatorId], _creatorRoyaltyBPS[creatorId], receivers, basisPoints);
if (creatorId == 0) {
emit DefaultRoyaltiesUpdated(receivers, basisPoints);
} else {
emit CreatorRoyaltiesUpdated(creatorId, receivers, basisPoints);
}
}
|
0.8.4
|
// Quick swap low gas method for pool swaps
|
function deposit(uint256 _amount)
external
nonReentrant
{
require(_amount > 0, "deposit must be greater than 0");
pool = _calcPoolValueInToken();
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
// Calculate pool shares
uint256 shares = 0;
if (pool == 0) {
shares = _amount;
pool = _amount;
} else {
shares = (_amount.mul(_totalSupply)).div(pool);
}
pool = _calcPoolValueInToken();
_mint(msg.sender, shares);
}
|
0.5.12
|
// 1999999614570950845
|
function _withdrawSomeFulcrum(uint256 _amount) internal {
// Balance of fulcrum tokens, 1 iDAI = 1.00x DAI
uint256 b = balanceFulcrum(); // 1970469086655766652
// Balance of token in fulcrum
uint256 bT = balanceFulcrumInToken(); // 2000000803224344406
require(bT >= _amount, "insufficient funds");
// can have unintentional rounding errors
uint256 amount = (b.mul(_amount)).div(bT).add(1);
_withdrawFulcrum(amount);
}
|
0.5.12
|
// Internal only rebalance for better gas in redeem
|
function _rebalance(Lender newProvider) internal {
if (_balance() > 0) {
if (newProvider == Lender.DYDX) {
supplyDydx(_balance());
} else if (newProvider == Lender.FULCRUM) {
supplyFulcrum(_balance());
} else if (newProvider == Lender.COMPOUND) {
supplyCompound(_balance());
} else if (newProvider == Lender.AAVE) {
supplyAave(_balance());
}
}
provider = newProvider;
}
|
0.5.12
|
/**
* Set some Moai aside
*/
|
function reserveMoai() public onlyOwner {
uint supply = totalSupply();
require(supply.add(50) <= MAX_MOAI , "would exceed max supply of Moai");
uint i;
for (i = 0; i < 50; i++) {
_safeMint(msg.sender, supply + i);
}
}
|
0.7.0
|
/**
* Mints Moai
*/
|
function mintMoai(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Moai");
require(numberOfTokens <= maxMoaiPurchase, "Can only mint 8 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_MOAI, "Purchase would exceed max supply of Moai");
require(moaiPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_MOAI) {
_safeMint(msg.sender, mintIndex);
}
}
}
|
0.7.0
|
/**
* @dev See {ICreatorCore-setTokenURI}.
*/
|
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired {
require(tokenIds.length == uris.length, "LGND: Invalid input");
for (uint i = 0; i < tokenIds.length; i++) {
_setTokenURI(tokenIds[i], uris[i]);
}
}
|
0.8.4
|
/**
* @dev Mint token
*/
|
function _mintCreator(address to, uint256 creatorId, uint256 templateId, string memory uri) internal virtual returns(uint256 tokenId) {
require(templateId <= MAX_TEMPLATE_ID, "LGND: templateId exceeds maximum");
uint256 mintId = _creatorTokenCount[creatorId][templateId] + 1;
require(mintId <= MAX_MINT_ID, "LGND: no remaining mints available");
_creatorTokenCount[creatorId][templateId] = mintId;
tokenId = (creatorId * CREATOR_SCALE) + (templateId * TEMPLATE_SCALE) + mintId;
_supply++;
_mint(_creatorAddresses[creatorId], tokenId);
if(_creatorAddresses[creatorId] != to) {
_safeTransfer(_creatorAddresses[creatorId], to, tokenId, "");
}
if (bytes(uri).length > 0) {
_tokenURIs[tokenId] = uri;
}
return tokenId;
}
|
0.8.4
|
/**
* @dev See {IERC721CreatorCore-burn}.
*/
|
function burn(uint256 tokenId) external override {
require(_isApprovedOrOwner(msg.sender, tokenId), "LGND: caller is not owner nor approved");
address owner = ERC721.ownerOf(tokenId);
require(bytes(_linkedAccounts[owner]).length != 0, "LGND: Must link account with setLinkedAccount");
if(tokenId > MAX_TOKEN_ID) {
require(_bridgeEnabled, "LGND: Bridge has not been enabled for this token");
_supply--;
// Delete token origin extension tracking
delete _creatorTokens[tokenId];
} else {
require(_creatorBridgeEnabled[tokenId / CREATOR_SCALE], "LGND: Bridge has not been enabled for this token");
}
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
emit ExportedToken(owner, exports++, tokenId, _linkedAccounts[owner]);
_burn(tokenId);
}
|
0.8.4
|
// Allows the developer or anyone with the password to claim the bounty and shut down everything except withdrawals in emergencies.
|
function activate_kill_switch(string password) {
// Only activate the kill switch if the sender is the developer or the password is correct.
if (msg.sender != developer && sha3(password) != password_hash) throw;
// Store the claimed bounty in a temporary variable.
uint256 claimed_bounty = bounty;
// Update bounty prior to sending to prevent recursive call.
bounty = 0;
// Irreversibly activate the kill switch.
kill_switch = true;
// Send the caller their bounty for activating the kill switch.
msg.sender.transfer(claimed_bounty);
}
|
0.4.13
|
// Automatically withdraws on users' behalves (less a 1% fee on tokens).
|
function auto_withdraw(address user){
// Only allow automatic withdrawals after users have had a chance to manually withdraw.
if (!bought_tokens || now < time_bought + 1 hours) throw;
// Withdraw the user's funds for them.
withdraw(user, true);
}
|
0.4.13
|
// Allows developer to add ETH to the buy execution bounty.
|
function add_to_bounty() payable {
// Only allow the developer to contribute to the buy execution bounty.
if (msg.sender != developer) throw;
// Disallow adding to bounty if kill switch is active.
if (kill_switch) throw;
// Disallow adding to the bounty if contract has already bought the tokens.
if (bought_tokens) throw;
// Update bounty to include received amount.
bounty += msg.value;
}
|
0.4.13
|
// A helper function for the default function, allowing contracts to interact.
|
function default_helper() payable {
// Treat near-zero ETH transactions as withdrawal requests.
if (msg.value <= 1 finney) {
// No fee on manual withdrawals.
withdraw(msg.sender, false);
}
// Deposit the user's funds for use in purchasing tokens.
else {
// Disallow deposits if kill switch is active.
if (kill_switch) throw;
// Only allow deposits if the contract hasn't already purchased the tokens.
if (bought_tokens) throw;
// Update records of deposited ETH to include the received amount.
balances[msg.sender] += msg.value;
}
}
|
0.4.13
|
// @dev create specified number of tokens and transfer to destination
|
function createTokensInt(uint256 _tokens, address _destination) internal onlyOwner {
uint256 tokens = _tokens * 10**uint256(decimals);
totalSupply_ = totalSupply_.add(tokens);
balances[_destination] = balances[_destination].add(tokens);
emit Transfer(0x0, _destination, tokens);
totalBurnedOut_ = 0;
require(totalSupply_ <= HARD_CAP);
}
|
0.4.24
|
//-- mint
// Transfer ETH to receive a given amount of tokens in exchange
// Token amount must be integers, no decimals
// Current token cost is determined through computeCost, frontend sets the proper ETH amount to send
|
function mint(uint fullToken) public payable {
uint _token = fullToken.mul(10 ** decimals);
uint _newSupply = _totalSupply.add(_token);
require(_newSupply <= MAX_SUPPLY, "supply cannot go over 1M");
uint _ethCost = computeCost(fullToken);
require(msg.value == _ethCost, "wrong ETH amount for tokens");
owner.transfer(msg.value);
_totalSupply = _newSupply;
balances[msg.sender] = balances[msg.sender].add(_token);
emit Minted(msg.sender, msg.value, fullToken);
}
|
0.5.10
|
//func constructor
|
function GrowToken() public {
owner = 0x757D7FbB9822b5033a6BBD4e17F95714942f921f;
name = "GROWCHAIN";
symbol = "GROW";
decimals = 8;
totalSupply = 5000000000 * 10 ** uint256(8);
//init totalSupply to map(db)
balanceOf[owner] = totalSupply;
}
|
0.4.18
|
// 2 Transfer Other's tokens ,who had approve some token to me
|
function transferFrom(address _from,address _to,uint256 _value) public returns (bool success){
//validate the allowance
require(!frozenAccount[_from]&&!frozenAccount[msg.sender]);
require(_value<=allowance[_from][msg.sender]);
//do action :sub allowance and do transfer
allowance[_from][msg.sender] -= _value;
if(_to == address(this)){
_sell(_from,_value);
}else
{
_transfer(_from,_to,_value);
}
return true;
}
|
0.4.18
|
//internal transfer function
// 1 _transfer
|
function _transfer(address _from,address _to, uint256 _value) internal {
//validate input and other internal limites
require(_to != 0x0);//check to address
require(balanceOf[_from] >= _value);//check from address has enough balance
require(balanceOf[_to] + _value >balanceOf[_to]);//after transfer the balance of _to address is ok ,no overflow
uint256 previousBalances = balanceOf[_from]+balanceOf[_to];//store it for add asset to power the security
//do transfer:sub from _from address,and add to the _to address
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
//after transfer: emit transfer event,and add asset for security
Transfer(_from,_to,_value);
assert(balanceOf[_from]+balanceOf[_to] == previousBalances);
}
|
0.4.18
|
// 3 _sell
|
function _sell(address _from,uint256 amount) internal returns (uint256 revenue){
require(sellOpen);
require(!frozenAccount[_from]);
require(amount>0);
require(sellPrice>0);
require(_from!=owner);
_transfer(_from,owner,amount);
revenue = amount * sellPrice;
_from.transfer(revenue); // sends ether to the seller: it's important to do this last to prevent recursion attacks
SellToken(_from,sellPrice,amount,revenue);
return revenue; // ends function and returns
}
|
0.4.18
|
/********************************** Mutated Functions **********************************/
|
function mint() external nonReentrant {
PendingMint memory pending = addressToPendingMint[msg.sender];
address _lottery = lottery;
uint256 _tokenCounter = tokenCounter;
for (uint256 level = pending.mintedLevel + 1; level <= pending.maxLevel; level++) {
tokenToLevel[_tokenCounter] = level;
_safeMint(msg.sender, _tokenCounter);
if (_lottery != address(0)) {
ILottery(_lottery).registerToken(_tokenCounter);
}
_tokenCounter += 1;
}
tokenCounter = _tokenCounter;
pending.mintedLevel = pending.maxLevel;
addressToPendingMint[msg.sender] = pending;
}
|
0.7.6
|
/* Smart Contract Administation - Owner Only */
|
function reserve(uint256 count) public onlyOwner {
require(isDevMintEnabled, "Dev Minting not active");
require(totalSupply() + count - 1 < MAX_SUPPLY, "Exceeds max supply");
for (uint256 i = 0; i < count; i++) {
_safeMint(_msgSender(), totalSupply());
}
}
|
0.8.9
|
// ============ Mint & Redeem & Donate ============
|
function mint(uint256 dodoAmount, address superiorAddress) public {
require(
superiorAddress != address(0) && superiorAddress != msg.sender,
"vDODOToken: Superior INVALID"
);
require(dodoAmount > 0, "vDODOToken: must mint greater than 0");
UserInfo storage user = userInfo[msg.sender];
if (user.superior == address(0)) {
require(
superiorAddress == _DODO_TEAM_ || userInfo[superiorAddress].superior != address(0),
"vDODOToken: INVALID_SUPERIOR_ADDRESS"
);
user.superior = superiorAddress;
}
_updateAlpha();
IDODOApproveProxy(_DODO_APPROVE_PROXY_).claimTokens(
_DODO_TOKEN_,
msg.sender,
address(this),
dodoAmount
);
uint256 newStakingPower = DecimalMath.divFloor(dodoAmount, alpha);
_mint(user, newStakingPower);
emit MintVDODO(msg.sender, superiorAddress, dodoAmount);
}
|
0.6.9
|
/**
* Constructor mints tokens to corresponding addresses
*/
|
function Token () public {
address publicSaleReserveAddress = 0x11f104b59d90A00F4bDFF0Bed317c8573AA0a968;
mint(publicSaleReserveAddress, 100000000);
address hintPlatformReserveAddress = 0xE46C2C7e4A53bdC3D91466b6FB45Ac9Bc996a3Dc;
mint(hintPlatformReserveAddress, 21000000000);
address advisorsReserveAddress = 0xdc9aea710D5F8169AFEDA4bf6F1d6D64548951AF;
mint(advisorsReserveAddress, 50000000);
address frozenHintEcosystemReserveAddress = 0xfeC2C0d053E9D6b1A7098F17b45b48102C8890e5;
mint(frozenHintEcosystemReserveAddress, 77600000000);
address teamReserveAddress = 0xeE162d1CCBb1c14169f26E5b35e3ca44C8bDa4a0;
mint(teamReserveAddress, 50000000);
address preICOReserveAddress = 0xD2c395e12174630993572bf4Cbb5b9a93384cdb2;
mint(preICOReserveAddress, 100000000);
address foundationReserveAddress = 0x7A5d4e184f10b63C27ad772D17bd3b7393933142;
mint(foundationReserveAddress, 100000000);
address hintPrivateOfferingReserve = 0x3f851952ACbEd98B39B913a5c8a2E55b2E28c8F4;
mint(hintPrivateOfferingReserve, 1000000000);
assert(totalSupply == 100000000000*decimalMultiplier);
}
|
0.4.18
|
// >>> include all other rewards in eth besides _claimableBasicInETH()
|
function _claimableInETH() internal override view returns (uint256 _claimable) {
_claimable = super._claimableInETH();
uint256 _dfd = IERC20(dfd).balanceOf(address(this));
if (_dfd > 0) {
address[] memory path = new address[](2);
path[0] = dfd;
path[1] = weth;
uint256[] memory swap = Uni(dex[2]).getAmountsOut(_dfd, path);
_claimable = _claimable.add(swap[1]);
}
}
|
0.6.12
|
/**
* @notice Atomic Token Swap
* @param nonce uint256 Unique and should be sequential
* @param expiry uint256 Expiry in seconds since 1 January 1970
* @param signerWallet address Wallet of the signer
* @param signerToken address ERC20 token transferred from the signer
* @param signerAmount uint256 Amount transferred from the signer
* @param senderToken address ERC20 token transferred from the sender
* @param senderAmount uint256 Amount transferred from the sender
* @param v uint8 "v" value of the ECDSA signature
* @param r bytes32 "r" value of the ECDSA signature
* @param s bytes32 "s" value of the ECDSA signature
*/
|
function swap(
uint256 nonce,
uint256 expiry,
address signerWallet,
IERC20 signerToken,
uint256 signerAmount,
IERC20 senderToken,
uint256 senderAmount,
uint8 v,
bytes32 r,
bytes32 s
) external override {
swapWithRecipient(
msg.sender,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
senderToken,
senderAmount,
v,
r,
s
);
}
|
0.6.12
|
/**
* @notice Cancel one or more nonces
* @dev Cancelled nonces are marked as used
* @dev Emits a Cancel event
* @dev Out of gas may occur in arrays of length > 400
* @param nonces uint256[] List of nonces to cancel
*/
|
function cancel(uint256[] calldata nonces) external override {
for (uint256 i = 0; i < nonces.length; i++) {
uint256 nonce = nonces[i];
if (_markNonceAsUsed(msg.sender, nonce)) {
emit Cancel(nonce, msg.sender);
}
}
}
|
0.6.12
|
/**
* @notice Returns true if the nonce has been used
* @param signer address Address of the signer
* @param nonce uint256 Nonce being checked
*/
|
function nonceUsed(address signer, uint256 nonce)
public
view
override
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
return (_nonceGroups[signer][groupKey] >> indexInGroup) & 1 == 1;
}
|
0.6.12
|
/**
* @notice Marks a nonce as used for the given signer
* @param signer address Address of the signer for which to mark the nonce as used
* @param nonce uint256 Nonce to be marked as used
* @return bool True if the nonce was not marked as used already
*/
|
function _markNonceAsUsed(address signer, uint256 nonce)
internal
returns (bool)
{
uint256 groupKey = nonce / 256;
uint256 indexInGroup = nonce % 256;
uint256 group = _nonceGroups[signer][groupKey];
// If it is already used, return false
if ((group >> indexInGroup) & 1 == 1) {
return false;
}
_nonceGroups[signer][groupKey] = group | (uint256(1) << indexInGroup);
return true;
}
|
0.6.12
|
/**
* @notice Hash order parameters
* @param nonce uint256
* @param expiry uint256
* @param signerWallet address
* @param signerToken address
* @param signerAmount uint256
* @param senderToken address
* @param senderAmount uint256
* @return bytes32
*/
|
function _getOrderHash(
uint256 nonce,
uint256 expiry,
address signerWallet,
IERC20 signerToken,
uint256 signerAmount,
address senderWallet,
IERC20 senderToken,
uint256 senderAmount
) internal view returns (bytes32) {
return
keccak256(
abi.encode(
ORDER_TYPEHASH,
nonce,
expiry,
signerWallet,
signerToken,
signerAmount,
signerFee,
senderWallet,
senderToken,
senderAmount
)
);
}
|
0.6.12
|
/**
* @notice Recover the signatory from a signature
* @param hash bytes32
* @param v uint8
* @param r bytes32
* @param s bytes32
*/
|
function _getSignatory(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal view returns (address) {
bytes32 digest =
keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash));
address signatory = ecrecover(digest, v, r, s);
// Ensure the signatory is not null
require(signatory != address(0), "INVALID_SIG");
return signatory;
}
|
0.6.12
|
// Transfer recipient recives amount - fee
|
function transfer(address recipient, uint256 amount) public override returns (bool) {
if (activeFee && feeException[_msgSender()] == false) {
uint256 marketing = transferFee.mul(amount).div(100000);
uint256 fee = transferFee.mul(amount).div(10000).sub(marketing);
uint amountLessFee = amount.sub(fee).sub(marketing);
_transfer(_msgSender(), recipient, amountLessFee);
_transfer(_msgSender(), feeRecipient, fee);
_transfer(_msgSender(), marketingRecipient, marketing);
} else {
_transfer(_msgSender(), recipient, amount);
}
return true;
}
|
0.6.2
|
// TransferFrom recipient recives amount, sender's account is debited amount + fee
|
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
if (activeFee && feeException[recipient] == false) {
uint256 fee = transferFee.mul(amount).div(10000);
_transfer(sender, feeRecipient, fee);
}
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
|
0.6.2
|
// want => stratId => StrategyInfo
|
function setStrategyInfo(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external {
require(msg.sender == strategist || msg.sender == governance, "!strategist");
require(approvedStrategies[_want][_strategy], "!approved");
strategies[_want][_sid].strategy = _strategy;
strategies[_want][_sid].quota = _quota;
strategies[_want][_sid].percent = _percent;
}
|
0.6.12
|
/**
* adds SamuraiDoges to the War
* @param tokenIds the IDs of the SamuraiDoge to stake
*/
|
function addManyToWar(uint16[] calldata tokenIds) external {
require(stakeIsActive, "Staking is paused");
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
samuraidoge.ownerOf(tokenIds[i]) == msg.sender,
"Not your token"
);
samuraidoge.transferFrom(msg.sender, address(this), tokenIds[i]);
_addSamuraiDogeToWar(msg.sender, tokenIds[i]);
}
}
|
0.8.10
|
/**
* realize $HONOR earnings and optionally unstake tokens from the War
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
*/
|
function claimManyFromWar(uint16[] calldata tokenIds, bool unstake)
external
{
uint256 owed = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
owed += _claimHonorFromWar(tokenIds[i], unstake);
}
if (owed == 0) return;
honor.stakingMint(msg.sender, owed);
}
|
0.8.10
|
/**
* realize $HONOR earnings for a single SamuraiDoge and optionally unstake it
* @param tokenId the ID of the SamuraiDoge to claim earnings from
* @param unstake whether or not to unstake the SamuraiDoge
* @return owed - the amount of $HONOR earned
*/
|
function _claimHonorFromWar(uint256 tokenId, bool unstake)
internal
returns (uint256)
{
Stake memory stake = war[tokenId];
if (stake.owner == address(0)) {
// Unstaked SD tokens
require(
samuraidoge.ownerOf(tokenId) == msg.sender,
"Not your token"
);
uint256 owed = _getClaimableHonor(tokenId);
bonusClaimed[tokenId] = true;
emit HONORClaimed(tokenId, owed, unstake);
return owed;
} else {
// Staked SD tokens
require(stake.owner == msg.sender, "Not your token");
uint256 owed = _getClaimableHonor(tokenId);
if (_elligibleForBonus(tokenId)) {
bonusClaimed[tokenId] = true;
}
if (unstake) {
// Send back SamuraiDoge to owner
samuraidoge.safeTransferFrom(
address(this),
msg.sender,
tokenId,
""
);
_removeTokenFromOwnerEnumeration(stake.owner, stake.tokenId);
delete war[tokenId];
totalSamuraiDogeStaked -= 1;
numTokensStaked[msg.sender] -= 1;
} else {
// Reset stake
war[tokenId] = Stake({
owner: msg.sender,
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
}
emit HONORClaimed(tokenId, owed, unstake);
return owed;
}
}
|
0.8.10
|
/**
* Calculate claimable $HONOR earnings from a single staked SamuraiDoge
* @param tokenId the ID of the token to claim earnings from
*/
|
function _getClaimableHonor(uint256 tokenId)
internal
view
returns (uint256)
{
uint256 owed = 0;
if (tokenId < tokensElligibleForBonus && !bonusClaimed[tokenId]) {
owed += bonusAmount;
}
Stake memory stake = war[tokenId];
if (stake.value == 0) {} else if (
block.timestamp < lastClaimTimestamp
) {
owed +=
((block.timestamp - stake.value) * DAILY_HONOR_RATE) /
1 days;
} else if (stake.value > lastClaimTimestamp) {
// $HONOR production stopped already
} else {
owed =
((lastClaimTimestamp - stake.value) * DAILY_HONOR_RATE) /
1 days; // stop earning additional $HONOR after lastClaimTimeStamp
}
return owed;
}
|
0.8.10
|
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures.
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param owner address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
|
function _removeTokenFromOwnerEnumeration(address owner, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = numTokensStaked[owner] - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[owner][lastTokenIndex];
_ownedTokens[owner][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[owner][lastTokenIndex];
}
|
0.8.10
|
/**
* allows owner to unstake tokens from the War, return the tokens to the tokens' owner, and claim $HON earnings
* @param tokenIds the IDs of the tokens to claim earnings from
* @param tokenOwner the address of the SamuraiDoge tokens owner
*/
|
function rescueManyFromWar(uint16[] calldata tokenIds, address tokenOwner)
external
onlyOwner
{
uint256 owed = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
owed += _rescueFromWar(tokenIds[i], tokenOwner);
}
if (owed == 0) return;
honor.stakingMint(tokenOwner, owed);
}
|
0.8.10
|
/**
* unstake a single SamuraiDoge from War and claim $HON earnings
* @param tokenId the ID of the SamuraiDoge to rescue
* @param tokenOwner the address of the SamuraiDoge token owner
* @return owed - the amount of $HONOR earned
*/
|
function _rescueFromWar(uint256 tokenId, address tokenOwner)
internal
returns (uint256)
{
Stake memory stake = war[tokenId];
require(stake.owner == tokenOwner, "Not your token");
uint256 owed = _getClaimableHonor(tokenId);
if (_elligibleForBonus(tokenId)) {
bonusClaimed[tokenId] = true;
}
// Send back SamuraiDoge to owner
samuraidoge.safeTransferFrom(address(this), tokenOwner, tokenId, "");
_removeTokenFromOwnerEnumeration(stake.owner, stake.tokenId);
delete war[tokenId];
totalSamuraiDogeStaked -= 1;
numTokensStaked[tokenOwner] -= 1;
emit HONORClaimed(tokenId, owed, true);
return owed;
}
|
0.8.10
|
/**
* @dev Fetch all tokens owned by an address
*/
|
function tokensOfOwner(address _owner) external view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
|
0.8.4
|
/**
* @dev Fetch all tokens and their tokenHash owned by an address
*/
|
function tokenHashesOfOwner(address _owner) external view returns (uint256[] memory, bytes32[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return (new uint256[](0), new bytes32[](0));
} else {
uint256[] memory result = new uint256[](tokenCount);
bytes32[] memory hashes = new bytes32[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
hashes[index] = tokenIdToHash[index];
}
return (result, hashes);
}
}
|
0.8.4
|
/**
* @dev Returns current token price
*/
|
function getNFTPrice() public view returns (uint256) {
require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started");
uint256 count = totalSupply();
require(count < MAX_NFT_SUPPLY, "Sale has already ended");
uint256 elapsed = block.timestamp - SALE_START_TIMESTAMP;
if (elapsed >= SALE_DURATION * SALE_DURATION_SEC_PER_STEP) {
return DUTCH_AUCTION_END_FEE;
} else {
return (((SALE_DURATION * SALE_DURATION_SEC_PER_STEP - elapsed - 1) / SALE_DURATION_SEC_PER_STEP + 1) * (DUTCH_AUCTION_START_FEE - DUTCH_AUCTION_END_FEE)) / SALE_DURATION + DUTCH_AUCTION_END_FEE;
}
}
|
0.8.4
|
/**
* @dev Mint tokens and refund any excessive amount of ETH sent in
*/
|
function mintAndRefundExcess(uint256 numberOfNfts) external payable nonReentrant {
// Checks
require(!contractSealed, "Contract sealed");
require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started");
require(numberOfNfts > 0, "Cannot mint 0 NFTs");
require(numberOfNfts <= 50, "Cannot mint more than 50 in 1 tx");
uint256 total = totalSupply();
require(total + numberOfNfts <= MAX_NFT_SUPPLY, "Sold out");
uint256 price = getNFTPrice();
require(msg.value >= numberOfNfts * price, "Ether value sent is insufficient");
// Effects
_safeMintWithHash(msg.sender, numberOfNfts, total);
if (msg.value > numberOfNfts * price) {
(bool success, ) = msg.sender.call{value: msg.value - numberOfNfts * price}("");
require(success, "Refund excess failed.");
}
}
|
0.8.4
|
/**
* @dev Mint early access tokens
*/
|
function mintEarlyAccess(uint256 numberOfNfts) external payable nonReentrant {
// Checks
require(!contractSealed, "Contract sealed");
require(block.timestamp < SALE_START_TIMESTAMP, "Early access is over");
require(block.timestamp >= EARLY_ACCESS_START_TIMESTAMP, "Early access has not started");
require(numberOfNfts > 0, "Cannot mint 0 NFTs");
require(numberOfNfts <= 50, "Cannot mint more than 50 in 1 tx");
uint256 total = totalSupply();
require(total + numberOfNfts <= MAX_NFT_SUPPLY, "Sold out");
require(earlyAccessMinted + numberOfNfts <= MAX_EARLY_ACCESS_SUPPLY, "No more early access tokens left");
require(earlyAccessList[msg.sender] >= numberOfNfts, "Invalid early access mint");
require(msg.value == numberOfNfts * EARLY_ACCESS_MINT_FEE, "Ether value sent is incorrect");
// Effects
earlyAccessList[msg.sender] = earlyAccessList[msg.sender] - numberOfNfts;
earlyAccessMinted = earlyAccessMinted + numberOfNfts;
_safeMintWithHash(msg.sender, numberOfNfts, total);
}
|
0.8.4
|
/**
* @dev Interact with Pochi. Directly from Ethereum!
*/
|
function pochiAction(
uint256 actionType,
string calldata actionText,
string calldata actionTarget
) external payable {
if (balanceOf(msg.sender) > 0) {
require(msg.value >= POCHI_ACTION_OWNER_FEE, "Ether value sent is incorrect");
} else {
require(msg.value >= POCHI_ACTION_PUBLIC_FEE, "Ether value sent is incorrect");
}
emit PochiAction(block.timestamp, actionType, actionText, actionTarget, msg.sender);
}
|
0.8.4
|
/**
* @dev Safely mint tokens, and assign tokenHash to the new tokens
*
* Emits a {NewTokenHash} event.
*/
|
function _safeMintWithHash(
address to,
uint256 numberOfNfts,
uint256 startingTokenId
) internal virtual {
for (uint256 i = 0; i < numberOfNfts; i++) {
uint256 tokenId = startingTokenId + i;
bytes32 tokenHash = keccak256(abi.encodePacked(tokenId, block.number, block.coinbase, block.timestamp, blockhash(block.number - 1), msg.sender));
tokenIdToHash[tokenId] = tokenHash;
_safeMint(to, tokenId, "");
emit NewTokenHash(tokenId, tokenHash);
}
}
|
0.8.4
|
/**
* @dev Add to the early access list
*/
|
function deployerAddEarlyAccess(address[] calldata recipients, uint256[] calldata limits) external onlyDeployer {
require(!contractSealed, "Contract sealed");
for (uint256 i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Can't add the null address");
earlyAccessList[recipients[i]] = limits[i];
}
}
|
0.8.4
|
/**
* @dev Remove from the early access list
*/
|
function deployerRemoveEarlyAccess(address[] calldata recipients) external onlyDeployer {
require(!contractSealed, "Contract sealed");
for (uint256 i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Can't remove the null address");
earlyAccessList[recipients[i]] = 0;
}
}
|
0.8.4
|
/**
* @dev Reserve dev tokens and air drop tokens to craft ham holders
*/
|
function deployerMintMultiple(address[] calldata recipients) external payable onlyDeployer {
require(!contractSealed, "Contract sealed");
uint256 total = totalSupply();
require(total + recipients.length <= MAX_NFT_SUPPLY, "Sold out");
for (uint256 i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Can't mint to null address");
_safeMintWithHash(recipients[i], 1, total + i);
}
}
|
0.8.4
|
// callable by owner only
|
function activate() onlyOwner public {
//check for rewards
ERC20 tokenOne = ERC20(token1);
ERC20 tokenTwo = ERC20(token2);
uint256 tenPerc=10;
uint256 balanceForToken1= tokenOne.balanceOf(address(this));
uint256 balanceForToken2= tokenTwo.balanceOf(address(this));
uint256 token1CheckAmount;
uint256 token2CheckAmount;
uint256 rewardBalance1;
uint256 rewardBalance2;
token1CheckAmount = SafeMath.sub(balanceForToken1,totalStaked1);
token2CheckAmount = SafeMath.sub(balanceForToken2,totalStaked2);
rewardBalance1 = SafeMath.sub(SafeMath.sub(rewardAmt1,totalRedeemed1),openRewards1);
rewardBalance2 = SafeMath.sub(SafeMath.sub(rewardAmt2,totalRedeemed2),openRewards2);
require (token1CheckAmount>=SafeMath.div(rewardBalance1,tenPerc),"Activation error. Insufficient balance of rewards for token1");
require (token2CheckAmount>=SafeMath.div(rewardBalance2,tenPerc),"Activation error. Insufficient balance of rewards for token2");
//activate staking
stakingStarted = true;
emit StartStaking(msg.sender,block.timestamp);
}
|
0.8.4
|
// UniswapV3 callback
|
function uniswapV3SwapCallback(
int256,
int256,
bytes calldata data
) external {
SwapV3Calldata memory fsCalldata = abi.decode(data, (SwapV3Calldata));
CallbackValidation.verifyCallback(UNIV3_FACTORY, fsCalldata.tokenIn, fsCalldata.tokenOut, fsCalldata.fee);
bool success;
bytes memory m;
for (uint256 i = 0; i < fsCalldata.targets.length; i++) {
(success, m) = fsCalldata.targets[i].call(fsCalldata.data[i]);
require(success, string(m));
}
}
|
0.7.4
|
/**
* To allow distributing of trading fees to be split between dapps
* (Dapps cant be hardcoded because more will be added in future)
* Has a hardcap of 1% per 24 hours -trading fees consistantly exceeding that 1% is not a bad problem to have(!)
*/
|
function distributeTradingFees(address recipient, uint256 amount) external {
uint256 liquidityBalance = liquidityToken.balanceOf(address(this));
require(amount < (liquidityBalance / 100)); // Max 1%
require(lastTradingFeeDistribution + 24 hours < now); // Max once a day
require(msg.sender == tszunami);
liquidityToken.transfer(recipient, amount);
lastTradingFeeDistribution = now;
}
|
0.5.16
|
/**
* Check the merkle proof of balance in the given side-chain block for given account
*/
|
function proofIsCorrect(uint blockNumber, address account, uint balance, bytes32[] memory proof) public view returns(bool) {
bytes32 hash = keccak256(abi.encodePacked(account, balance));
bytes32 rootHash = blockHash[blockNumber];
require(rootHash != 0x0, "error_blockNotFound");
return rootHash == calculateRootHash(hash, proof);
}
|
0.4.24
|
/**
* Calculate root hash of a Merkle tree, given
* @param hash of the leaf to verify
* @param others list of hashes of "other" branches
*/
|
function calculateRootHash(bytes32 hash, bytes32[] memory others) public pure returns (bytes32 root) {
root = hash;
for (uint8 i = 0; i < others.length; i++) {
bytes32 other = others[i];
if (other == 0x0) continue; // odd branch, no need to hash
if (root < other) {
root = keccak256(abi.encodePacked(root, other));
} else {
root = keccak256(abi.encodePacked(other, root));
}
}
}
|
0.4.24
|
/**
* Called from BalanceVerifier.prove
* Prove can be called directly to withdraw less than the whole share,
* or just "cement" the earnings so far into root chain even without withdrawing
*/
|
function onVerifySuccess(uint blockNumber, address account, uint newEarnings) internal {
uint blockFreezeStart = blockTimestamp[blockNumber];
require(now > blockFreezeStart + blockFreezeSeconds, "error_frozen");
require(earnings[account] < newEarnings, "error_oldEarnings");
totalProven = totalProven.add(newEarnings).sub(earnings[account]);
require(totalProven.sub(totalWithdrawn) <= token.balanceOf(this), "error_missingBalance");
earnings[account] = newEarnings;
}
|
0.4.24
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.