comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
/**
* Execute token withdrawal into specified recipient address from specified member account
* @dev It is up to the sidechain implementation to make sure
* @dev always token balance >= sum of earnings - sum of withdrawn
*/
|
function withdrawTo(address recipient, address account, uint amount) public {
require(amount > 0, "error_zeroWithdraw");
uint w = withdrawn[account].add(amount);
require(w <= earnings[account], "error_overdraft");
withdrawn[account] = w;
totalWithdrawn = totalWithdrawn.add(amount);
require(token.transfer(recipient, amount), "error_transfer");
}
|
0.4.24
|
/// Requires the amount of Ether be at least or more of the currentPrice
/// @dev Creates an instance of an token and mints it to the purchaser
/// @param _tokenIdList The token identification as an integer
/// @param _tokenOwner owner of the token
|
function createToken (uint256[] _tokenIdList, address _tokenOwner) external payable onlyOwner{
uint256 _tokenId;
for (uint8 tokenNum=0; tokenNum < _tokenIdList.length; tokenNum++){
_tokenId = _tokenIdList[tokenNum];
NFTtoken memory _NFTtoken = NFTtoken({
attribute: "",
birthTime: uint64(now)
});
isNFTAlive[_tokenId] = true;
tokdenIdToNFTindex[_tokenId] = allNFTtokens.length;
allNFTtokens.push(_NFTtoken);
_mint(_tokenOwner, _tokenId);
emit BoughtToken(_tokenOwner, _tokenId);
}
}
|
0.4.24
|
/**
* Sends Bondf Fund ether to the bond contract
*
*/
|
function payFund() payable public
onlyAdministrator()
{
uint256 _bondEthToPay = 0;
uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
require(ethToPay > 1);
uint256 altEthToPay = SafeMath.div(SafeMath.mul(ethToPay,altFundFee_),100);
if (altFundFee_ > 0){
_bondEthToPay = SafeMath.sub(ethToPay,altEthToPay);
} else{
_bondEthToPay = 0;
}
totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay);
if(!bondFundAddress.call.value(_bondEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _bondEthToPay);
}
if(altEthToPay > 0){
if(!altFundAddress.call.value(altEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, altEthToPay);
}
}
}
|
0.4.24
|
/**
* Transfer tokens from the caller to a new holder.
* REMEMBER THIS IS 0% TRANSFER FEE
*/
|
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
|
0.4.24
|
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
|
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true); // security check that contract approved by Wall Street Exchange platform
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsExchange receiver = AcceptsExchange(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
|
0.4.24
|
/**
* Additional check that the game address we are sending tokens to is a contract
* assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*/
|
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
|
0.4.24
|
// Make sure we will send back excess if user sends more then 5 ether before 10 ETH in contract
|
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()// no contracts allowed
internal
returns(uint256) {
uint256 purchaseEthereum = _incomingEthereum;
uint256 excess;
if(purchaseEthereum > 2.5 ether) { // check if the transaction is over 2.5 ether
if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 10 ether) { // if so check the contract is less then 100 ether
purchaseEthereum = 2.5 ether;
excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);
}
}
purchaseTokens(purchaseEthereum, _referredBy);
if (excess > 0) {
msg.sender.transfer(excess);
}
}
|
0.4.24
|
//onlyDelegates
|
function mintTo(uint[] calldata quantity, address[] calldata recipient, TOKEN_TYPES _tokenType) external payable onlyDelegates {
require(quantity.length == recipient.length, "Must provide equal quantities and recipients" );
uint totalQuantity = 0;
for(uint i = 0; i < quantity.length; i++){
totalQuantity += quantity[i];
}
require( amountSold + totalQuantity <= MAX_SUPPLY, "Mint/order exceeds supply" );
delete totalQuantity;
for(uint i = 0; i < recipient.length; i++) {
for(uint j = 0; j < quantity[i]; j++) {
tokenContract.mint(recipient[i], _tokenType);
}
}
}
|
0.8.4
|
//onlyOwner
|
function setMaxSupply(uint maxSupply) external onlyOwner {
require( MAX_SUPPLY != maxSupply, "New value matches old" );
require( maxSupply >= amountSold, "Specified supply is lower than current balance" );
MAX_SUPPLY = maxSupply;
}
|
0.8.4
|
/**
* @dev calculates total amounts must be rewarded and transfers XCAD to the address
*/
|
function getReward() public {
uint256 _earned = earned(msg.sender);
require(_earned <= rewards[msg.sender], "RewardPayout: earned is more than reward!");
require(_earned > payouts[msg.sender], "RewardPayout: earned is less or equal to already paid!");
uint256 reward = _earned.sub(payouts[msg.sender]);
if (reward > 0) {
payouts[msg.sender] = _earned;
xcadToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
|
0.8.4
|
//------------------------- STRING MANIPULATION --------------------------
|
function trimStr(uint256 maxLength, string calldata str) internal pure returns( string memory ) {
bytes memory strBytes = bytes(str);
if (strBytes.length < maxLength) {
return str;
} else {
// Trim down to max length
bytes memory trimmed = new bytes(maxLength);
for(uint256 i = 0; i < maxLength; i++) {
trimmed[i] = strBytes[i];
}
return string(trimmed);
}
}
|
0.8.7
|
//------------------------- MESSAGES --------------------------
|
function setMsgSingleDigit(string calldata leaderMsg) external {
require(bytes(leaderMsg).length > 0, "You cannot set an empty message.");
require(msg.sender == topSingleDigitHolder(), "You are not the leading owner of single-digit mint numbers.");
msgSingleDigit = trimStr( MAX_MSG_LENGTH, leaderMsg );
emit singleDigitLeaderMsgSet(msg.sender, leaderMsg);
}
|
0.8.7
|
// ------------------------------------------------------------------------
// _to The address that will receive the minted tokens.
// _amount The amount of tokens to mint.
// A boolean that indicates if the operation was successful.
// ------------------------------------------------------------------------
|
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
require(_to != address(0));
require(_amount > 0);
uint newamount = _amount * 10**uint(decimals);
_totalSupply = _totalSupply.add(newamount);
balances[_to] = balances[_to].add(newamount);
emit Mint(_to, newamount);
emit Transfer(address(0), _to, newamount);
return true;
}
|
0.4.26
|
/**
* @dev Validate a multihash bytes value
*/
|
function isValidIPFSMultihash(bytes _multihashBytes) internal pure returns (bool) {
require(_multihashBytes.length > 2);
uint8 _size;
// There isn't another way to extract only this byte into a uint8
// solhint-disable no-inline-assembly
assembly {
// Seek forward 33 bytes beyond the solidity length value and the hash function byte
_size := byte(0, mload(add(_multihashBytes, 33)))
}
return (_multihashBytes.length == _size + 2);
}
|
0.4.18
|
/**
* @dev Cast or change your vote
* @param _choice The index of the option in the corresponding IPFS document.
*/
|
function vote(uint16 _choice) public duringPoll {
// Choices are indexed from 1 since the mapping returns 0 for "no vote cast"
require(_choice <= numChoices && _choice > 0);
votes[msg.sender] = _choice;
VoteCast(msg.sender, _choice);
}
|
0.4.18
|
// via https://stackoverflow.com/a/65707309/424107
// @dev credit again to the blitmap contract
|
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
|
0.8.0
|
// owner to claim keycards
|
function ownerClaim(uint256 num) external nonReentrant onlyOwner {
require( _tokenIdCounter.current() + num <= _maxSupply, "max supply reached" );
for (uint i = 0; i < num; i++) {
_safeMint(owner(), _tokenIdCounter.current() + 1);
_tokenIdCounter.increment();
}
}
|
0.8.7
|
// ============ For Owner ============
|
function grant(address[] calldata holderList, uint256[] calldata amountList)
external
onlyOwner
{
require(holderList.length == amountList.length, "batch grant length not match");
uint256 amount = 0;
for (uint256 i = 0; i < holderList.length; ++i) {
// for saving gas, no event for grant
originBalances[holderList[i]] = originBalances[holderList[i]].add(amountList[i]);
amount = amount.add(amountList[i]);
}
_UNDISTRIBUTED_AMOUNT_ = _UNDISTRIBUTED_AMOUNT_.sub(amount);
}
|
0.6.9
|
// get a linked keycard from tokenId
|
function getAssetLink1(uint256 tokenId) private pure returns (uint256) {
if (tokenId > 1) {
uint256 rand = random("link1", tokenId);
if (rand % 99 < 70)
return rand % (tokenId - 1) + 1;
else
return 0;
} else {
return 0;
}
}
|
0.8.7
|
// (^_^) Business Logic (^_^)
|
function claimReserved(uint _amount) external onlyAdmin {
require(_amount > 0, "Error: Need to have reserved supply.");
require(accounts[msg.sender].isAdmin == true,"Error: Only an admin can claim.");
require(accounts[msg.sender].nftsReserved >= _amount, "Error: You are trying to claim more NFTs than you have reserved.");
require(totalSupply() + _amount <= MAXSUPPLY, "Error: You would exceed the max supply limit.");
accounts[msg.sender].nftsReserved -= _amount;
_reserved = _reserved - _amount;
for (uint i = 0; i < _amount; i++) {
id++;
_safeMint(msg.sender, id);
emit Mint(msg.sender, totalSupply());
}
}
|
0.8.2
|
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
|
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _becomeImplementation");
}
|
0.5.17
|
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
|
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _resignImplementation");
}
|
0.5.17
|
// -- Internal Helper functions -- //
|
function _getMarketIdFromTokenAddress(address _solo, address token)
internal
view
returns (uint256)
{
ISoloMargin solo = ISoloMargin(_solo);
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("No marketId found for provided token");
}
|
0.7.4
|
/**
* @dev Allows the current owner to update multiple rates.
* @param data an array that alternates sha3 hashes of the symbol and the corresponding rate .
*/
|
function updateRates(uint[] data) public onlyOwner {
if (data.length % 2 > 0)
throw;
uint i = 0;
while (i < data.length / 2) {
bytes32 symbol = bytes32(data[i * 2]);
uint rate = data[i * 2 + 1];
rates[symbol] = rate;
RateUpdated(now, symbol, rate);
i++;
}
}
|
0.4.11
|
// get a 2nd linked keycard from tokenId
|
function getAssetLink2(uint256 tokenId) private pure returns (uint256) {
uint256 rand = random("link2", tokenId);
uint256 link2Id = rand % (tokenId - 1) + 1;
if (link2Id == getAssetLink1(tokenId)){
return 0;
} else {
if (rand % 99 < 50)
return link2Id;
else
return 0;
}
}
|
0.8.7
|
// generate metadata for links
|
function getAssetLinks(uint256 tokenId) private pure returns (string memory) {
string memory traitTypeJson = ', {"trait_type": "Linked", "value": "';
if (getAssetLink1(tokenId) < 1)
return '';
if (getAssetLink2(tokenId) > 0) {
return string(abi.encodePacked(traitTypeJson, '2 Rooms"}'));
} else {
return string(abi.encodePacked(traitTypeJson, '1 Room"}'));
}
}
|
0.8.7
|
// get a random gradient color from tokenId
|
function getBackgrounGradient(uint256 tokenId) private pure returns (string memory) {
uint256 colorSeed = random("color", tokenId);
if ( colorSeed % 7 == 3)
return "black;red;gray;red;purple;black;";
if ( colorSeed % 7 == 2)
return "black;green;black;";
if ( colorSeed % 7 == 1)
return "black;blue;black;";
if ( colorSeed % 7 == 4)
return "black;lightblue;black;";
if ( colorSeed % 7 == 5)
return "black;red;purple;blue;black;";
if ( colorSeed % 7 == 6)
return "black;blue;purple;blue;black;";
return "black;gray;red;purple;black;";
}
|
0.8.7
|
/** Set `_owner` to the 0 address.
* Only do this to deliberately lock in the current permissions.
*
* THIS CANNOT BE UNDONE! Call this only if you know what you're doing and why you're doing it!
*/
|
function renounceOwnership(string calldata declaration) external onlyOwner {
string memory requiredDeclaration = "I hereby renounce ownership of this contract forever.";
require(
keccak256(abi.encodePacked(declaration)) ==
keccak256(abi.encodePacked(requiredDeclaration)),
"declaration incorrect");
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
|
0.5.7
|
/// Mint `value` new attotokens to `account`.
|
function mint(address account, uint256 value)
external
notPaused
only(minter)
{
require(account != address(0), "can't mint to address zero");
totalSupply = totalSupply.add(value);
require(totalSupply < maxSupply, "max supply exceeded");
trustedData.addBalance(account, value);
emit Transfer(address(0), account, value);
}
|
0.5.7
|
/// @dev Transfer of `value` attotokens from `from` to `to`.
/// Internal; doesn't check permissions.
|
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0), "can't transfer to address zero");
trustedData.subBalance(from, value);
uint256 fee = 0;
if (address(trustedTxFee) != address(0)) {
fee = trustedTxFee.calculateFee(from, to, value);
require(fee <= value, "transaction fee out of bounds");
trustedData.addBalance(feeRecipient, fee);
emit Transfer(from, feeRecipient, fee);
}
trustedData.addBalance(to, value.sub(fee));
emit Transfer(from, to, value.sub(fee));
}
|
0.5.7
|
/// @dev Set `spender`'s allowance on `holder`'s tokens to `value` attotokens.
/// Internal; doesn't check permissions.
|
function _approve(address holder, address spender, uint256 value) internal {
require(spender != address(0), "spender cannot be address zero");
require(holder != address(0), "holder cannot be address zero");
trustedData.setAllowed(holder, spender, value);
emit Approval(holder, spender, value);
}
|
0.5.7
|
/// Accept upgrade from previous RSV instance. Can only be called once.
|
function acceptUpgrade(address previousImplementation) external onlyOwner {
require(address(trustedData) == address(0), "can only be run once");
Reserve previous = Reserve(previousImplementation);
trustedData = ReserveEternalStorage(previous.getEternalStorageAddress());
// Copy values from old contract
totalSupply = previous.totalSupply();
maxSupply = previous.maxSupply();
emit MaxSupplyChanged(maxSupply);
// Unpause.
paused = false;
emit Unpaused(pauser);
previous.acceptOwnership();
// Take control of Eternal Storage.
previous.changePauser(address(this));
previous.pause();
previous.transferEternalStorage(address(this));
// Burn the bridge behind us.
previous.changeMinter(address(0));
previous.changePauser(address(0));
previous.renounceOwnership("I hereby renounce ownership of this contract forever.");
}
|
0.5.7
|
// Verify the signature for the given payload is valid
|
function verifySignature(
address _wallet,
uint256 _amount,
uint256 _dropId,
uint256 _tokenId,
bytes memory signature
) public view returns (bool) {
bytes32 messageHash = hashPayload(_wallet, _amount, _dropId, _tokenId);
return messageHash.toEthSignedMessageHash().recover(signature) == signer;
}
|
0.8.4
|
// Payable function to receive funds and emit event to indicate successful purchase
|
function purchase(
address _wallet,
uint256 _amount,
uint256 _dropId,
uint256 _tokenId,
bytes memory signature
) public payable {
require(verifySignature(_wallet, _amount, _dropId, _tokenId, signature));
require(msg.value == _amount, "Amount received does not match expected transfer amount");
require(!tokenClaimed[_tokenId], "Token has already been claimed");
tokenClaimed[_tokenId] = true;
emit Purchase(_wallet, _amount, _dropId, _tokenId);
}
|
0.8.4
|
// generate metadata for lasers
|
function haveLaser(uint256 tokenId) private pure returns (string memory) {
uint256 laserSeed = random("laser", tokenId);
string memory traitTypeJson = ', {"trait_type": "Laser", "value": "';
if (laserSeed % 251 == 2)
return string(abi.encodePacked(traitTypeJson, 'Dual Green Lasers"}'));
if (laserSeed % 167 == 2)
return string(abi.encodePacked(traitTypeJson, 'Dual Red Lasers"}'));
if (laserSeed % 71 == 2)
return string(abi.encodePacked(traitTypeJson, 'Green Laser"}'));
if (laserSeed % 31 == 2)
return string(abi.encodePacked(traitTypeJson, 'Red Laser"}'));
return '';
}
|
0.8.7
|
// generate basic attributes in metadata
|
function haveBasicAttributes(uint256 tokenId) private view returns (string memory) {
string memory traitTypeJson = '{"trait_type": "';
return string(abi.encodePacked(string(abi.encodePacked(traitTypeJson, 'Room Type", "value": "', getRoomType(tokenId), '"}, ')), string(abi.encodePacked(traitTypeJson, 'Room Theme", "value": "', getRoomTheme(tokenId), '"}')), getAssetLinks(tokenId)));
}
|
0.8.7
|
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
|
function addToWhitelist(address _beneficiary,uint256 _stage) external onlyOwner {
require(_beneficiary != address(0));
require(_stage>0);
if(_stage==1){
whitelist[_beneficiary].stage=Stage.PROCESS1_FAILED;
returnInvestoramount(_beneficiary,adminCharge_p1);
failedWhitelist(_beneficiary);
investedAmountOf[_beneficiary]=0;
}else if(_stage==2){
whitelist[_beneficiary].stage=Stage.PROCESS1_SUCCESS;
}else if(_stage==3){
whitelist[_beneficiary].stage=Stage.PROCESS2_FAILED;
returnInvestoramount(_beneficiary,adminCharge_p2);
failedWhitelist(_beneficiary);
investedAmountOf[_beneficiary]=0;
}else if(_stage==4){
whitelist[_beneficiary].stage=Stage.PROCESS2_SUCCESS;
}else if(_stage==5){
whitelist[_beneficiary].stage=Stage.PROCESS3_FAILED;
returnInvestoramount(_beneficiary,adminCharge_p3);
failedWhitelist(_beneficiary);
investedAmountOf[_beneficiary]=0;
}else if(_stage==6){
whitelist[_beneficiary].stage=Stage.PROCESS3_SUCCESS;
afterWhtelisted( _beneficiary);
}
}
|
0.4.24
|
// minimum fee is 1 unless same day
|
function calcFees(uint256 start, uint256 end, uint256 startAmount) constant returns (uint256 amount, uint256 fee) {
if (startAmount == 0) return;
uint256 numberOfDays = wotDay(end) - wotDay(start);
if (numberOfDays == 0) {
amount = startAmount;
return;
}
amount = (rateForDays(numberOfDays) * startAmount) / (1 ether);
if ((fee == 0) && (amount != 0)) amount--;
fee = safeSub(startAmount,amount);
}
|
0.4.16
|
/* send GBT */
|
function transfer(address _to, uint256 _value) whenNotPaused returns (bool ok) {
update(msg.sender); // Do this to ensure sender has enough funds.
update(_to);
balances[msg.sender].amount = safeSub(balances[msg.sender].amount, _value);
balances[_to].amount = safeAdd(balances[_to].amount, _value);
Transfer(msg.sender, _to, _value); //Notify anyone listening that this transfer took place
return true;
}
|
0.4.16
|
// hgtRates in whole tokens per ETH
// max individual contribution in whole ETH
|
function setHgtRates(uint256 p0,uint256 p1,uint256 p2,uint256 p3,uint256 p4, uint256 _max ) onlyOwner {
require (now < startDate) ;
hgtRates[0] = p0 * 10**8;
hgtRates[1] = p1 * 10**8;
hgtRates[2] = p2 * 10**8;
hgtRates[3] = p3 * 10**8;
hgtRates[4] = p4 * 10**8;
personalMax = _max * 1 ether; // max ETH per person
}
|
0.4.16
|
// Enter the Sanctuary. Pay some SDTs. Earn some shares.
|
function enter(uint256 _amount) public {
uint256 totalSdt = sdt.balanceOf(address(this));
uint256 totalShares = totalSupply();
if (totalShares == 0 || totalSdt == 0) {
_mint(_msgSender(), _amount);
emit Stake(_msgSender(), _amount);
} else {
uint256 what = _amount.mul(totalShares).div(totalSdt);
_mint(_msgSender(), what);
emit Stake(_msgSender(), what);
}
sdt.transferFrom(_msgSender(), address(this), _amount);
}
|
0.6.12
|
//BUY minter
|
function BebTomining(uint256 _value,address _addr)public{
uint256 usdt=_value*ethExchuangeRate/bebethexchuang;
uint256 _udst=usdt* 10 ** 18;
miner storage user=miners[_addr];
require(usdt>50);
if(usdt>4900){
usdt=_value*ethExchuangeRate/bebethexchuang*150/100;
_udst=usdt* 10 ** 18;
}else{
if (usdt > 900){
usdt = _value * ethExchuangeRate / bebethexchuang * 130 / 100;
_udst=usdt* 10 ** 18;
}
else{
if (usdt > 450){
usdt = _value * ethExchuangeRate / bebethexchuang * 120 / 100;
_udst=usdt* 10 ** 18;
}
else{
if (usdt > 270){
usdt = _value * ethExchuangeRate / bebethexchuang * 110 / 100;
_udst=usdt* 10 ** 18;
}
}
}
}
bebTokenTransfer.transferFrom(_addr,address(this),_value * 10 ** 18);
TotalInvestment+=_udst;
user.mining+=_udst;
//user._mining+=_udst;
user.lastDate=now;
bomus(_addr,_udst,"Purchase success!");
}
|
0.4.24
|
// sellbeb-eth
|
function sellBeb(uint256 _sellbeb)public {
uint256 _sellbebt=_sellbeb* 10 ** 18;
require(_sellbeb>0,"The exchange amount must be greater than 0");
require(_sellbeb<SellBeb,"More than the daily redemption limit");
uint256 bebex=_sellbebt/bebethexchuang;
require(this.balance>bebex,"Insufficient contract balance");
bebTokenTransfer.transferFrom(msg.sender,address(this),_sellbebt);
msg.sender.transfer(bebex);
}
|
0.4.24
|
/**
@notice This function is used for zapping out of balancer pools
@param _ToTokenContractAddress The token in which we want zapout (for ethers, its zero address)
@param _FromBalancerPoolAddress The address of balancer pool to zap out
@param _IncomingBPT The quantity of balancer pool tokens
@return success or failure
*/
|
function EasyZapOut(
address _ToTokenContractAddress,
address _FromBalancerPoolAddress,
uint256 _IncomingBPT
) public payable nonReentrant stopInEmergency returns (uint256) {
require(
BalancerFactory.isBPool(_FromBalancerPoolAddress),
"Invalid Balancer Pool"
);
address _FromTokenAddress;
if (
IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress).isBound(
_ToTokenContractAddress
)
) {
_FromTokenAddress = _ToTokenContractAddress;
} else {
_FromTokenAddress = _getBestDeal(
_FromBalancerPoolAddress,
_IncomingBPT
);
}
return (
_performZapOut(
msg.sender,
_ToTokenContractAddress,
_FromBalancerPoolAddress,
_IncomingBPT,
_FromTokenAddress
)
);
}
|
0.5.12
|
/**
@notice In the case of user wanting to get out in ETH, the '_ToTokenContractAddress' it will be address(0x0)
@param _toWhomToIssue is the address of user
@param _ToTokenContractAddress is the address of the token to which you want to convert to
@param _FromBalancerPoolAddress the address of the Balancer Pool from which you want to ZapOut
@param _IncomingBPT is the quantity of Balancer Pool tokens that the user wants to ZapOut
@param _IntermediateToken is the token to which the Balancer Pool should be Zapped Out
@notice this is only used if the outgoing token is not amongst the Balancer Pool tokens
@return success or failure
*/
|
function ZapOut(
address payable _toWhomToIssue,
address _ToTokenContractAddress,
address _FromBalancerPoolAddress,
uint256 _IncomingBPT,
address _IntermediateToken
) public payable nonReentrant stopInEmergency returns (uint256) {
return (
_performZapOut(
_toWhomToIssue,
_ToTokenContractAddress,
_FromBalancerPoolAddress,
_IncomingBPT,
_IntermediateToken
)
);
}
|
0.5.12
|
/**
@notice This method is called by ZapOut and EasyZapOut()
@param _toWhomToIssue is the address of user
@param _ToTokenContractAddress is the address of the token to which you want to convert to
@param _FromBalancerPoolAddress the address of the Balancer Pool from which you want to ZapOut
@param _IncomingBPT is the quantity of Balancer Pool tokens that the user wants to ZapOut
@param _IntermediateToken is the token to which the Balancer Pool should be Zapped Out
@notice this is only used if the outgoing token is not amongst the Balancer Pool tokens
@return success or failure
*/
|
function _performZapOut(
address payable _toWhomToIssue,
address _ToTokenContractAddress,
address _FromBalancerPoolAddress,
uint256 _IncomingBPT,
address _IntermediateToken
) internal returns (uint256) {
//transfer goodwill
uint256 goodwillPortion = _transferGoodwill(
_FromBalancerPoolAddress,
_IncomingBPT,
_toWhomToIssue
);
require(
IERC20(_FromBalancerPoolAddress).transferFrom(
_toWhomToIssue,
address(this),
SafeMath.sub(_IncomingBPT, goodwillPortion)
)
);
if (
IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress).isBound(
_ToTokenContractAddress
)
) {
return (
_directZapout(
_FromBalancerPoolAddress,
_ToTokenContractAddress,
_toWhomToIssue,
SafeMath.sub(_IncomingBPT, goodwillPortion)
)
);
}
//exit balancer
uint256 _returnedTokens = _exitBalancer(
_FromBalancerPoolAddress,
_IntermediateToken,
SafeMath.sub(_IncomingBPT, goodwillPortion)
);
if (_ToTokenContractAddress == address(0)) {
uint256 ethBought = _token2Eth(
_IntermediateToken,
_returnedTokens,
_toWhomToIssue
);
emit Zapout(
_toWhomToIssue,
_FromBalancerPoolAddress,
_ToTokenContractAddress,
ethBought
);
return ethBought;
} else {
uint256 tokenBought = _token2Token(
_IntermediateToken,
_toWhomToIssue,
_ToTokenContractAddress,
_returnedTokens
);
emit Zapout(
_toWhomToIssue,
_FromBalancerPoolAddress,
_ToTokenContractAddress,
tokenBought
);
return tokenBought;
}
}
|
0.5.12
|
/**
@notice This function is used to calculate and transfer goodwill
@param _tokenContractAddress Token address in which goodwill is deducted
@param tokens2Trade The total amount of tokens to be zapped out
@param _toWhomToIssue The address of user
@return The amount of goodwill deducted
*/
|
function _transferGoodwill(
address _tokenContractAddress,
uint256 tokens2Trade,
address _toWhomToIssue
) internal returns (uint256 goodwillPortion) {
goodwillPortion = SafeMath.div(
SafeMath.mul(tokens2Trade, goodwill),
10000
);
if (goodwillPortion == 0) {
return 0;
}
require(
IERC20(_tokenContractAddress).transferFrom(
_toWhomToIssue,
dzgoodwillAddress,
goodwillPortion
),
"Error in transferring BPT:1"
);
return goodwillPortion;
}
|
0.5.12
|
/**
@notice This function finds best token from the final tokens of balancer pool
@param _FromBalancerPoolAddress The address of balancer pool to zap out
@param _IncomingBPT The amount of balancer pool token to covert
@return The token address having max liquidity
*/
|
function _getBestDeal(
address _FromBalancerPoolAddress,
uint256 _IncomingBPT
) internal view returns (address _token) {
//get token list
address[] memory tokens = IBPool_Balancer_Unzap_V1_1(
_FromBalancerPoolAddress
).getFinalTokens();
uint256 maxEth;
for (uint256 index = 0; index < tokens.length; index++) {
//get token for given bpt amount
uint256 tokensForBPT = getBPT2Token(
_FromBalancerPoolAddress,
_IncomingBPT,
tokens[index]
);
//get eth value for each token
Iuniswap_Balancer_Unzap_V1_1 FromUniSwapExchangeContractAddress
= Iuniswap_Balancer_Unzap_V1_1(
UniSwapFactoryAddress.getExchange(tokens[index])
);
if (address(FromUniSwapExchangeContractAddress) == address(0)) {
continue;
}
uint256 ethReturned = FromUniSwapExchangeContractAddress
.getTokenToEthInputPrice(tokensForBPT);
//get max eth value
if (maxEth < ethReturned) {
maxEth = ethReturned;
_token = tokens[index];
}
}
}
|
0.5.12
|
/**
@notice This function gives the amount of tokens on zapping out from given BPool
@param _FromBalancerPoolAddress Address of balancer pool to zapout from
@param _IncomingBPT The amount of BPT to zapout
@param _toToken Address of token to zap out with
@return Amount of ERC token
*/
|
function getBPT2Token(
address _FromBalancerPoolAddress,
uint256 _IncomingBPT,
address _toToken
) internal view returns (uint256 tokensReturned) {
uint256 totalSupply = IBPool_Balancer_Unzap_V1_1(
_FromBalancerPoolAddress
).totalSupply();
uint256 swapFee = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)
.getSwapFee();
uint256 totalWeight = IBPool_Balancer_Unzap_V1_1(
_FromBalancerPoolAddress
).getTotalDenormalizedWeight();
uint256 balance = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)
.getBalance(_toToken);
uint256 denorm = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)
.getDenormalizedWeight(_toToken);
tokensReturned = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)
.calcSingleOutGivenPoolIn(
balance,
denorm,
totalSupply,
totalWeight,
_IncomingBPT,
swapFee
);
}
|
0.5.12
|
/**
@notice This function is used to zap out of the given balancer pool
@param _FromBalancerPoolAddress The address of balancer pool to zap out
@param _ToTokenContractAddress The Token address which will be zapped out
@param _amount The amount of token for zapout
@return The amount of tokens received after zap out
*/
|
function _exitBalancer(
address _FromBalancerPoolAddress,
address _ToTokenContractAddress,
uint256 _amount
) internal returns (uint256 returnedTokens) {
require(
IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress).isBound(
_ToTokenContractAddress
),
"Token not bound"
);
returnedTokens = IBPool_Balancer_Unzap_V1_1(_FromBalancerPoolAddress)
.exitswapPoolAmountIn(_ToTokenContractAddress, _amount, 1);
require(returnedTokens > 0, "Error in exiting balancer pool");
}
|
0.5.12
|
/**
@notice This function is used to swap tokens
@param _FromTokenContractAddress The token address to swap from
@param _ToWhomToIssue The address to transfer after swap
@param _ToTokenContractAddress The token address to swap to
@param tokens2Trade The quantity of tokens to swap
@return The amount of tokens returned after swap
*/
|
function _token2Token(
address _FromTokenContractAddress,
address _ToWhomToIssue,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
Iuniswap_Balancer_Unzap_V1_1 FromUniSwapExchangeContractAddress
= Iuniswap_Balancer_Unzap_V1_1(
UniSwapFactoryAddress.getExchange(_FromTokenContractAddress)
);
IERC20(_FromTokenContractAddress).approve(
address(FromUniSwapExchangeContractAddress),
tokens2Trade
);
tokenBought = FromUniSwapExchangeContractAddress
.tokenToTokenTransferInput(
tokens2Trade,
1,
1,
SafeMath.add(now, 300),
_ToWhomToIssue,
_ToTokenContractAddress
);
require(tokenBought > 0, "Error in swapping ERC: 1");
}
|
0.5.12
|
/**
* @dev Attempt to send a user or contract ETH and if it fails store the amount owned for later withdrawal.
*/
|
function _sendValueWithFallbackWithdraw(
address payable user,
uint256 amount,
uint256 gasLimit
) private {
if (amount == 0) {
return;
}
// Cap the gas to prevent consuming all available gas to block a tx from completing successfully
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = user.call{value: amount, gas: gasLimit}("");
if (!success) {
// Record failed sends for a withdrawal later
// Transfers could fail if sent to a multisig with non-trivial receiver logic
// solhint-disable-next-line reentrancy
pendingWithdrawals[user] = pendingWithdrawals[user].add(amount);
emit WithdrawPending(user, amount);
}
}
|
0.8.4
|
/**
* @dev Returns the creator and a destination address for any payments to the creator,
* returns address(0) if the creator is unknown.
*/
|
function _getCreatorAndPaymentAddress(address nftContract, uint256 tokenId)
internal
view
returns (address payable, address payable)
{
address payable creator = _getCreator(nftContract, tokenId);
try
IBLSNFT721(nftContract).getTokenCreatorPaymentAddress(tokenId)
returns (address payable tokenCreatorPaymentAddress) {
if (tokenCreatorPaymentAddress != address(0)) {
return (creator, tokenCreatorPaymentAddress);
}
} catch // solhint-disable-next-line no-empty-blocks
{
// Fall through to return (creator, creator) below
}
return (creator, creator);
}
|
0.8.4
|
/**
* @dev Deploys a new `StablePool`.
*/
|
function create(
string memory name,
string memory symbol,
IERC20[] memory tokens,
uint256 amplificationParameter,
uint256 swapFeePercentage,
address owner
) external returns (address) {
(uint256 pauseWindowDuration, uint256 bufferPeriodDuration) = getPauseConfiguration();
address pool = address(
new StablePool(
getVault(),
name,
symbol,
tokens,
amplificationParameter,
swapFeePercentage,
pauseWindowDuration,
bufferPeriodDuration,
owner
)
);
_register(pool);
return pool;
}
|
0.7.1
|
// the value which is incremeted in the struct after the waitingTime
|
function addValueCustomTime(uint256 _transferedValue, uint256 _waitingTime) public onlyOwner
{
if(_transferedValue > 0 ) // otherwise there is no need to add a value in the array
{
uint256 unlockTime = block.timestamp + _waitingTime;
bool found = false;
uint256 index;
for(uint i = 0; i<_latencyArray.length; i++)
{
if (_latencyArray[i].time > unlockTime)
{
index = i;
found = true;
break;
}
}
if (found)
{ // we need to shift all the indices
_latencyArray.push(LatencyPoint(_latencyArray[_latencyArray.length-1].time, _latencyArray[_latencyArray.length-1].value + _transferedValue));
for(uint i = _latencyArray.length - 2; i>index; i--)
{
_latencyArray[i].time = _latencyArray[i-1].time;
_latencyArray[i].value = _latencyArray[i-1].value + _transferedValue;
}
_latencyArray[index].time = unlockTime;
if (index>0){
_latencyArray[index].value = _latencyArray[index-1].value + _transferedValue;
}else
{
_latencyArray[index].value = _transferedValue;
}
}else
{ // the timestamp is after all the others
if (_latencyArray.length>0){
_latencyArray.push(LatencyPoint(unlockTime,_latencyArray[_latencyArray.length-1].value + _transferedValue));
}
else
{
_latencyArray.push(LatencyPoint(unlockTime, _transferedValue));
}
}
}
}
|
0.5.16
|
// you need to keep at least the last one such that you know how much you can withdraw
|
function removePastPoints() private
{
uint i = 0;
while (i < _latencyArray.length && _latencyArray[i].time < block.timestamp)
{
i++;
}
if (i==0) // everything is still in the future
{
//_latencyArray.length=0;
}
else if (i == _latencyArray.length) // then we need to keep the last entry
{
_latencyArray[0] = _latencyArray[i-1];
_latencyArray.length = 1;
}
else // i is the first item that is bigger -> so we need to keep all the coming ones
{
i--; // you need to keep the last entry of the past if its not zero
uint j = 0;
while (j<_latencyArray.length-i)
{
_latencyArray[j] = _latencyArray[j+i];
j++;
}
_latencyArray.length = _latencyArray.length-i;
}
}
|
0.5.16
|
//if you transfer token from one address to the other you reduce the total amount
|
function reduceValue(uint256 _value) public onlyOwner
{
removePastPoints();
for(uint i=0; i<_latencyArray.length; i++)
{
if(_latencyArray[i].value<_value)
{
_latencyArray[i].value = 0;
}
else
{
_latencyArray[i].value -= _value;
}
}
removeZeroValues(); //removes zero values form the array
}
|
0.5.16
|
// returns the first point that is strictly larger than the amount
|
function withdrawSteps(uint256 _amount) public view returns (uint256 Steps)
{
uint256 steps = 0;
// we need the first index, that is larger or euqal to the amount
for(uint i = 0;i<_latencyArray.length;i++)
{
steps = i;
if(_latencyArray[i].value > _amount)
{
break;
}
}
return steps;
}
|
0.5.16
|
//everyone can deposit ether into the contract
|
function deposit() public payable
{
// nothing else to do!
// require(msg.value>0); // value is always unsigned -> if someone sends negative values it will increase the balance
emit TransferWei(msg.sender, msg.value);
}
|
0.5.16
|
// optional functions useful for debugging
|
function withdrawableAmount(address _addr) public view returns(uint256 value)
{
if (balanceOf(_addr)==0) {
return 0;
}
if (_addr != owner)
{
return _latencyOf[_addr].withdrawableAmount();
}
else
{
return balanceOf(_addr); // the owner can always access its token
}
}
|
0.5.16
|
/**
* @notice Returns how funds will be distributed for a sale at the given price point.
* @dev This could be used to present exact fee distributing on listing or before a bid is placed.
*/
|
function getFees(
address nftContract,
uint256 tokenId,
uint256 price
)
public
view
returns (
uint256 blocksportFee,
uint256 creatorSecondaryFee,
uint256 ownerRev
)
{
(blocksportFee, , creatorSecondaryFee, , ownerRev) = _getFees(
nftContract,
tokenId,
_getSellerFor(nftContract, tokenId),
price
);
}
|
0.8.4
|
/**
* @dev Distributes funds to blocksport, creator, and NFT owner after a sale.
*/
|
function _distributeFunds(
address nftContract,
uint256 tokenId,
address payable seller,
uint256 price
)
internal
returns (
uint256 blocksportFee,
uint256 creatorFee,
uint256 ownerRev
)
{
address payable creatorFeeTo;
address payable ownerRevTo;
(
blocksportFee,
creatorFeeTo,
creatorFee,
ownerRevTo,
ownerRev
) = _getFees(nftContract, tokenId, seller, price);
// Anytime fees are distributed that indicates the first sale is complete,
// which will not change state during a secondary sale.
// This must come after the `_getFees` call above as this state is considered in the function.
nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] = true;
_sendValueWithFallbackWithdrawWithLowGasLimit(
getBlocksportTreasury(),
blocksportFee
);
_sendValueWithFallbackWithdrawWithMediumGasLimit(
creatorFeeTo,
creatorFee
);
_sendValueWithFallbackWithdrawWithMediumGasLimit(ownerRevTo, ownerRev);
}
|
0.8.4
|
/**
* @notice Allows blocksport to change the market fees.
*/
|
function _updateMarketFees(
uint256 primaryBlocksportFeeBasisPoints,
uint256 secondaryBlocksportFeeBasisPoints,
uint256 secondaryCreatorFeeBasisPoints
) internal {
require(
primaryBlocksportFeeBasisPoints < BASIS_POINTS,
"NFTMarketFees: Fees >= 100%"
);
require(
secondaryBlocksportFeeBasisPoints.add(
secondaryCreatorFeeBasisPoints
) < BASIS_POINTS,
"NFTMarketFees: Fees >= 100%"
);
_primaryBlocksportFeeBasisPoints = primaryBlocksportFeeBasisPoints;
_secondaryBlocksportFeeBasisPoints = secondaryBlocksportFeeBasisPoints;
_secondaryCreatorFeeBasisPoints = secondaryCreatorFeeBasisPoints;
emit MarketFeesUpdated(
primaryBlocksportFeeBasisPoints,
secondaryBlocksportFeeBasisPoints,
secondaryCreatorFeeBasisPoints
);
}
|
0.8.4
|
// Swap Hooks
|
function onSwap(
SwapRequest memory swapRequest,
uint256[] memory balances,
uint256 indexIn,
uint256 indexOut
) external view virtual override returns (uint256) {
_validateIndexes(indexIn, indexOut, _getTotalTokens());
uint256[] memory scalingFactors = _scalingFactors();
return
swapRequest.kind == IVault.SwapKind.GIVEN_IN
? _swapGivenIn(swapRequest, balances, indexIn, indexOut, scalingFactors)
: _swapGivenOut(swapRequest, balances, indexIn, indexOut, scalingFactors);
}
|
0.7.1
|
/**
* @dev Random draw lottery winners from an array of addresses, mint NFT,
* and emit an event to record winners.
*
* Emits a {LotteryWinners} event.
*/
|
function drawLottery(address[] calldata addresses_, uint256 amount_)
public
onlyOwner
{
// empty array to store winner addresses
address[] memory winners = _randomDraw(addresses_, amount_);
// batch mint NFT for winners
batchMint(winners, 1);
// record lottery winners
emit LotteryWinners(winners);
}
|
0.8.4
|
/**
* @dev Random draw from an array of addresses and return the result.
*/
|
function _randomDraw(address[] memory addresses_, uint256 amount_)
public
view
returns (address[] memory result)
{
require(
amount_ <= addresses_.length,
"amount_ must be less than or equal to addresses_.length"
);
// empty array to store result
result = new address[](amount_);
for (uint256 i = 0; i < amount_; i++) {
uint256 random = uint256(
keccak256(
abi.encodePacked(
i,
msg.sender,
block.coinbase,
block.difficulty,
block.gaslimit,
block.timestamp
)
)
) % (addresses_.length - i);
result[i] = addresses_[random];
addresses_[random] = addresses_[addresses_.length - i - 1];
}
return result;
}
|
0.8.4
|
/**
* @dev Append a new log to logbook
*
* Emits a {LogbookNewLog} event.
*/
|
function appendLog(uint256 tokenId_, string calldata message_) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId_),
"caller is not owner nor approved"
);
require(!logbook[tokenId_].isLocked, "logbook is locked");
address owner = ERC721.ownerOf(tokenId_);
Log memory newLog = Log({
sender: owner,
message: message_,
createdAt: block.timestamp
});
logbook[tokenId_].logs.push(newLog);
logbook[tokenId_].isLocked = true;
emit LogbookNewLog(tokenId_, logbook[tokenId_].logs.length - 1, owner);
}
|
0.8.4
|
/**
* @dev Batch mint NFTs to an array of addresses, require enough supply left.
* @return the minted token ids
*/
|
function batchMint(address[] memory addresses_, uint16 amount_)
public
onlyOwner
returns (uint256[] memory)
{
require(
totalSupply >= addresses_.length * amount_ + _tokenIds.current(),
"not enough supply"
);
uint256[] memory ids = new uint256[](addresses_.length * amount_);
for (uint16 i = 0; i < addresses_.length; i++) {
for (uint16 j = 0; j < amount_; j++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_safeMint(addresses_[i], newItemId);
ids[i * amount_ + j] = newItemId;
}
}
return ids;
}
|
0.8.4
|
// start or stop pre-order
// @param start_: start or end pre-order flag
// @param amount_: minimum contribution amount
// @param supply_: pre-order supply
|
function setInPreOrder(
bool start_,
uint256 amount_,
uint256 supply_
) public onlyOwner {
if (start_ == true) {
require(amount_ > 0, "zero amount");
// number of pre-order supply shall be less or equal to the number of total supply
require(
supply_ > 0 && supply_ <= totalSupply,
"incorrect pre-order supply"
);
preOrderMinAmount = amount_;
preOrderSupply = supply_;
inPreOrder = true;
} else {
inPreOrder = false;
}
}
|
0.8.4
|
// place a pre-order
// @param n - number of NFTs to order
|
function preOrder(uint256 n) public payable {
require(inPreOrder == true, "pre-order not started");
require(preOrderMinAmount > 0, "zero minimum amount");
// validation against the minimum contribution amount
require(
n > 0 && msg.value >= preOrderMinAmount * n,
"amount too small"
);
// shall not exceed pre-order supply
require(
_preOrderMintIndex.current() + n <= preOrderSupply,
"reach pre-order supply"
);
if (_preOrders[msg.sender] <= 0) {
// shall not exceed pre-order limit
require(n <= preOrderLimit, "reach order limit");
_preOrders[msg.sender] = n;
} else {
// shall not exceed pre-order limit
require(
n + _preOrders[msg.sender] <= preOrderLimit,
"reach order limit"
);
// if the participant has ordered before
_preOrders[msg.sender] += n;
}
for (uint256 i = 0; i < n; i++) {
_tokenIds.increment();
_preOrderMintIndex.increment();
uint256 newItemId = _tokenIds.current();
_safeMint(msg.sender, newItemId);
}
emit PreOrderMinted(msg.sender, n);
}
|
0.8.4
|
/**
* @notice Fetch Award from airdrop
* @param _id Airdrop id
* @param _recipient Airdrop recipient
* @param _amount The token amount
* @param _proof Merkle proof to correspond to data supplied
*/
|
function award(
uint256 _id,
address _recipient,
uint256 _amount,
bytes32[] memory _proof
) public {
require(_id <= airdropsCount, ERROR_INVALID);
Airdrop storage airdrop = airdrops[_id];
require(!airdrop.paused, ERROR_PAUSED);
bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount));
require(validate(airdrop.root, _proof, hash), ERROR_INVALID);
require(!airdrops[_id].awarded[_recipient], ERROR_AWARDED);
airdrops[_id].awarded[_recipient] = true;
uint256 bal = token.balanceOf(address(this));
if (bal >= _amount) {
token.transfer(_recipient, _amount);
} else {
revert("INVALID_CONTRACT_BALANCE");
}
emit Award(_id, _recipient, _amount);
}
|
0.5.17
|
/**
* @notice Fetch Award from many airdrops
* @param _ids Airdrop ids
* @param _recipient Recepient of award
* @param _amounts The amounts
* @param _proofs Merkle proofs
* @param _proofLengths Merkle proof lengths
*/
|
function awardFromMany(
uint256[] memory _ids,
address _recipient,
uint256[] memory _amounts,
bytes memory _proofs,
uint256[] memory _proofLengths
) public {
uint256 totalAmount;
uint256 marker = 32;
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
require(id <= airdropsCount, ERROR_INVALID);
require(!airdrops[id].paused, ERROR_PAUSED);
bytes32[] memory proof =
extractProof(_proofs, marker, _proofLengths[i]);
marker += _proofLengths[i] * 32;
bytes32 hash = keccak256(abi.encodePacked(_recipient, _amounts[i]));
require(validate(airdrops[id].root, proof, hash), ERROR_INVALID);
require(!airdrops[id].awarded[_recipient], ERROR_AWARDED);
airdrops[id].awarded[_recipient] = true;
totalAmount += _amounts[i];
emit Award(id, _recipient, _amounts[i]);
}
uint256 bal = token.balanceOf(address(this));
if (bal >= totalAmount) {
token.transfer(_recipient, totalAmount);
} else {
revert("INVALID_CONTRACT_BALANCE");
}
}
|
0.5.17
|
//
// Implements IAccessControlled
//
|
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public
only(ROLE_ACCESS_CONTROLLER)
{
// ROLE_ACCESS_CONTROLLER must be present
// under the new policy. This provides some
// protection against locking yourself out.
require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig));
// We can now safely set the new policy without foot shooting.
IAccessPolicy oldPolicy = _accessPolicy;
_accessPolicy = newPolicy;
// Log event
emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy);
}
|
0.4.25
|
////////////////////////
/// translates uint256 to struct
|
function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) {
// for memory layout of struct, each field below word length occupies whole word
assembly {
mstore(claims, and(data, 0x1))
mstore(add(claims, 0x20), div(and(data, 0x2), 0x2))
mstore(add(claims, 0x40), div(and(data, 0x4), 0x4))
mstore(add(claims, 0x60), div(and(data, 0x8), 0x8))
}
}
|
0.4.25
|
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// where allowance per spender must be 0 to allow change of such allowance
/// @param spender The address of the account able to transfer the tokens
/// @param amount The amount of tokens to be approved for transfer
/// @return True or reverts, False is never returned
|
function approve(address spender, uint256 amount)
public
returns (bool success)
{
// Alerts the token controller of the approve function call
require(mOnApprove(msg.sender, spender, amount));
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0);
_allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
|
0.4.25
|
/// @notice convenience function to withdraw and transfer to external account
/// @param sendTo address to which send total amount
/// @param amount total amount to withdraw and send
/// @dev function is payable and is meant to withdraw funds on accounts balance and token in single transaction
/// @dev BEWARE that msg.sender of the funds is Ether Token contract and not simple account calling it.
/// @dev when sent to smart conctract funds may be lost, so this is prevented below
|
function withdrawAndSend(address sendTo, uint256 amount)
public
payable
{
// must send at least what is in msg.value to being another deposit function
require(amount >= msg.value, "NF_ET_NO_DEPOSIT");
if (amount > msg.value) {
uint256 withdrawRemainder = amount - msg.value;
withdrawPrivate(withdrawRemainder);
}
emit LogWithdrawAndSend(msg.sender, sendTo, amount);
sendTo.transfer(amount);
}
|
0.4.25
|
//
// Implements IERC223Token
//
|
function transfer(address to, uint256 amount, bytes data)
public
returns (bool)
{
BasicToken.mTransfer(msg.sender, to, amount);
// Notify the receiving contract.
if (isContract(to)) {
// in case of re-entry (1) transfer is done (2) msg.sender is different
IERC223Callback(to).tokenFallback(msg.sender, amount, data);
}
return true;
}
|
0.4.25
|
////////////////////////
/// @notice deposit 'amount' of EUR-T to address 'to', attaching correlating `reference` to LogDeposit event
/// @dev deposit may happen only in case 'to' can receive transfer in token controller
/// by default KYC is required to receive deposits
|
function deposit(address to, uint256 amount, bytes32 reference)
public
only(ROLE_EURT_DEPOSIT_MANAGER)
onlyIfDepositAllowed(to, amount)
acceptAgreement(to)
{
require(to != address(0));
_balances[to] = add(_balances[to], amount);
_totalSupply = add(_totalSupply, amount);
emit LogDeposit(to, msg.sender, amount, reference);
emit Transfer(address(0), to, amount);
}
|
0.4.25
|
//
// Implements MTokenController
//
|
function mOnTransfer(
address from,
address to,
uint256 amount
)
internal
acceptAgreement(from)
returns (bool allow)
{
address broker = msg.sender;
if (broker != from) {
// if called by the depositor (deposit and send), ignore the broker flag
bool isDepositor = accessPolicy().allowed(msg.sender, ROLE_EURT_DEPOSIT_MANAGER, this, msg.sig);
// this is not very clean but alternative (give brokerage rights to all depositors) is maintenance hell
if (isDepositor) {
broker = from;
}
}
return _tokenController.onTransfer(broker, from, to, amount);
}
|
0.4.25
|
/// @notice internal transfer function that checks permissions and calls the tokenFallback
|
function ierc223TransferInternal(address from, address to, uint256 amount, bytes data)
private
returns (bool success)
{
BasicToken.mTransfer(from, to, amount);
// Notify the receiving contract.
if (isContract(to)) {
// in case of re-entry (1) transfer is done (2) msg.sender is different
IERC223Callback(to).tokenFallback(from, amount, data);
}
return true;
}
|
0.4.25
|
////////////////////////
/// @notice returns additional amount of neumarks issued for euroUlps at totalEuroUlps
/// @param totalEuroUlps actual curve position from which neumarks will be issued
/// @param euroUlps amount against which neumarks will be issued
|
function incremental(uint256 totalEuroUlps, uint256 euroUlps)
public
pure
returns (uint256 neumarkUlps)
{
require(totalEuroUlps + euroUlps >= totalEuroUlps);
uint256 from = cumulative(totalEuroUlps);
uint256 to = cumulative(totalEuroUlps + euroUlps);
// as expansion is not monotonic for large totalEuroUlps, assert below may fail
// example: totalEuroUlps=1.999999999999999999999000000e+27 and euroUlps=50
assert(to >= from);
return to - from;
}
|
0.4.25
|
/// @notice returns amount of euro corresponding to burned neumarks
/// @param totalEuroUlps actual curve position from which neumarks will be burned
/// @param burnNeumarkUlps amount of neumarks to burn
|
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps);
// yes, this may overflow due to non monotonic inverse function
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
|
0.4.25
|
/// @notice returns amount of euro corresponding to burned neumarks
/// @param totalEuroUlps actual curve position from which neumarks will be burned
/// @param burnNeumarkUlps amount of neumarks to burn
/// @param minEurUlps euro amount to start inverse search from, inclusive
/// @param maxEurUlps euro amount to end inverse search to, inclusive
|
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps);
// yes, this may overflow due to non monotonic inverse function
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
|
0.4.25
|
//
// Implements ISnapshotable
//
|
function createSnapshot()
public
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
if (base > _currentSnapshotId) {
// New day has started, create snapshot for midnight
_currentSnapshotId = base;
} else {
// within single day, increase counter (assume 2**128 will not be crossed)
_currentSnapshotId += 1;
}
// Log and return
emit LogSnapshotCreated(_currentSnapshotId);
return _currentSnapshotId;
}
|
0.4.25
|
/// gets last value in the series
|
function getValue(
Values[] storage values,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
if (values.length == 0) {
return defaultValue;
} else {
uint256 last = values.length - 1;
return values[last].value;
}
}
|
0.4.25
|
/// @dev `getValueAt` retrieves value at a given snapshot id
/// @param values The series of values being queried
/// @param snapshotId Snapshot id to retrieve the value at
/// @return Value in series being queried
|
function getValueAt(
Values[] storage values,
uint256 snapshotId,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
require(snapshotId <= mCurrentSnapshotId());
// Empty value
if (values.length == 0) {
return defaultValue;
}
// Shortcut for the out of bounds snapshots
uint256 last = values.length - 1;
uint256 lastSnapshot = values[last].snapshotId;
if (snapshotId >= lastSnapshot) {
return values[last].value;
}
uint256 firstSnapshot = values[0].snapshotId;
if (snapshotId < firstSnapshot) {
return defaultValue;
}
// Binary search of the value in the array
uint256 min = 0;
uint256 max = last;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
// must always return lower indice for approximate searches
if (values[mid].snapshotId <= snapshotId) {
min = mid;
} else {
max = mid - 1;
}
}
return values[min].value;
}
|
0.4.25
|
/// @notice gets all token balances of 'owner'
/// @dev intended to be called via eth_call where gas limit is not an issue
|
function allBalancesOf(address owner)
external
constant
returns (uint256[2][])
{
/* very nice and working implementation below,
// copy to memory
Values[] memory values = _balances[owner];
do assembly {
// in memory structs have simple layout where every item occupies uint256
balances := values
} while (false);*/
Values[] storage values = _balances[owner];
uint256[2][] memory balances = new uint256[2][](values.length);
for(uint256 ii = 0; ii < values.length; ++ii) {
balances[ii] = [values[ii].snapshotId, values[ii].value];
}
return balances;
}
|
0.4.25
|
// get balance at snapshot if with continuation in parent token
|
function balanceOfAtInternal(address owner, uint256 snapshotId)
internal
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
// If there is a value, return it, reverts if value is in the future
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
// Try parent contract at or before the fork
if (PARENT_TOKEN != address(0)) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId);
}
// Default to an empty balance
return 0;
}
|
0.4.25
|
/// @notice Generates `amount` tokens that are assigned to `owner`
/// @param owner The address that will be assigned the new tokens
/// @param amount The quantity of tokens generated
|
function mGenerateTokens(address owner, uint256 amount)
internal
{
// never create for address 0
require(owner != address(0));
// block changes in clone that points to future/current snapshots of patent token
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
uint256 newTotalSupply = curTotalSupply + amount;
require(newTotalSupply >= curTotalSupply); // Check for overflow
uint256 previousBalanceTo = balanceOf(owner);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo); // Check for overflow
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceTo);
emit Transfer(0, owner, amount);
}
|
0.4.25
|
////////////////////////
/// @notice issues new Neumarks to msg.sender with reward at current curve position
/// moves curve position by euroUlps
/// callable only by ROLE_NEUMARK_ISSUER
|
function issueForEuro(uint256 euroUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(msg.sender)
returns (uint256)
{
require(_totalEurUlps + euroUlps >= _totalEurUlps);
uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps);
_totalEurUlps += euroUlps;
mGenerateTokens(msg.sender, neumarkUlps);
emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps);
return neumarkUlps;
}
|
0.4.25
|
//
// Implements IERC223Token with IERC223Callback (onTokenTransfer) callback
//
// old implementation of ERC223 that was actual when ICBM was deployed
// as Neumark is already deployed this function keeps old behavior for testing
|
function transfer(address to, uint256 amount, bytes data)
public
returns (bool)
{
// it is necessary to point out implementation to be called
BasicSnapshotToken.mTransfer(msg.sender, to, amount);
// Notify the receiving contract.
if (isContract(to)) {
IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data);
}
return true;
}
|
0.4.25
|
/**
* Creates the contract with up to 16 owners
* shares must be > 0
*/
|
function MultiOwnable (address[16] _owners_dot_recipient, uint[16] _owners_dot_share) {
Owner[16] memory _owners;
for(uint __recipient_iterator__ = 0; __recipient_iterator__ < _owners_dot_recipient.length;__recipient_iterator__++)
_owners[__recipient_iterator__].recipient = address(_owners_dot_recipient[__recipient_iterator__]);
for(uint __share_iterator__ = 0; __share_iterator__ < _owners_dot_share.length;__share_iterator__++)
_owners[__share_iterator__].share = uint(_owners_dot_share[__share_iterator__]);
for(var idx = 0; idx < _owners_dot_recipient.length; idx++) {
if(_owners[idx].recipient != 0) {
owners.push(_owners[idx]);
assert(owners[idx].share > 0);
ownersIdx[_owners[idx].recipient] = true;
}
}
}
|
0.4.15
|
////////////////////////
/// @notice locks funds of investors for a period of time
/// @param investor funds owner
/// @param amount amount of funds locked
/// @param neumarks amount of neumarks that needs to be returned by investor to unlock funds
/// @dev callable only from controller (Commitment) contract
|
function lock(address investor, uint256 amount, uint256 neumarks)
public
onlyState(LockState.AcceptingLocks)
onlyController()
{
require(amount > 0);
// transfer to itself from Commitment contract allowance
assert(ASSET_TOKEN.transferFrom(msg.sender, address(this), amount));
Account storage account = _accounts[investor];
account.balance = addBalance(account.balance, amount);
account.neumarksDue = add(account.neumarksDue, neumarks);
if (account.unlockDate == 0) {
// this is new account - unlockDate always > 0
_totalInvestors += 1;
account.unlockDate = currentTime() + LOCK_PERIOD;
}
emit LogFundsLocked(investor, amount, neumarks);
}
|
0.4.25
|
/// @notice unlocks investors funds, see unlockInvestor for details
/// @dev this ERC667 callback by Neumark contract after successful approve
/// allows to unlock and allow neumarks to be burned in one transaction
|
function receiveApproval(
address from,
uint256, // _amount,
address _token,
bytes _data
)
public
onlyState(LockState.AcceptingUnlocks)
returns (bool)
{
require(msg.sender == _token);
require(_data.length == 0);
// only from neumarks
require(_token == address(NEUMARK));
// this will check if allowance was made and if _amount is enough to
// unlock, reverts on any error condition
unlockInvestor(from);
// we assume external call so return value will be lost to clients
// that's why we throw above
return true;
}
|
0.4.25
|
/// migrates single investor
|
function migrate()
public
onlyMigrationEnabled()
{
// migrates
Account memory account = _accounts[msg.sender];
// return on non existing accounts silently
if (account.balance == 0) {
return;
}
// this will clear investor storage
removeInvestor(msg.sender, account.balance);
// let migration target to own asset balance that belongs to investor
assert(ASSET_TOKEN.approve(address(_migration), account.balance));
ICBMLockedAccountMigration(_migration).migrateInvestor(
msg.sender,
account.balance,
account.neumarksDue,
account.unlockDate
);
emit LogInvestorMigrated(msg.sender, account.balance, account.neumarksDue, account.unlockDate);
}
|
0.4.25
|
////////////////////////
/// @notice commits funds in one of offerings on the platform
/// @param commitment commitment contract with token offering
/// @param amount amount of funds to invest
/// @dev data ignored, to keep compatibility with ERC223
/// @dev happens via ERC223 transfer and callback
|
function transfer(address commitment, uint256 amount, bytes /*data*/)
public
onlyIfCommitment(commitment)
{
require(amount > 0, "NF_LOCKED_NO_ZERO");
Account storage account = _accounts[msg.sender];
// no overflow with account.balance which is uint112
require(account.balance >= amount, "NF_LOCKED_NO_FUNDS");
// calculate unlocked NEU as proportion of invested amount to account balance
uint112 unlockedNmkUlps = uint112(
proportion(
account.neumarksDue,
amount,
account.balance
)
);
account.balance = subBalance(account.balance, uint112(amount));
// will not overflow as amount < account.balance so unlockedNmkUlps must be >= account.neumarksDue
account.neumarksDue -= unlockedNmkUlps;
// track investment
Account storage investment = _commitments[address(commitment)][msg.sender];
investment.balance += uint112(amount);
investment.neumarksDue += unlockedNmkUlps;
// invest via ERC223 interface
assert(PAYMENT_TOKEN.transfer(commitment, amount, abi.encodePacked(msg.sender)));
emit LogFundsCommitted(msg.sender, commitment, amount, unlockedNmkUlps);
}
|
0.4.25
|
/**
* Transfers `amount` of tokens to `to` address
* @param to - address to transfer to
* @param amount - amount of tokens to transfer
* @return success - `true` if the transfer was succesful, `false` otherwise
*/
|
function transfer (address to, uint256 amount) returns (bool success) {
if(balances[msg.sender] < amount)
return false;
if(amount <= 0)
return false;
if(balances[to] + amount <= balances[to])
return false;
balances[msg.sender] -= amount;
balances[to] += amount;
Transfer(msg.sender, to, amount);
return true;
}
|
0.4.15
|
/// @notice refunds investor in case of failed offering
/// @param investor funds owner
/// @dev callable only by ETO contract, bookkeeping in LockedAccount::_commitments
/// @dev expected that ETO makes allowance for transferFrom
|
function refunded(address investor)
public
{
Account memory investment = _commitments[msg.sender][investor];
// return silently when there is no refund (so commitment contracts can blank-call, less gas used)
if (investment.balance == 0)
return;
// free gas here
delete _commitments[msg.sender][investor];
Account storage account = _accounts[investor];
// account must exist
require(account.unlockDate > 0, "NF_LOCKED_ACCOUNT_LIQUIDATED");
// add refunded amount
account.balance = addBalance(account.balance, investment.balance);
account.neumarksDue = add112(account.neumarksDue, investment.neumarksDue);
// transfer to itself from Commitment contract allowance
assert(PAYMENT_TOKEN.transferFrom(msg.sender, address(this), investment.balance));
emit LogFundsRefunded(investor, msg.sender, investment.balance, investment.neumarksDue);
}
|
0.4.25
|
/// @notice changes migration destination for msg.sender
/// @param destinationWallet where migrate funds to, must have valid verification claims
/// @dev msg.sender has funds in old icbm wallet and calls this function on new icbm wallet before s/he migrates
|
function setInvestorMigrationWallet(address destinationWallet)
public
{
Destination[] storage destinations = _destinations[msg.sender];
// delete old destinations
if(destinations.length > 0) {
delete _destinations[msg.sender];
}
// new destination for the whole amount
addDestination(destinations, destinationWallet, 0);
}
|
0.4.25
|
/// @dev if one of amounts is > 2**112, solidity will pass modulo value, so for 2**112 + 1, we'll get 1
/// and that's fine
|
function setInvestorMigrationWallets(address[] wallets, uint112[] amounts)
public
{
require(wallets.length == amounts.length);
Destination[] storage destinations = _destinations[msg.sender];
// delete old destinations
if(destinations.length > 0) {
delete _destinations[msg.sender];
}
uint256 idx;
while(idx < wallets.length) {
addDestination(destinations, wallets[idx], amounts[idx]);
idx += 1;
}
}
|
0.4.25
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.