comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/*
* Function swapping the presale tokens for the Signal tokens regardless on the presale pool
* @dev initiated from Signals (passing the ownership to a oracle to handle a script is recommended)
* @dev requires having ownership of the two presale contracts
* @dev requires the calling party to finish the KYC pro... | function swapFor(address whom) onlyOwner public returns(bool) {
require(registry.approved(whom));
uint256 oldBalance;
uint256 newBalance;
if (PublicPresale.balanceOf(whom) > 0) {
oldBalance = PublicPresale.balanceOf(whom);
newBalance = oldBalance * compens... | 0.4.20 |
/*
* Buy in function to be called from the fallback function
* @param beneficiary address
*/ | function buyTokens(address beneficiary) private {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// base discount
uint256 discount = ((toBeRaised*10000)/HARD_CAP)*15;
// calculate token amount to be created
uint2... | 0.4.20 |
/// @dev See `IERC20.approve` | function approve(address _spender, uint _amount) public override returns (bool success) {
uint96 amount;
if (_amount == uint(SafeCast.toUint256(-1))) {
amount = uint96(SafeCast.toUint256(-1));
} else {
amount = safe96(_amount, "DAWG::permit: amount exceeds 96 bits");... | 0.8.6 |
/// @dev `See ERC20i.transferFrom` | function transferFrom(address _from, address _to, uint _amount) public override returns (bool success) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[_from][spender];
uint96 amount = safe96(_amount, "DAWG::approve: amount exceeds 96 bits");
if (spender != _fro... | 0.8.6 |
/**
* @dev Function for loomiVault deposit
*/ | function deposit(uint256[] memory tokenIds) public nonReentrant whenNotPaused {
require(tokenIds.length > 0, "Empty array");
Staker storage user = _stakers[_msgSender()];
if (user.stakedVault.length == 0) {
uint256 currentLoomiPot = _getLoomiPot();
user.loomiPotSnapshot = currentLoomi... | 0.8.7 |
/**
* @dev Function for loomiVault withdraw
*/ | function withdraw(uint256[] memory tokenIds) public nonReentrant whenNotPaused {
require(tokenIds.length > 0, "Empty array");
Staker storage user = _stakers[_msgSender()];
accumulate(_msgSender());
for (uint256 i; i < tokenIds.length; i++) {
require(loomiVault.ownerOf(tokenIds[i]) == a... | 0.8.7 |
/**
* @dev Function for loomi reward claim
* @notice caller must own a Genesis Creepz
*/ | function claim(uint256 tokenId) public nonReentrant whenNotPaused {
Staker storage user = _stakers[_msgSender()];
accumulate(_msgSender());
require(user.accumulatedAmount > 0, "Insufficient funds");
require(_validateCreepzOwner(tokenId, _msgSender()), "!Creepz owner");
uint256 currentLoo... | 0.8.7 |
/**
* @dev Helper function for arrays
*/ | function _moveTokenInTheList(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) {
uint256 tokenIndex = 0;
uint256 lastTokenIndex = list.length - 1;
uint256 length = list.length;
for(uint256 i = 0; i < length; i++) {
if (list[i] == tokenId) {
token... | 0.8.7 |
/**
* @dev Returns accumulated amount from last snapshot based on baseRate
*/ | function getCurrentReward(address staker) public view returns (uint256) {
Staker memory user = _stakers[staker];
if (user.lastCheckpoint == 0) { return 0; }
return (block.timestamp - user.lastCheckpoint) * (baseYield * user.stakedVault.length) / SECONDS_IN_DAY;
} | 0.8.7 |
/**
* @dev Function allows admin withdraw ERC721 in case of emergency.
*/ | function emergencyWithdraw(address tokenAddress, uint256[] memory tokenIds) public onlyOwner {
require(tokenIds.length <= 50, "50 is max per tx");
for (uint256 i; i < tokenIds.length; i++) {
address receiver = _ownerOfToken[tokenIds[i]];
if (receiver != address(0) && IERC721(tokenAddress).ow... | 0.8.7 |
/// @dev Emits an {Approval} event indicating the updated allowance. | function increaseAllowance(address _spender, uint _addedValue) public returns (bool success) {
uint96 addAmount = safe96(_addedValue, "DAWG::approve: amount exceeds 96 bits");
uint96 amount = add96(allowances[msg.sender][_spender], addAmount, "DAWG::increaseAllowance: increase allowance exceeds 96 bit... | 0.8.6 |
/**
* @notice Allows spender to `spender` on `owner`'s behalf
* @param owner address that holds tokens
* @param spender address that spends on `owner`'s behalf
* @param _amount unsigned integer denoting amount, uncast
* @param deadline The time at which to expire the signature
* @param v The recovery byte ... | function permit(address owner, address spender, uint _amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (_amount == uint(SafeCast.toUint256(-1))) {
amount = uint96(SafeCast.toUint256(-1));
} else {
amount = safe96(_amount, "DAWG::perm... | 0.8.6 |
//
// Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
// https://github.com/ProjectOpenSea/opensea-creatures/blob/master/contracts/ERC721Tradable.sol
// | function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool isOperator)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.pro... | 0.8.4 |
/// @dev Moves tokens `_amount` from `"sender"` to `"recipient"`
/// Emits a {Transfer} event | function _transfer(address _from, address _to, uint96 amount) internal {
require(_from != address(0), "ERC20: cannot transfer from the zero address");
require(_to != address(0), "ERC20: cannot transfer to the zero address");
balances[_from] = sub96(balances[_from], amount, "DAWG::_transferT... | 0.8.6 |
/// @dev Sets given `_amount` as the allowance of a `_spender` for the `_owner`'s tokens.
//// Emits a {Approval} event | function _approve(address _owner, address _spender, uint96 amount) internal {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
allowances[_owner][_spender] = amount;
emit Approval(_owner, _... | 0.8.6 |
//@dev this function allows purchase of ERC-20 tokens | function buyTokens(uint256 _numberOfTokens) external payable {
require(msg.value == _numberOfTokens.mul(tokenPrice));
uint256 numberOfTokens = _numberOfTokens.mul(10**(tokenContract.decimals()));
//@mul only to prevent overflow
require(tokenContract.totalSupply() >= numberOfTokens);
... | 0.4.25 |
/**
* Get random index
*/ | function randomIndex() internal returns (uint256) {
uint256 totalSize = MAX_TOKENS - numTokens;
uint256 index = uint256(
keccak256(
abi.encodePacked(
nonce,
msg.sender,
block.difficulty,
block.tim... | 0.8.4 |
/**
* Mint one token internal
*/ | function _internalMint(address to) private returns (uint256) {
require(numTokens < MAX_TOKENS, "Token limit");
//Get random token
uint256 id = randomIndex();
//Change internal token amount
numTokens++;
//Mint token
_mint(to, id);
return id;
} | 0.8.4 |
/**
* Mint selected amount of tokens
*/ | function mint(address _to, uint8 _amount) public payable {
require(mintEnabled, "Minting disabled");
require(_amount <= 20, "Maximum 20 tokens per mint");
require(msg.value >= _amount * tokenPrice, "Not enought money");
require(_to != address(0), "Cannot mint to empty");
_ensure... | 0.8.4 |
/**
* Mint selected amount of tokens to a given address by owner (airdrop)
*/ | function airdrop(address _to, uint8 _amount) public onlyOwner {
require(mintEnabled, "Minting disabled");
require(_amount <= 20, "Maximum 20 tokens per mint");
require(_to != address(0), "Cannot mint to empty");
for (uint8 i = 0; i < _amount; i++) {
// Mint token tok user
... | 0.8.4 |
/**
* @dev Mints a token to an address with a tokenURI.
* fee may or may not be required*
* @param _to address of the future owner of the token
*/ | function mintTo(address _to) public payable {
require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 2");
require(mintingOpen == true, "Minting is not open right now!");
require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints");
... | 0.8.9 |
// @notice Query if an address implements an interface and through which contract.
// @param _addr Address being queried for the implementer of an interface.
// (If '_addr' is the zero address then 'msg.sender' is assumed.)
// @param _interfaceHash Keccak256 hash of the name of the interface as a string.
// E.g., 'web3... | function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view override returns (address) {
address addr = _addr == address(0) ? msg.sender : _addr;
if (isERC165Interface(_interfaceHash)) {
bytes4 erc165InterfaceHash = bytes4(_interfaceHash);
return im... | 0.6.12 |
// @notice Sets the contract which implements a specific interface for an address.
// Only the manager defined for that address can set it.
// (Each address is the manager for itself until it sets a new manager.)
// @param _addr Address for which to set the interface.
// (If '_addr' is the zero address then 'msg.sender... | function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external override {
address addr = _addr == address(0) ? msg.sender : _addr;
require(getManager(addr) == msg.sender, "Not the manager");
require(!isERC165Interface(_interfaceHash), "Must not be an ... | 0.6.12 |
// @notice Get the manager of an address.
// @param _addr Address for which to return the manager.
// @return Address of the manager for a given address. | function getManager(address _addr) public view override returns(address) {
// By default the manager of an address is the same address
if (managers[_addr] == address(0)) {
return _addr;
} else {
return managers[_addr];
}
} | 0.6.12 |
// @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
// @param _contract Address of the contract to check.
// @param _interfaceId ERC165 interface to check.
// @return True if '_contract' implements '_interfaceId', false otherwise. | function implementsERC165InterfaceNoCache(address _contract, bytes4 _interfaceId) public view override returns (bool) {
uint256 success;
uint256 result;
(success, result) = noThrowCall(_contract, ERC165ID);
if (success == 0 || result == 0) {
return false;
}
... | 0.6.12 |
// @dev Make a call on a contract without throwing if the function does not exist. | function noThrowCall(address _contract, bytes4 _interfaceId)
internal view returns (uint256 success, uint256 result)
{
bytes4 erc165ID = ERC165ID;
assembly {
let x := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(x... | 0.6.12 |
// gets the amount of rew | function rewardPerToken(address _rewardToken)
internal
view
returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_)
{
RewardToken storage rewardToken = s.rewardTokens[_rewardToken];
uint256 l_totalSupply = s.totalSupply;
uint256 lastUpdateTime = rewardTok... | 0.8.10 |
/**
* @dev Stake ERC-1155
*/ | function stake(uint256[] calldata tokenIds, uint256[] calldata amounts) external nonReentrant whenNotPaused updateReward(msg.sender) {
require(tokenIds.length == amounts.length, "TokenIds and amounts length should be the same");
for(uint256 i = 0; i < tokenIds.length; i++) {
stakeInternal... | 0.6.12 |
/**
* @dev Stake particular ERC-1155 tokenId
*/ | function stakeInternal(uint256 tokenId, uint256 amount) internal {
(,,,,,uint256 series) = INodeRunnersNFT(address(NFT)).getFighter(tokenId);
if(!nftTokenMap[tokenId].hasValue) {
nftTokens.push(tokenId);
nftTokenMap[tokenId] = NftToken({ hasValue: true });
}
... | 0.6.12 |
/**
* @dev Withdraw ERC-1155
*/ | function withdrawNFT(uint256[] memory tokenIds, uint256[] memory amounts) public updateReward(msg.sender) {
require(tokenIds.length == amounts.length, "TokenIds and amounts length should be the same");
for(uint256 i = 0; i < tokenIds.length; i++) {
withdrawNFTInternal(tokenIds[i], amounts... | 0.6.12 |
/**
* @dev Withdraw particular ERC-1155 tokenId
*/ | function withdrawNFTInternal(uint256 tokenId, uint256 amount) internal {
(uint256 strength,,,,,) = INodeRunnersNFT(address(NFT)).getFighter(tokenId);
strength = strength.mul(amount);
strengthWeight[msg.sender] = strengthWeight[msg.sender].sub(strength);
_totalStrength = _totalStren... | 0.6.12 |
/**
* @dev Withdraw all cards
*/ | function withdraw() public updateReward(msg.sender) {
uint256[] memory tokenIds = new uint256[](nftTokens.length);
uint256[] memory amounts = new uint256[](nftTokens.length);
for (uint8 i = 0; i < nftTokens.length; i++) {
uint256 tokenId = nftTokens[i];
tokenIds[i] =... | 0.6.12 |
/// @dev uADPriceReset remove uAD unilateraly from the curve LP share sitting inside
/// the bonding contract and send the uAD received to the treasury.
/// This will have the immediate effect of pushing the uAD price HIGHER
/// @param amount of LP token to be removed for uAD
/// @notice it will remove one co... | function uADPriceReset(uint256 amount) external onlyBondingManager {
IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress());
// safe approve
IERC20(manager.stableSwapMetaPoolAddress()).safeApprove(
address(this),
amount
);
// remove one coin
... | 0.8.3 |
/// @dev crvPriceReset remove 3CRV unilateraly from the curve LP share sitting inside
/// the bonding contract and send the 3CRV received to the treasury
/// This will have the immediate effect of pushing the uAD price LOWER
/// @param amount of LP token to be removed for 3CRV tokens
/// @notice it will remov... | function crvPriceReset(uint256 amount) external onlyBondingManager {
IMetaPool metaPool = IMetaPool(manager.stableSwapMetaPoolAddress());
// safe approve
IERC20(manager.stableSwapMetaPoolAddress()).safeApprove(
address(this),
amount
);
// remove one coin
... | 0.8.3 |
/// @dev deposit uAD-3CRV LP tokens for a duration to receive bonding shares
/// @param _lpsAmount of LP token to send
/// @param _weeks during lp token will be held
/// @notice weeks act as a multiplier for the amount of bonding shares to be received | function deposit(uint256 _lpsAmount, uint256 _weeks)
public
returns (uint256 _id)
{
require(
1 <= _weeks && _weeks <= 208,
"Bonding: duration must be between 1 and 208 weeks"
);
_updateOracle();
IERC20(manager.stableSwapMetaPoolAddress()).safe... | 0.8.3 |
/// @dev withdraw an amount of uAD-3CRV LP tokens
/// @param _sharesAmount of bonding shares of type _id to be withdrawn
/// @param _id bonding shares id
/// @notice bonding shares are ERC1155 (aka NFT) because they have an expiration date | function withdraw(uint256 _sharesAmount, uint256 _id) public {
require(
block.number > _id,
"Bonding: Redeem not allowed before bonding time"
);
require(
IERC1155Ubiquity(manager.bondingShareAddress()).balanceOf(
msg.sender,
_i... | 0.8.3 |
//Custom Minting Function for utility (to be called by trusted contracts) | function mintCustomWarrior(address owner, uint32 generation, bool special, uint randomSeed, uint16 colorHue, uint8 armorType, uint8 shieldType, uint8 weaponType) public onlyTrustedContracts returns(uint theNewWarrior) {
//Calculate new Token ID for minting
uint256 _id = _getNextTokenID();
_incre... | 0.5.17 |
//Standard factory function, allowing minting warriors. | function newWarrior() public returns(uint theNewWarrior) {
//Generate a new random seed for the warrior
uint randomSeed = uint(blockhash(block.number - 1)); //YES WE KNOW this isn't truely random. it's predictable, and vulnerable to malicious miners...
... | 0.5.17 |
//// Secure payable fallback function - receives bets | function () external payable {
require((msg.value == oneBet) || (msg.sender == owner));
if (msg.sender != owner) {
require(betsState && !emergencyBlock);
require(!betsBlock);
if (numberOfBets < participants+(extraBets-1)) {
bets[numberOfBets] = m... | 0.4.22 |
//// Withdraw and distribute winnings | function withdrawWinnings() external payable
onlyProxy
{
if ((msg.value > expectedReturn) && !emergencyBlock) {
emit BetResult(roundID, 1, msg.value); // We won! Set 1
distributeWinnings(msg.value);
} else {
emit BetResult(roundID, 0, msg.value)... | 0.4.22 |
/**
* @dev Allows the transfer of token amounts to multiple addresses
* @param beneficiaries Array of addresses that receive the tokens
* @param amounts Array of amounts to be transferred per beneficiary
*/ | function multiTransfer(address[] calldata beneficiaries, uint256[] calldata amounts) external {
uint256 length = beneficiaries.length;
require(length == amounts.length, "lenghts are different");
for (uint256 i = 0; i < length; i++) {
super.transfer(beneficiaries[i], amounts[i])... | 0.5.10 |
// ========== RESTRICTED ========== | function setCrossDomainMessageGasLimit(CrossDomainMessageGasLimits _gasLimitType, uint _crossDomainMessageGasLimit)
external
onlyOwner
{
require(
_crossDomainMessageGasLimit >= MIN_CROSS_DOMAIN_GAS_LIMIT &&
_crossDomainMessageGasLimit <= MAX_CROSS_DOMAIN_GAS_LIMIT... | 0.5.16 |
/**
* @dev Returns the current implementation of `proxy`.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
*/ | function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = add... | 0.8.3 |
// Transfer the _amount from msg.sender to _to account | function transfer(address _to, uint256 _amount) public returns (bool) {
if (balances[msg.sender] >= _amount && _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _... | 0.4.17 |
// fallback function, Charon sells napkins as merchandise! | function () public payable {
uint256 amount;
uint256 checkedAmount;
// give away some napkins in return proportional to value
amount = msg.value / napkinPrice;
checkedAmount = checkAmount(amount);
// only payout napkins if there is the appropriate amount available
... | 0.4.17 |
// sells your soul for a given price and a given reason! | function sellSoul(string reason, uint256 price) public payable{
uint256 charonsObol;
string storage has_reason = reasons[msg.sender];
// require that user gives a reason
require(bytes(reason).length > 0);
// require to pay bookingFee
require(msg.value >= booking... | 0.4.17 |
// can transfer a soul to a different account, but beware you have to pay Charon again! | function transferSoul(address _to, address noSoulMate) public payable{
uint256 charonsObol;
// require correct ownership
require(ownedBy[noSoulMate] == msg.sender);
require(soulsOwned[_to] + 1 > soulsOwned[_to]);
// require transfer fee is payed again
charonsObol ... | 0.4.17 |
// transfers napkins to people | function payOutNapkins(uint256 amount) internal{
// check for amount and wrap around
require(amount > 0);
// yeah some sanity check
require(amount <= balances[this]);
// send napkins from contract to msg.sender
balances[this] -= amount;
balances[msg.sende... | 0.4.17 |
/**
* @notice Extract a bytes32 from a bytes.
* @param data bytes from where the bytes32 will be extract
* @param offset position of the first byte of the bytes32
* @return address
*/ | function extractBytes32(bytes memory data, uint offset)
internal
pure
returns (bytes32 bs)
{
require(offset >= 0 && offset + 32 <= data.length, "offset value should be in the correct range");
// solium-disable-next-line security/no-inline-assembly
assembly {
bs := mload(add(d... | 0.5.0 |
/**
* @notice Computes the fees.
* @param _contentSize Size of the content of the block to be stored
* @return the expected amount of fees in wei
*/ | function getFeesAmount(uint256 _contentSize)
public
view
returns(uint256)
{
// Transactions fee
uint256 computedAllFee = _contentSize.mul(rateFeesNumerator);
if (rateFeesDenominator != 0) {
computedAllFee = computedAllFee.div(rateFeesDenominator);
}
if (computedAllF... | 0.5.0 |
/**
* @notice Submit a new hash to the blockchain.
*
* @param _hash Hash of the request to be stored
* @param _feesParameters fees parameters used to compute the fees. Here, it is the content size in an uint256
*/ | function submitHash(string calldata _hash, bytes calldata _feesParameters)
external
payable
{
// extract the contentSize from the _feesParameters
uint256 contentSize = uint256(Bytes.extractBytes32(_feesParameters, 0));
// Check fees are paid
require(getFeesAmount(contentSize) == msg.v... | 0.5.0 |
// compressBoard removes last col and last row and joins digits into one number. | function compressBoard(uint[81] _b) constant returns (uint) {
uint cb = 0;
uint mul = 1000000000000000000000000000000000000000000000000000000000000000;
for (uint i = 0; i < 72; i++) {
if (i % 9 == 8) {
continue;
}
cb = cb + mul * _b[i];
mul = mul / 10;
}
ret... | 0.4.13 |
/**
* @dev Add Account to User Linked List.
* @param _owner Account Owner.
* @param _account Smart Account Address.
*/ | function addAccount(address _owner, uint64 _account) internal {
if (userLink[_owner].last != 0) {
userList[_owner][_account].prev = userLink[_owner].last;
userList[_owner][userLink[_owner].last].next = _account;
}
if (userLink[_owner].first == 0) userLink[_owner].fir... | 0.6.0 |
/**
* @dev Remove Account from User Linked List.
* @param _owner Account Owner/User.
* @param _account Smart Account Address.
*/ | function removeAccount(address _owner, uint64 _account) internal {
uint64 _prev = userList[_owner][_account].prev;
uint64 _next = userList[_owner][_account].next;
if (_prev != 0) userList[_owner][_prev].next = _next;
if (_next != 0) userList[_owner][_next].prev = _prev;
if (... | 0.6.0 |
/**
* @dev Remove Owner from Account Linked List.
* @param _owner Account Owner.
* @param _account Smart Account Address.
*/ | function removeUser(address _owner, uint64 _account) internal {
address _prev = accountList[_account][_owner].prev;
address _next = accountList[_account][_owner].next;
if (_prev != address(0)) accountList[_account][_prev].next = _next;
if (_next != address(0)) accountList[_account][_... | 0.6.0 |
// Function to mint new NFTs during the presale | function mintDuringPresale(uint256 _numOfTokens) public payable whenNotPaused nonReentrant {
require(isPreSaleActive==true, "Presale Not Active");
if(checkWhitelist==true) {
require(presaleAccess[msg.sender] == true, "Presale Access Denied");
}
require(presaleClaimed[msg... | 0.8.4 |
// Function to mint new NFTs during the public sale | function mint(uint256 _numOfTokens) public payable whenNotPaused nonReentrant {
require(isMainSaleActive==true, "Sale Not Active");
require(mainSaleClaimed[msg.sender].add(_numOfTokens) <= MAINSALE_PURCHASE_LIMIT,
"Above Main Sale Purchase Limit");
require(publicTotalSupply.add(... | 0.8.4 |
// Function to check charity and treasury distribution | function checkDistribution(uint256 _numOfTokens) internal {
if (publicTotalSupply < PUBLIC_NFT && publicTotalSupply.add(_numOfTokens) >= PUBLIC_NFT) {
payable(communityTreasury).transfer(15 ether);
payable(charity).transfer(12 ether);
} else if (publicTotalSupply < 3675 && p... | 0.8.4 |
/**
* Reserve some GALAs for marketing and giveaway purpose.
*/ | function reserveGiveaway(uint256 quantity) external onlyOwner {
SaleConfig memory config = saleConfig;
bool _publicSaleStarted = config.publicSaleStarted;
bool _wlSaleStarted = config.wlSaleStarted;
uint _reserved = config.reservedAmount;
// the sale must not be started
... | 0.8.1 |
// mint a tx from clover to bsc chain
// note here we use the blockNumber + txIndex instead of txHash to identify the transaction
// because tx hash is not guarantee to be unique in substrate based chains.
// refer to: https://wiki.polkadot.network/docs/en/build-protocol-info#unique-identifiers-for-extrinsics | function mintTx(
uint32 blockNumber,
uint32 txIndex,
address dest,
uint256 amount
) public returns (bool) {
require(
hasRole(BRIDGE_ROLE, _msgSender()),
"CloverBridge: must have bridge role"
);
require(dest != address(0), "SakuraBridge:... | 0.8.0 |
/*
function selleth(uint amount) public payable {
//address user = msg.sender;
//canOf[user] = myuseOf(user);
//require(balances[user] >= amount );
//uint money = amount * sellPrice;
// balances[msg.sender] += money;
owner.transfer(amount);
}*/ | function sell(uint256 amount) public returns(bool success) {
//address user = msg.sender;
//canOf[msg.sender] = myuseOf(msg.sender);
//require(!frozenAccount[msg.sender]);
uint256 canuse = getcanuse(msg.sender);
require(canuse >= amount);
uint moneys = amount / sellPrice;
require(msg.sender.send(mo... | 0.4.24 |
/**
* Multiplication with safety check
*/ | function Mul(uint a, uint b) constant internal returns (uint) {
uint c = a * b;
//check result should not be other wise until a=0
assert(a == 0 || c / a == b);
return c;
} | 0.4.13 |
/**
* Division with safety check
*/ | function Div(uint a, uint b) constant internal returns (uint) {
//overflow check; b must not be 0
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
} | 0.4.13 |
/**
* Subtraction with safety check
*/ | function Sub(uint a, uint b) constant internal returns (uint) {
//b must be greater that a as we need to store value in unsigned integer
assert(b <= a);
return a - b;
} | 0.4.13 |
/**
* Addition with safety check
*/ | function Add(uint a, uint b) constant internal returns (uint) {
uint c = a + b;
//result must be greater as a or b can not be negative
assert(c>=a && c>=b);
return c;
} | 0.4.13 |
//Contructor to define EXH Token token properties | function EXH() public {
// lock the transfer function during Sale
locked = true;
//initial token supply is 0
totalSupply = 0;
//Name for token set to EXH Token
name = 'EXH Token';
// Symbol for token set to 'EXH'
symbol = 'EXH';
decimals = 18;
} | 0.4.13 |
//Implementation for transferring EXH Token to provided address | function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public onlyUnlocked returns (bool){
//Check provided EXH Token should not be 0
if (_value > 0 && !(_to == address(0))) {
//deduct EXH Token amount from transaction initiator
balances[msg.sender] = balances[msg.sender].Sub(_val... | 0.4.13 |
//Transfer initiated by spender | function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) public onlyUnlocked returns (bool) {
//Check provided EXH Token should not be 0
if (_value > 0 && (_to != address(0) && _from != address(0))) {
//Get amount of EXH Token for which spender is authorized
var _... | 0.4.13 |
/*
* To start Sale from Presale
*/ | function start() public onlyOwner {
//Set block number to current block number
assert(startBlock == 0);
startBlock = now;
//Set end block number
endBlock = now.Add(durationCrowdSale.Add(durationPreSale));
//Sale presale is started
crowdsaleStatus = 1;
//Emit event whe... | 0.4.13 |
/*
* To start Crowdsale
*/ | function startSale() public onlyOwner
{
if(now > startBlock.Add(durationPreSale) && now <= endBlock){
crowdsaleStatus = 1;
crowdSaleType = 1;
if(crowdSaleType != 1)
{
totalSupplyCrowdsale = totalSupplyPreSale;
}
//Emit event when crowdsale state c... | 0.4.13 |
/*
* To extend duration of Crowdsale
*/ | function updateDuration(uint time) public onlyOwner
{
require(time != 0);
assert(startBlock != 0);
assert(crowdSaleType == 1 && crowdsaleStatus != 2);
durationCrowdSale = durationCrowdSale.Add(time);
endBlock = endBlock.Add(time);
//Emit event when crowdsale state changes
... | 0.4.13 |
/*
* To enable vesting of B type EXH Token
*/ | function MintAndTransferToken(address beneficiary,uint exhToCredit,bytes32 comment) external onlyOwner {
//Available after the crowdsale is started
assert(startBlock != 0);
//Check whether tokens are available or not
assert(totalSupplyMintTransfer <= maxCapMintTransfer);
//Check whether the amo... | 0.4.13 |
/*
* To get price for EXH Token
*/ | function getPrice() public constant returns (uint result) {
if (crowdSaleType == 0) {
return (PRICE.Mul(100)).Div(70);
}
if (crowdSaleType == 1) {
uint crowdsalePriceBracket = 1 weeks;
uint startCrowdsale = startBlock.Add(durationPreSale);
if (now > s... | 0.4.13 |
/*
* Finalize the crowdsale
*/ | function finalize() public onlyOwner {
//Make sure Sale is running
assert(crowdsaleStatus==1 && crowdSaleType==1);
// cannot finalise before end or until maxcap is reached
assert(!((totalSupplyCrowdsale < maxCap && now < endBlock) && (maxCap.Sub(totalSupplyCrowdsale) >= valueOneEther)));
... | 0.4.13 |
/*
* Refund the investors in case target of crowdsale not achieved
*/ | function refund() public onlyOwner {
assert(refundStatus == 2);
uint batchSize = countInvestorsRefunded.Add(50) < countTotalInvestors ? countInvestorsRefunded.Add(50): countTotalInvestors;
for(uint i=countInvestorsRefunded.Add(1); i <= batchSize; i++){
address investorAddress = investorL... | 0.4.13 |
// ------------------------------------------------------------------------
// Allocate a particular amount of tokens from onwer to an account
// ------------------------------------------------------------------------ | function allocate(address to, uint amount) public onlyOwner {
require(to != address(0));
require(!frozenAccount[to]);
require(!halted && amount > 0);
require(balances[owner] >= amount);
balances[owner] = balances[owner].sub(amount);
balances[to] = balances[to].add... | 0.4.24 |
// calculation of the percentage of profit depending on the balance sheet
// returns the percentage times 10 | function calculateProfitPercent(uint bal) private pure returns (uint) {
if (bal >= 1e22) { // balance >= 10000 ETH
return 50;
}
if (bal >= 7e21) { // balance >= 7000 ETH
return 47;
}
if (bal >= 5e21) { // balance >= 5000 ETH
return 45;
... | 0.4.23 |
// transfer default refback and referrer percents of invested | function transferRefPercents(uint value, address sender) private {
if (msg.data.length != 0) {
address referrer = bytesToAddress(msg.data);
if(referrer != sender) {
sender.transfer(value * refBack / 100);
referrer.transfer(value * refPercent / 100);
... | 0.4.23 |
// calculate profit amount as such:
// amount = (amount invested) * ((percent * 10)/ 1000) * (blocks since last transaction) / 6100
// percent is multiplied by 10 to calculate fractional percentages and then divided by 1000 instead of 100
// 6100 is an average block count per day produced by Ethereum blockchain | function () external payable {
if (invested[msg.sender] != 0) {
uint thisBalance = address(this).balance;
uint amount = invested[msg.sender] * calculateProfitPercent(thisBalance) / 1000 * (block.number - atBlock[msg.sender]) / 6100;
address sender = msg.se... | 0.4.23 |
/* Listing */ | function populateFromItemRegistry (uint256[] _itemIds) onlyOwner() public {
for (uint256 i = 0; i < _itemIds.length; i++) {
if (priceOfItem[_itemIds[i]] > 0 || itemRegistry.priceOf(_itemIds[i]) == 0) {
continue;
}
listItemFromRegistry(_itemIds[i]);
}
} | 0.4.20 |
/*
Buy a country directly from the contract for the calculated price
which ensures that the owner gets a profit. All countries that
have been listed can be bought by this method. User funds are sent
directly to the previous owner and are never stored in the contract.
*/ | function buy (uint256 _itemId) payable public {
require(priceOf(_itemId) > 0);
require(ownerOf(_itemId) != address(0));
require(msg.value >= priceOf(_itemId));
require(ownerOf(_itemId) != msg.sender);
require(!isContract(msg.sender));
require(msg.sender != address(0));
address oldOw... | 0.4.20 |
/// @dev Creates a new pool. | function createPool(IERC20 _token, bool _needVesting, uint256 _vestingDurationInSecs, uint256 _depositLockPeriodInSecs) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(Pool.Data({
... | 0.6.10 |
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
/// @param referral the address of referral. | function deposit(uint256 _poolId, uint256 _depositAmount, address referral) external nonReentrant checkIfNewReferral(_poolId, referral) {
require(_depositAmount > 0, "zero deposit");
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender... | 0.6.10 |
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw. | function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
require(_withdrawAmount > 0, "to withdraw zero");
uint256 withdrawAbleAmount = getWithdrawableAmount(_poolId, msg.sender);
require(withdrawAbleAmount >= _withdrawAmount, "amount exceeds withdrawAble");
Pool.Data st... | 0.6.10 |
/// @dev Claims all rewards from a pool and then withdraws all withdrawAble tokens.
///
/// @param _poolId the pool to exit from. | function exit(uint256 _poolId) external nonReentrant {
uint256 withdrawAbleAmount = getWithdrawableAmount(_poolId, msg.sender);
require(withdrawAbleAmount > 0, "all deposited still locked");
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stak... | 0.6.10 |
/// @dev To get withdrawable amount that has passed lockup period of a pool | function getWithdrawableAmount(uint256 _poolId, address _account) public view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[_account][_poolId];
uint256 withdrawAble = 0;
for (uint32 i = 0; i < _stake.deposits.length; i++) {
uint256 un... | 0.6.10 |
/**
* @dev Return the URI of the NFT
* @notice return the hidden URI then the Revealed JSON when the Revealed param is true
*/ | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token");
if(_revealed == false) {
return _hideURI;
}
string memory URI = _baseURI();
return bytes(URI).length > 0 ? string... | 0.8.1 |
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
/// @param _referral The referral's address for reducing re... | function _withdraw(uint256 _poolId, uint256 _withdrawAmount, address _referral) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.total... | 0.6.10 |
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID. | function _claim(uint256 _poolId) internal {
require(!pause, "StakingPools: emergency pause enabled");
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
if(_... | 0.6.10 |
/// @dev To update a pool's lockup period.
///
/// Update a pool's lockup period will affect all current deposits. i.e. if set lock up period to 0, will
/// unlock all current desposits. | function setPoolLockUpPeriodInSecs(uint256 _poolId, uint256 _newLockUpPeriodInSecs) external {
require(msg.sender == governance || msg.sender == sentinel, "StakingPools: !(gov || sentinel)");
Pool.Data storage _pool = _pools.get(_poolId);
uint256 oldLockUpPeriodInSecs = _pool.lockUpPeriodInSecs;
_... | 0.6.10 |
/// @dev to change a pool's reward vesting period.
///
/// Change a pool's reward vesting period. Reward already in vesting schedule won't be affected by this update. | function setPoolVestingDurationInSecs(uint256 _poolId, uint256 _newVestingDurationInSecs) external {
require(msg.sender == governance || msg.sender == sentinel, "StakingPools: !(gov || sentinel)");
Pool.Data storage _pool = _pools.get(_poolId);
uint256 oldVestingDurationInSecs = _pool.vestingDurationInS... | 0.6.10 |
/// @dev To start referral power calculation for a pool, referral power caculation won't turn on if the onReferralBonus is not set
///
/// @param _poolId the pool to start referral power accumulation | function startReferralBonus(uint256 _poolId) external {
require(msg.sender == governance || msg.sender == sentinel, "startReferralBonus: !(gov || sentinel)");
Pool.Data storage _pool = _pools.get(_poolId);
require(_pool.onReferralBonus == false, "referral bonus already on");
_pool.onReferral... | 0.6.10 |
/**
* Set team tokens.
*
* Security review
*
* - Integer math: ok - only called once with fixed parameters
*
* Applicable tests:
*
* - Test founder token allocation too early
* - Test founder token allocation on time
* - Test founder token allocation twice
*
*/ | function allocateTeamTokens() onlyOwner public returns (bool success){
require( (startBlock + teamLockup) > block.number); // Check if it is time to allocate team tokens
require(!teamAllocated);
//check if team tokens have already been allocated
balanceOf[msg.sender] = balan... | 0.4.18 |
/*
* Verifies the inclusion of a leaf in a Merkle tree using a Merkle proof.
*
* Based on https://github.com/ameensol/merkle-tree-solidity/src/MerkleProof.sol
*/ | function checkProof(bytes memory proof, bytes32 root, bytes32 leaf) public pure returns (bool) {
if (proof.length % 32 != 0) return false; // Check if proof is made of bytes32 slices
bytes memory elements = proof;
bytes32 element;
bytes32 hash = leaf;
for (uint i = 32; i <= proof.length; i += 32) {... | 0.5.3 |
/** Adds an allowed deployer. */ | function addAllowedDeployer(address newDeployer) external {
// Reentrancy guard.
require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);
require(msg.sender == _owner, "Not owner");
require(!_allowedDeployersMap[newDeployer], "Already allowed");
// Add the... | 0.6.12 |
/** Removes an allowed deployer by index. We require the index for no-traversal removal against a known address. */ | function removeAllowedDeployer(address deployerAddress, uint256 index) external {
// Reentrancy guard.
require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);
require(msg.sender == _owner, "Not owner");
require(index < _allowedDeployersList.length, "Out of bounds"... | 0.6.12 |
/** The proxy address is what the Goald deployers send their fees to. */ | function setProxyAddress(address newAddress) external {
// Reentrancy guard.
require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);
require(msg.sender == _owner, "Not owner");
require(newAddress != address(0), "Can't be zero address");
require(IGoaldProxy(newAddress... | 0.6.12 |
/** The uniswap router for converting tokens within this proxys. */ | function setUniswapRouterAddress(address newAddress) external {
// Reentrancy guard.
require(_status == RE_NOT_ENTERED || _status == RE_FROZEN);
require(msg.sender == _owner, "Not owner");
require(newAddress != address(0), "Can't be zero address");
_uniswapRouterAddres... | 0.6.12 |
/** Return the metadata for a specific Goald. */ | function getTokenURI(uint256 tokenId) external view returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
uint256 temp = tokenId;
uint256 d... | 0.6.12 |
/** Updates the owner of a deployed Goald. */ | function setGoaldOwner(uint256 id) external {
// Reentrancy guard.
require(_status == RE_NOT_ENTERED);
_status = RE_ENTERED;
// Id is offset by one of the index
id --;
require(id < _deployedGoalds.length, "Invalid id");
// We don't have the address as a... | 0.6.12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.