contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
TrifoliumCoin
TrifoliumCoin.sol
0xaf3573e1e223c601340ade1f1d52cd106b264367
Solidity
TrifoliumCoin
contract TrifoliumCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "TRF"; name = "Trifolium Coin"; decimals = 8; _totalSupply = 2500000000000000000; balances[0xbBeF3dF952B8375eAC290F85d8408928d80200A1] = _totalSupply; emit Transfer(address(0), 0xbBeF3dF952B8375eAC290F85d8408928d80200A1, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferAnyERC20Token
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------
LineComment
v0.4.26+commit.4563c3fc
Unlicense
bzzr://3eb1872d4617e4eeb5092088bd46ae520993873a98d7ecc5e99c2742894ae43b
{ "func_code_index": [ 5292, 5481 ] }
5,707
Treasury
contracts/Treasury.sol
0x0f5ecb70896fd26e595e81dac3d881fbf8e0f7b3
Solidity
Treasury
contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public cash; address public bond; address public share; address public curve; address public boardroom; address public bondOracle; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne; uint256 public lastBondOracleEpoch = 0; uint256 public bondCap = 0; uint256 public accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _bond, address _share, address _bondOracle, address _seigniorageOracle, address _boardroom, address _fund, address _curve, uint256 _startTime ) public Epoch(1 days, _startTime, 0) { cash = _cash; bond = _bond; share = _share; curve = _curve; bondOracle = _bondOracle; seigniorageOracle = _seigniorageOracle; boardroom = _boardroom; fund = _fund; cashPriceOne = 10**18; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } modifier updatePrice { _; _updateCashPrice(); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function circulatingSupply() public view returns (uint256) { return IERC20(cash).totalSupply().sub(accumulatedSeigniorage); } function getCeilingPrice() public view returns (uint256) { return ICurve(curve).calcCeiling(circulatingSupply()); } // oracle function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); } function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ // MIGRATION function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } // FUND function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); } function setFundAllocationRate(uint256 newRate) public onlyOperator { uint256 oldRate = fundAllocationRate; fundAllocationRate = newRate; emit ContributionPoolRateChanged(msg.sender, oldRate, newRate); } // ORACLE function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); } function setSeigniorageOracle(address newOracle) public onlyOperator { address oldOracle = seigniorageOracle; seigniorageOracle = newOracle; emit SeigniorageOracleChanged(msg.sender, oldOracle, newOracle); } // TWEAK function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } } function _updateCashPrice() internal { if (Epoch(bondOracle).callable()) { try IOracle(bondOracle).update() {} catch {} } if (Epoch(seigniorageOracle).callable()) { try IOracle(seigniorageOracle).update() {} catch {} } } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice <= targetPrice, 'Treasury: cash price moved'); require( cashPrice < cashPriceOne, // price < $1 'Treasury: cashPrice not eligible for bond purchase' ); _updateConversionLimit(cashPrice); amount = Math.min(amount, bondCap.mul(cashPrice).div(1e18)); require(amount > 0, 'Treasury: amount exceeds bond cap'); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(cashPrice)); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require( cashPrice > getCeilingPrice(), // price > $1.05 'Treasury: cashPrice not eligible for bond purchase' ); require( IERC20(cash).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, amount); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice <= getCeilingPrice()) { return; // just advance epoch instead revert } // circulating supply uint256 percentage = cashPrice.sub(cashPriceOne); uint256 seigniorage = circulatingSupply().mul(percentage).div(1e18); IBasisAsset(cash).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { if (treasuryReserve == seigniorage) { treasuryReserve = treasuryReserve.mul(80).div(100); } accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(cash).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } /* ========== EVENTS ========== */ // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged( address indexed operator, address oldFund, address newFund ); event ContributionPoolRateChanged( address indexed operator, uint256 oldRate, uint256 newRate ); event BondOracleChanged( address indexed operator, address oldOracle, address newOracle ); event SeigniorageOracleChanged( address indexed operator, address oldOracle, address newOracle ); event CeilingCurveChanged( address indexed operator, address oldCurve, address newCurve ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
/** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */
NatSpecMultiLine
getReserve
function getReserve() public view returns (uint256) { return accumulatedSeigniorage; }
// budget
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://281dbf07430b63c8e244159e2db3312302f29665b6c6dbdbc87b58cdf8313df1
{ "func_code_index": [ 2197, 2302 ] }
5,708
Treasury
contracts/Treasury.sol
0x0f5ecb70896fd26e595e81dac3d881fbf8e0f7b3
Solidity
Treasury
contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public cash; address public bond; address public share; address public curve; address public boardroom; address public bondOracle; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne; uint256 public lastBondOracleEpoch = 0; uint256 public bondCap = 0; uint256 public accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _bond, address _share, address _bondOracle, address _seigniorageOracle, address _boardroom, address _fund, address _curve, uint256 _startTime ) public Epoch(1 days, _startTime, 0) { cash = _cash; bond = _bond; share = _share; curve = _curve; bondOracle = _bondOracle; seigniorageOracle = _seigniorageOracle; boardroom = _boardroom; fund = _fund; cashPriceOne = 10**18; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } modifier updatePrice { _; _updateCashPrice(); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function circulatingSupply() public view returns (uint256) { return IERC20(cash).totalSupply().sub(accumulatedSeigniorage); } function getCeilingPrice() public view returns (uint256) { return ICurve(curve).calcCeiling(circulatingSupply()); } // oracle function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); } function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ // MIGRATION function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } // FUND function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); } function setFundAllocationRate(uint256 newRate) public onlyOperator { uint256 oldRate = fundAllocationRate; fundAllocationRate = newRate; emit ContributionPoolRateChanged(msg.sender, oldRate, newRate); } // ORACLE function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); } function setSeigniorageOracle(address newOracle) public onlyOperator { address oldOracle = seigniorageOracle; seigniorageOracle = newOracle; emit SeigniorageOracleChanged(msg.sender, oldOracle, newOracle); } // TWEAK function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } } function _updateCashPrice() internal { if (Epoch(bondOracle).callable()) { try IOracle(bondOracle).update() {} catch {} } if (Epoch(seigniorageOracle).callable()) { try IOracle(seigniorageOracle).update() {} catch {} } } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice <= targetPrice, 'Treasury: cash price moved'); require( cashPrice < cashPriceOne, // price < $1 'Treasury: cashPrice not eligible for bond purchase' ); _updateConversionLimit(cashPrice); amount = Math.min(amount, bondCap.mul(cashPrice).div(1e18)); require(amount > 0, 'Treasury: amount exceeds bond cap'); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(cashPrice)); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require( cashPrice > getCeilingPrice(), // price > $1.05 'Treasury: cashPrice not eligible for bond purchase' ); require( IERC20(cash).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, amount); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice <= getCeilingPrice()) { return; // just advance epoch instead revert } // circulating supply uint256 percentage = cashPrice.sub(cashPriceOne); uint256 seigniorage = circulatingSupply().mul(percentage).div(1e18); IBasisAsset(cash).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { if (treasuryReserve == seigniorage) { treasuryReserve = treasuryReserve.mul(80).div(100); } accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(cash).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } /* ========== EVENTS ========== */ // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged( address indexed operator, address oldFund, address newFund ); event ContributionPoolRateChanged( address indexed operator, uint256 oldRate, uint256 newRate ); event BondOracleChanged( address indexed operator, address oldOracle, address newOracle ); event SeigniorageOracleChanged( address indexed operator, address oldOracle, address newOracle ); event CeilingCurveChanged( address indexed operator, address oldCurve, address newCurve ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
/** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */
NatSpecMultiLine
getBondOraclePrice
function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); }
// oracle
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://281dbf07430b63c8e244159e2db3312302f29665b6c6dbdbc87b58cdf8313df1
{ "func_code_index": [ 2604, 2720 ] }
5,709
Treasury
contracts/Treasury.sol
0x0f5ecb70896fd26e595e81dac3d881fbf8e0f7b3
Solidity
Treasury
contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public cash; address public bond; address public share; address public curve; address public boardroom; address public bondOracle; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne; uint256 public lastBondOracleEpoch = 0; uint256 public bondCap = 0; uint256 public accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _bond, address _share, address _bondOracle, address _seigniorageOracle, address _boardroom, address _fund, address _curve, uint256 _startTime ) public Epoch(1 days, _startTime, 0) { cash = _cash; bond = _bond; share = _share; curve = _curve; bondOracle = _bondOracle; seigniorageOracle = _seigniorageOracle; boardroom = _boardroom; fund = _fund; cashPriceOne = 10**18; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } modifier updatePrice { _; _updateCashPrice(); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function circulatingSupply() public view returns (uint256) { return IERC20(cash).totalSupply().sub(accumulatedSeigniorage); } function getCeilingPrice() public view returns (uint256) { return ICurve(curve).calcCeiling(circulatingSupply()); } // oracle function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); } function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ // MIGRATION function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } // FUND function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); } function setFundAllocationRate(uint256 newRate) public onlyOperator { uint256 oldRate = fundAllocationRate; fundAllocationRate = newRate; emit ContributionPoolRateChanged(msg.sender, oldRate, newRate); } // ORACLE function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); } function setSeigniorageOracle(address newOracle) public onlyOperator { address oldOracle = seigniorageOracle; seigniorageOracle = newOracle; emit SeigniorageOracleChanged(msg.sender, oldOracle, newOracle); } // TWEAK function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } } function _updateCashPrice() internal { if (Epoch(bondOracle).callable()) { try IOracle(bondOracle).update() {} catch {} } if (Epoch(seigniorageOracle).callable()) { try IOracle(seigniorageOracle).update() {} catch {} } } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice <= targetPrice, 'Treasury: cash price moved'); require( cashPrice < cashPriceOne, // price < $1 'Treasury: cashPrice not eligible for bond purchase' ); _updateConversionLimit(cashPrice); amount = Math.min(amount, bondCap.mul(cashPrice).div(1e18)); require(amount > 0, 'Treasury: amount exceeds bond cap'); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(cashPrice)); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require( cashPrice > getCeilingPrice(), // price > $1.05 'Treasury: cashPrice not eligible for bond purchase' ); require( IERC20(cash).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, amount); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice <= getCeilingPrice()) { return; // just advance epoch instead revert } // circulating supply uint256 percentage = cashPrice.sub(cashPriceOne); uint256 seigniorage = circulatingSupply().mul(percentage).div(1e18); IBasisAsset(cash).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { if (treasuryReserve == seigniorage) { treasuryReserve = treasuryReserve.mul(80).div(100); } accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(cash).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } /* ========== EVENTS ========== */ // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged( address indexed operator, address oldFund, address newFund ); event ContributionPoolRateChanged( address indexed operator, uint256 oldRate, uint256 newRate ); event BondOracleChanged( address indexed operator, address oldOracle, address newOracle ); event SeigniorageOracleChanged( address indexed operator, address oldOracle, address newOracle ); event CeilingCurveChanged( address indexed operator, address oldCurve, address newCurve ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
/** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */
NatSpecMultiLine
initialize
function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); }
// MIGRATION
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://281dbf07430b63c8e244159e2db3312302f29665b6c6dbdbc87b58cdf8313df1
{ "func_code_index": [ 3218, 3545 ] }
5,710
Treasury
contracts/Treasury.sol
0x0f5ecb70896fd26e595e81dac3d881fbf8e0f7b3
Solidity
Treasury
contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public cash; address public bond; address public share; address public curve; address public boardroom; address public bondOracle; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne; uint256 public lastBondOracleEpoch = 0; uint256 public bondCap = 0; uint256 public accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _bond, address _share, address _bondOracle, address _seigniorageOracle, address _boardroom, address _fund, address _curve, uint256 _startTime ) public Epoch(1 days, _startTime, 0) { cash = _cash; bond = _bond; share = _share; curve = _curve; bondOracle = _bondOracle; seigniorageOracle = _seigniorageOracle; boardroom = _boardroom; fund = _fund; cashPriceOne = 10**18; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } modifier updatePrice { _; _updateCashPrice(); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function circulatingSupply() public view returns (uint256) { return IERC20(cash).totalSupply().sub(accumulatedSeigniorage); } function getCeilingPrice() public view returns (uint256) { return ICurve(curve).calcCeiling(circulatingSupply()); } // oracle function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); } function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ // MIGRATION function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } // FUND function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); } function setFundAllocationRate(uint256 newRate) public onlyOperator { uint256 oldRate = fundAllocationRate; fundAllocationRate = newRate; emit ContributionPoolRateChanged(msg.sender, oldRate, newRate); } // ORACLE function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); } function setSeigniorageOracle(address newOracle) public onlyOperator { address oldOracle = seigniorageOracle; seigniorageOracle = newOracle; emit SeigniorageOracleChanged(msg.sender, oldOracle, newOracle); } // TWEAK function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } } function _updateCashPrice() internal { if (Epoch(bondOracle).callable()) { try IOracle(bondOracle).update() {} catch {} } if (Epoch(seigniorageOracle).callable()) { try IOracle(seigniorageOracle).update() {} catch {} } } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice <= targetPrice, 'Treasury: cash price moved'); require( cashPrice < cashPriceOne, // price < $1 'Treasury: cashPrice not eligible for bond purchase' ); _updateConversionLimit(cashPrice); amount = Math.min(amount, bondCap.mul(cashPrice).div(1e18)); require(amount > 0, 'Treasury: amount exceeds bond cap'); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(cashPrice)); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require( cashPrice > getCeilingPrice(), // price > $1.05 'Treasury: cashPrice not eligible for bond purchase' ); require( IERC20(cash).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, amount); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice <= getCeilingPrice()) { return; // just advance epoch instead revert } // circulating supply uint256 percentage = cashPrice.sub(cashPriceOne); uint256 seigniorage = circulatingSupply().mul(percentage).div(1e18); IBasisAsset(cash).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { if (treasuryReserve == seigniorage) { treasuryReserve = treasuryReserve.mul(80).div(100); } accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(cash).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } /* ========== EVENTS ========== */ // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged( address indexed operator, address oldFund, address newFund ); event ContributionPoolRateChanged( address indexed operator, uint256 oldRate, uint256 newRate ); event BondOracleChanged( address indexed operator, address oldOracle, address newOracle ); event SeigniorageOracleChanged( address indexed operator, address oldOracle, address newOracle ); event CeilingCurveChanged( address indexed operator, address oldCurve, address newCurve ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
/** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */
NatSpecMultiLine
setFund
function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); }
// FUND
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://281dbf07430b63c8e244159e2db3312302f29665b6c6dbdbc87b58cdf8313df1
{ "func_code_index": [ 4358, 4552 ] }
5,711
Treasury
contracts/Treasury.sol
0x0f5ecb70896fd26e595e81dac3d881fbf8e0f7b3
Solidity
Treasury
contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public cash; address public bond; address public share; address public curve; address public boardroom; address public bondOracle; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne; uint256 public lastBondOracleEpoch = 0; uint256 public bondCap = 0; uint256 public accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _bond, address _share, address _bondOracle, address _seigniorageOracle, address _boardroom, address _fund, address _curve, uint256 _startTime ) public Epoch(1 days, _startTime, 0) { cash = _cash; bond = _bond; share = _share; curve = _curve; bondOracle = _bondOracle; seigniorageOracle = _seigniorageOracle; boardroom = _boardroom; fund = _fund; cashPriceOne = 10**18; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } modifier updatePrice { _; _updateCashPrice(); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function circulatingSupply() public view returns (uint256) { return IERC20(cash).totalSupply().sub(accumulatedSeigniorage); } function getCeilingPrice() public view returns (uint256) { return ICurve(curve).calcCeiling(circulatingSupply()); } // oracle function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); } function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ // MIGRATION function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } // FUND function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); } function setFundAllocationRate(uint256 newRate) public onlyOperator { uint256 oldRate = fundAllocationRate; fundAllocationRate = newRate; emit ContributionPoolRateChanged(msg.sender, oldRate, newRate); } // ORACLE function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); } function setSeigniorageOracle(address newOracle) public onlyOperator { address oldOracle = seigniorageOracle; seigniorageOracle = newOracle; emit SeigniorageOracleChanged(msg.sender, oldOracle, newOracle); } // TWEAK function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } } function _updateCashPrice() internal { if (Epoch(bondOracle).callable()) { try IOracle(bondOracle).update() {} catch {} } if (Epoch(seigniorageOracle).callable()) { try IOracle(seigniorageOracle).update() {} catch {} } } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice <= targetPrice, 'Treasury: cash price moved'); require( cashPrice < cashPriceOne, // price < $1 'Treasury: cashPrice not eligible for bond purchase' ); _updateConversionLimit(cashPrice); amount = Math.min(amount, bondCap.mul(cashPrice).div(1e18)); require(amount > 0, 'Treasury: amount exceeds bond cap'); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(cashPrice)); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require( cashPrice > getCeilingPrice(), // price > $1.05 'Treasury: cashPrice not eligible for bond purchase' ); require( IERC20(cash).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, amount); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice <= getCeilingPrice()) { return; // just advance epoch instead revert } // circulating supply uint256 percentage = cashPrice.sub(cashPriceOne); uint256 seigniorage = circulatingSupply().mul(percentage).div(1e18); IBasisAsset(cash).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { if (treasuryReserve == seigniorage) { treasuryReserve = treasuryReserve.mul(80).div(100); } accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(cash).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } /* ========== EVENTS ========== */ // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged( address indexed operator, address oldFund, address newFund ); event ContributionPoolRateChanged( address indexed operator, uint256 oldRate, uint256 newRate ); event BondOracleChanged( address indexed operator, address oldOracle, address newOracle ); event SeigniorageOracleChanged( address indexed operator, address oldOracle, address newOracle ); event CeilingCurveChanged( address indexed operator, address oldCurve, address newCurve ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
/** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */
NatSpecMultiLine
setBondOracle
function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); }
// ORACLE
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://281dbf07430b63c8e244159e2db3312302f29665b6c6dbdbc87b58cdf8313df1
{ "func_code_index": [ 4813, 5029 ] }
5,712
Treasury
contracts/Treasury.sol
0x0f5ecb70896fd26e595e81dac3d881fbf8e0f7b3
Solidity
Treasury
contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public cash; address public bond; address public share; address public curve; address public boardroom; address public bondOracle; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne; uint256 public lastBondOracleEpoch = 0; uint256 public bondCap = 0; uint256 public accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _bond, address _share, address _bondOracle, address _seigniorageOracle, address _boardroom, address _fund, address _curve, uint256 _startTime ) public Epoch(1 days, _startTime, 0) { cash = _cash; bond = _bond; share = _share; curve = _curve; bondOracle = _bondOracle; seigniorageOracle = _seigniorageOracle; boardroom = _boardroom; fund = _fund; cashPriceOne = 10**18; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } modifier updatePrice { _; _updateCashPrice(); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function circulatingSupply() public view returns (uint256) { return IERC20(cash).totalSupply().sub(accumulatedSeigniorage); } function getCeilingPrice() public view returns (uint256) { return ICurve(curve).calcCeiling(circulatingSupply()); } // oracle function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); } function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ // MIGRATION function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } // FUND function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); } function setFundAllocationRate(uint256 newRate) public onlyOperator { uint256 oldRate = fundAllocationRate; fundAllocationRate = newRate; emit ContributionPoolRateChanged(msg.sender, oldRate, newRate); } // ORACLE function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); } function setSeigniorageOracle(address newOracle) public onlyOperator { address oldOracle = seigniorageOracle; seigniorageOracle = newOracle; emit SeigniorageOracleChanged(msg.sender, oldOracle, newOracle); } // TWEAK function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } } function _updateCashPrice() internal { if (Epoch(bondOracle).callable()) { try IOracle(bondOracle).update() {} catch {} } if (Epoch(seigniorageOracle).callable()) { try IOracle(seigniorageOracle).update() {} catch {} } } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice <= targetPrice, 'Treasury: cash price moved'); require( cashPrice < cashPriceOne, // price < $1 'Treasury: cashPrice not eligible for bond purchase' ); _updateConversionLimit(cashPrice); amount = Math.min(amount, bondCap.mul(cashPrice).div(1e18)); require(amount > 0, 'Treasury: amount exceeds bond cap'); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(cashPrice)); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require( cashPrice > getCeilingPrice(), // price > $1.05 'Treasury: cashPrice not eligible for bond purchase' ); require( IERC20(cash).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, amount); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice <= getCeilingPrice()) { return; // just advance epoch instead revert } // circulating supply uint256 percentage = cashPrice.sub(cashPriceOne); uint256 seigniorage = circulatingSupply().mul(percentage).div(1e18); IBasisAsset(cash).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { if (treasuryReserve == seigniorage) { treasuryReserve = treasuryReserve.mul(80).div(100); } accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(cash).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } /* ========== EVENTS ========== */ // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged( address indexed operator, address oldFund, address newFund ); event ContributionPoolRateChanged( address indexed operator, uint256 oldRate, uint256 newRate ); event BondOracleChanged( address indexed operator, address oldOracle, address newOracle ); event SeigniorageOracleChanged( address indexed operator, address oldOracle, address newOracle ); event CeilingCurveChanged( address indexed operator, address oldCurve, address newCurve ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
/** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */
NatSpecMultiLine
setCeilingCurve
function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); }
// TWEAK
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://281dbf07430b63c8e244159e2db3312302f29665b6c6dbdbc87b58cdf8313df1
{ "func_code_index": [ 5293, 5501 ] }
5,713
Treasury
contracts/Treasury.sol
0x0f5ecb70896fd26e595e81dac3d881fbf8e0f7b3
Solidity
Treasury
contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public cash; address public bond; address public share; address public curve; address public boardroom; address public bondOracle; address public seigniorageOracle; // ========== PARAMS uint256 public cashPriceOne; uint256 public lastBondOracleEpoch = 0; uint256 public bondCap = 0; uint256 public accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _cash, address _bond, address _share, address _bondOracle, address _seigniorageOracle, address _boardroom, address _fund, address _curve, uint256 _startTime ) public Epoch(1 days, _startTime, 0) { cash = _cash; bond = _bond; share = _share; curve = _curve; bondOracle = _bondOracle; seigniorageOracle = _seigniorageOracle; boardroom = _boardroom; fund = _fund; cashPriceOne = 10**18; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(cash).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } modifier updatePrice { _; _updateCashPrice(); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function circulatingSupply() public view returns (uint256) { return IERC20(cash).totalSupply().sub(accumulatedSeigniorage); } function getCeilingPrice() public view returns (uint256) { return ICurve(curve).calcCeiling(circulatingSupply()); } // oracle function getBondOraclePrice() public view returns (uint256) { return _getCashPrice(bondOracle); } function getSeigniorageOraclePrice() public view returns (uint256) { return _getCashPrice(seigniorageOracle); } function _getCashPrice(address oracle) internal view returns (uint256) { try IOracle(oracle).consult(cash, 1e18) returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult cash price from the oracle'); } } /* ========== GOVERNANCE ========== */ // MIGRATION function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(cash).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // cash Operator(cash).transferOperator(target); Operator(cash).transferOwnership(target); IERC20(cash).transfer(target, IERC20(cash).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } // FUND function setFund(address newFund) public onlyOperator { address oldFund = fund; fund = newFund; emit ContributionPoolChanged(msg.sender, oldFund, newFund); } function setFundAllocationRate(uint256 newRate) public onlyOperator { uint256 oldRate = fundAllocationRate; fundAllocationRate = newRate; emit ContributionPoolRateChanged(msg.sender, oldRate, newRate); } // ORACLE function setBondOracle(address newOracle) public onlyOperator { address oldOracle = bondOracle; bondOracle = newOracle; emit BondOracleChanged(msg.sender, oldOracle, newOracle); } function setSeigniorageOracle(address newOracle) public onlyOperator { address oldOracle = seigniorageOracle; seigniorageOracle = newOracle; emit SeigniorageOracleChanged(msg.sender, oldOracle, newOracle); } // TWEAK function setCeilingCurve(address newCurve) public onlyOperator { address oldCurve = newCurve; curve = newCurve; emit CeilingCurveChanged(msg.sender, oldCurve, newCurve); } /* ========== MUTABLE FUNCTIONS ========== */ function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } } function _updateCashPrice() internal { if (Epoch(bondOracle).callable()) { try IOracle(bondOracle).update() {} catch {} } if (Epoch(seigniorageOracle).callable()) { try IOracle(seigniorageOracle).update() {} catch {} } } function buyBonds(uint256 amount, uint256 targetPrice) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require(cashPrice <= targetPrice, 'Treasury: cash price moved'); require( cashPrice < cashPriceOne, // price < $1 'Treasury: cashPrice not eligible for bond purchase' ); _updateConversionLimit(cashPrice); amount = Math.min(amount, bondCap.mul(cashPrice).div(1e18)); require(amount > 0, 'Treasury: amount exceeds bond cap'); IBasisAsset(cash).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(cashPrice)); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount) external onlyOneBlock checkMigration checkStartTime checkOperator updatePrice { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 cashPrice = _getCashPrice(bondOracle); require( cashPrice > getCeilingPrice(), // price > $1.05 'Treasury: cashPrice not eligible for bond purchase' ); require( IERC20(cash).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(cash).safeTransfer(msg.sender, amount); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updateCashPrice(); uint256 cashPrice = _getCashPrice(seigniorageOracle); if (cashPrice <= getCeilingPrice()) { return; // just advance epoch instead revert } // circulating supply uint256 percentage = cashPrice.sub(cashPriceOne); uint256 seigniorage = circulatingSupply().mul(percentage).div(1e18); IBasisAsset(cash).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(cash).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( cash, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { if (treasuryReserve == seigniorage) { treasuryReserve = treasuryReserve.mul(80).div(100); } accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(cash).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } /* ========== EVENTS ========== */ // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged( address indexed operator, address oldFund, address newFund ); event ContributionPoolRateChanged( address indexed operator, uint256 oldRate, uint256 newRate ); event BondOracleChanged( address indexed operator, address oldOracle, address newOracle ); event SeigniorageOracleChanged( address indexed operator, address oldOracle, address newOracle ); event CeilingCurveChanged( address indexed operator, address oldCurve, address newCurve ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
/** * @title Basis Cash Treasury contract * @notice Monetary policy logic to adjust supplies of basis cash assets * @author Summer Smith & Rick Sanchez */
NatSpecMultiLine
_updateConversionLimit
function _updateConversionLimit(uint256 cashPrice) internal { uint256 currentEpoch = Epoch(bondOracle).getLastEpoch(); // lastest update time if (lastBondOracleEpoch != currentEpoch) { uint256 percentage = cashPriceOne.sub(cashPrice); uint256 bondSupply = IERC20(bond).totalSupply(); bondCap = circulatingSupply().mul(percentage).div(1e18); bondCap = bondCap.sub(Math.min(bondCap, bondSupply)); lastBondOracleEpoch = currentEpoch; } }
/* ========== MUTABLE FUNCTIONS ========== */
Comment
v0.6.12+commit.27d51765
MIT
ipfs://281dbf07430b63c8e244159e2db3312302f29665b6c6dbdbc87b58cdf8313df1
{ "func_code_index": [ 5557, 6097 ] }
5,714
WethConverter
WethConverter.sol
0x7b706466ee101d6bebbbc2c279c9d8c628b4cb25
Solidity
WethConverter
contract WethConverter { WETH9Like constant private weth9 = WETH9Like(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // ETH wrapper contract v9 WETH10Like constant private weth10 = WETH10Like(0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9F); // ETH wrapper contract v10 receive() external payable {} function weth9ToWeth10(address account, uint256 value) external payable { weth9.transferFrom(account, address(this), value); weth9.withdraw(value); weth10.depositTo{value: value + msg.value}(account); } function weth10ToWeth9(address account, uint256 value) external payable { weth10.withdrawFrom(account, address(this), value); uint256 combined = value + msg.value; weth9.deposit{value: combined}(); weth9.transfer(account, combined); } }
// ETH wrapper contract v10
LineComment
v0.7.6+commit.7338295f
GNU GPLv3
ipfs://ed1627289bf6f4e7f31c90bafea22db950eeecbe1070afdaf9d4aefade6b937f
{ "func_code_index": [ 280, 314 ] }
5,715
SvdMainSale
contracts/SvdMainSale.sol
0x2c30840965f8fb2dc42bf4d6d530661d9f0e73c3
Solidity
SvdMainSale
contract SvdMainSale is Pausable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // track the investments made from each address mapping(address => uint256) public investments; // total amount of funds raised (in wei) uint256 public weiRaised; uint256 public minWeiInvestment; uint256 public maxWeiInvestment; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event Investment(address indexed purchaser, address indexed beneficiary, uint256 value); /** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */ function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; } /** * @dev External payable function to receive funds and buy tokens. */ function () external payable { buyTokens(msg.sender); } /** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */ function hasStarted() external view returns (bool) { return now >= startTime; } /** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */ function hasEnded() external view returns (bool) { return now > endTime; } /** * @dev Low level token purchase function */ function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); } // send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; } }
/** * @title SvdMainSale * @dev This crowdsale contract filters investments made according to * - time * - amount invested (in Wei) * and forwards them to a predefined wallet in case all the filtering conditions are met. */
NatSpecMultiLine
SvdMainSale
function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; }
/** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://da9ff952e767350dbbcf075e04968dd01e718b423e428d4599d4add6f4d0ae75
{ "func_code_index": [ 1354, 1909 ] }
5,716
SvdMainSale
contracts/SvdMainSale.sol
0x2c30840965f8fb2dc42bf4d6d530661d9f0e73c3
Solidity
SvdMainSale
contract SvdMainSale is Pausable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // track the investments made from each address mapping(address => uint256) public investments; // total amount of funds raised (in wei) uint256 public weiRaised; uint256 public minWeiInvestment; uint256 public maxWeiInvestment; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event Investment(address indexed purchaser, address indexed beneficiary, uint256 value); /** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */ function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; } /** * @dev External payable function to receive funds and buy tokens. */ function () external payable { buyTokens(msg.sender); } /** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */ function hasStarted() external view returns (bool) { return now >= startTime; } /** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */ function hasEnded() external view returns (bool) { return now > endTime; } /** * @dev Low level token purchase function */ function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); } // send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; } }
/** * @title SvdMainSale * @dev This crowdsale contract filters investments made according to * - time * - amount invested (in Wei) * and forwards them to a predefined wallet in case all the filtering conditions are met. */
NatSpecMultiLine
function () external payable { buyTokens(msg.sender); }
/** * @dev External payable function to receive funds and buy tokens. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://da9ff952e767350dbbcf075e04968dd01e718b423e428d4599d4add6f4d0ae75
{ "func_code_index": [ 2002, 2076 ] }
5,717
SvdMainSale
contracts/SvdMainSale.sol
0x2c30840965f8fb2dc42bf4d6d530661d9f0e73c3
Solidity
SvdMainSale
contract SvdMainSale is Pausable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // track the investments made from each address mapping(address => uint256) public investments; // total amount of funds raised (in wei) uint256 public weiRaised; uint256 public minWeiInvestment; uint256 public maxWeiInvestment; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event Investment(address indexed purchaser, address indexed beneficiary, uint256 value); /** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */ function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; } /** * @dev External payable function to receive funds and buy tokens. */ function () external payable { buyTokens(msg.sender); } /** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */ function hasStarted() external view returns (bool) { return now >= startTime; } /** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */ function hasEnded() external view returns (bool) { return now > endTime; } /** * @dev Low level token purchase function */ function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); } // send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; } }
/** * @title SvdMainSale * @dev This crowdsale contract filters investments made according to * - time * - amount invested (in Wei) * and forwards them to a predefined wallet in case all the filtering conditions are met. */
NatSpecMultiLine
hasStarted
function hasStarted() external view returns (bool) { return now >= startTime; }
/** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://da9ff952e767350dbbcf075e04968dd01e718b423e428d4599d4add6f4d0ae75
{ "func_code_index": [ 2193, 2291 ] }
5,718
SvdMainSale
contracts/SvdMainSale.sol
0x2c30840965f8fb2dc42bf4d6d530661d9f0e73c3
Solidity
SvdMainSale
contract SvdMainSale is Pausable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // track the investments made from each address mapping(address => uint256) public investments; // total amount of funds raised (in wei) uint256 public weiRaised; uint256 public minWeiInvestment; uint256 public maxWeiInvestment; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event Investment(address indexed purchaser, address indexed beneficiary, uint256 value); /** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */ function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; } /** * @dev External payable function to receive funds and buy tokens. */ function () external payable { buyTokens(msg.sender); } /** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */ function hasStarted() external view returns (bool) { return now >= startTime; } /** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */ function hasEnded() external view returns (bool) { return now > endTime; } /** * @dev Low level token purchase function */ function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); } // send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; } }
/** * @title SvdMainSale * @dev This crowdsale contract filters investments made according to * - time * - amount invested (in Wei) * and forwards them to a predefined wallet in case all the filtering conditions are met. */
NatSpecMultiLine
hasEnded
function hasEnded() external view returns (bool) { return now > endTime; }
/** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://da9ff952e767350dbbcf075e04968dd01e718b423e428d4599d4add6f4d0ae75
{ "func_code_index": [ 2404, 2497 ] }
5,719
SvdMainSale
contracts/SvdMainSale.sol
0x2c30840965f8fb2dc42bf4d6d530661d9f0e73c3
Solidity
SvdMainSale
contract SvdMainSale is Pausable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // track the investments made from each address mapping(address => uint256) public investments; // total amount of funds raised (in wei) uint256 public weiRaised; uint256 public minWeiInvestment; uint256 public maxWeiInvestment; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event Investment(address indexed purchaser, address indexed beneficiary, uint256 value); /** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */ function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; } /** * @dev External payable function to receive funds and buy tokens. */ function () external payable { buyTokens(msg.sender); } /** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */ function hasStarted() external view returns (bool) { return now >= startTime; } /** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */ function hasEnded() external view returns (bool) { return now > endTime; } /** * @dev Low level token purchase function */ function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); } // send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; } }
/** * @title SvdMainSale * @dev This crowdsale contract filters investments made according to * - time * - amount invested (in Wei) * and forwards them to a predefined wallet in case all the filtering conditions are met. */
NatSpecMultiLine
buyTokens
function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); }
/** * @dev Low level token purchase function */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://da9ff952e767350dbbcf075e04968dd01e718b423e428d4599d4add6f4d0ae75
{ "func_code_index": [ 2565, 3100 ] }
5,720
SvdMainSale
contracts/SvdMainSale.sol
0x2c30840965f8fb2dc42bf4d6d530661d9f0e73c3
Solidity
SvdMainSale
contract SvdMainSale is Pausable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // track the investments made from each address mapping(address => uint256) public investments; // total amount of funds raised (in wei) uint256 public weiRaised; uint256 public minWeiInvestment; uint256 public maxWeiInvestment; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event Investment(address indexed purchaser, address indexed beneficiary, uint256 value); /** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */ function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; } /** * @dev External payable function to receive funds and buy tokens. */ function () external payable { buyTokens(msg.sender); } /** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */ function hasStarted() external view returns (bool) { return now >= startTime; } /** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */ function hasEnded() external view returns (bool) { return now > endTime; } /** * @dev Low level token purchase function */ function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); } // send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; } }
/** * @title SvdMainSale * @dev This crowdsale contract filters investments made according to * - time * - amount invested (in Wei) * and forwards them to a predefined wallet in case all the filtering conditions are met. */
NatSpecMultiLine
forwardFunds
function forwardFunds() internal { wallet.transfer(msg.value); }
// send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms
LineComment
v0.4.18+commit.9cf6e910
bzzr://da9ff952e767350dbbcf075e04968dd01e718b423e428d4599d4add6f4d0ae75
{ "func_code_index": [ 3219, 3302 ] }
5,721
SvdMainSale
contracts/SvdMainSale.sol
0x2c30840965f8fb2dc42bf4d6d530661d9f0e73c3
Solidity
SvdMainSale
contract SvdMainSale is Pausable { using SafeMath for uint256; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // track the investments made from each address mapping(address => uint256) public investments; // total amount of funds raised (in wei) uint256 public weiRaised; uint256 public minWeiInvestment; uint256 public maxWeiInvestment; /** * @dev Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event Investment(address indexed purchaser, address indexed beneficiary, uint256 value); /** * @dev Constructor * @param _startTime the time to begin the crowdsale in seconds since the epoch * @param _endTime the time to begin the crowdsale in seconds since the epoch. Must be later than _startTime. * @param _minWeiInvestment the minimum amount for one single investment (in Wei) * @param _maxWeiInvestment the maximum amount for one single investment (in Wei) * @param _wallet the address to which funds will be directed to */ function SvdMainSale(uint256 _startTime, uint256 _endTime, uint256 _minWeiInvestment, uint256 _maxWeiInvestment, address _wallet) public { require(_endTime > _startTime); require(_minWeiInvestment > 0); require(_maxWeiInvestment > _minWeiInvestment); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; minWeiInvestment = _minWeiInvestment; maxWeiInvestment = _maxWeiInvestment; wallet = _wallet; } /** * @dev External payable function to receive funds and buy tokens. */ function () external payable { buyTokens(msg.sender); } /** * @dev Adapted Crowdsale#hasStarted * @return true if SvdMainSale event has started */ function hasStarted() external view returns (bool) { return now >= startTime; } /** * @dev Adapted Crowdsale#hasEnded * @return true if SvdMainSale event has ended */ function hasEnded() external view returns (bool) { return now > endTime; } /** * @dev Low level token purchase function */ function buyTokens(address beneficiary) public whenNotPaused payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // track how much wei is raised in total weiRaised = weiRaised.add(weiAmount); // track how much was transfered by the specific investor investments[beneficiary] = investments[beneficiary].add(weiAmount); Investment(msg.sender, beneficiary, weiAmount); forwardFunds(); } // send ether (wei) to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; } }
/** * @title SvdMainSale * @dev This crowdsale contract filters investments made according to * - time * - amount invested (in Wei) * and forwards them to a predefined wallet in case all the filtering conditions are met. */
NatSpecMultiLine
validPurchase
function validPurchase() internal view returns (bool) { if (msg.value < minWeiInvestment || msg.value > maxWeiInvestment) { return false; } bool withinPeriod = (now >= startTime) && (now <= endTime); return withinPeriod; }
// overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment
LineComment
v0.4.18+commit.9cf6e910
bzzr://da9ff952e767350dbbcf075e04968dd01e718b423e428d4599d4add6f4d0ae75
{ "func_code_index": [ 3427, 3709 ] }
5,722
TokenProxy
zos-lib/contracts/utils/Address.sol
0x1e053d89e08c24aa2ce5c5b4206744dc2d7bd8f5
Solidity
ZOSLibAddress
library ZOSLibAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } }
/** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.0.0/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */
NatSpecMultiLine
isContract
function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; }
/** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */
NatSpecMultiLine
v0.4.24+commit.e67f0147
{ "func_code_index": [ 367, 951 ] }
5,723
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
refreshDevtRate
function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } }
/// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 1528, 2309 ] }
5,724
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
updateRewards
function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } }
/// @notice update totalRewardsEarned, update cumulative profit per lp token
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 2392, 3404 ] }
5,725
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
init
function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); }
/// @notice Initialize variables
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 3905, 4466 ] }
5,726
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
utilization
function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; }
/// @notice Get mining utilization
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 4507, 4643 ] }
5,727
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
getBoost
function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } }
/// @notice Get mining efficiency bonus for different pledge time
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 4715, 5202 ] }
5,728
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
pendingRewards
function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); }
/// @notice Get the user's cumulative revenue as of the current time
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 5277, 6110 ] }
5,729
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
deposit
function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); }
/// @notice Pledge devt
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 6140, 7693 ] }
5,730
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
withdraw
function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); }
/// @notice Withdraw the principal and income after maturity
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 7760, 8831 ] }
5,731
DevtMine
contracts/DevtMine.sol
0xff55b2815a86a3c574ae6627f091c056592624c5
Solidity
DevtMine
contract DevtMine is Ownable { using SafeERC20 for ERC20; using SafeCast for uint256; using SafeCast for int256; // lock time enum Lock { twoWeeks, oneMonth, twoMonths } uint256 public constant LIFECYCLE = 90 days; // Devt token addr ERC20 public immutable devt; // Dvt token addr (These two addresses can be the same) ERC20 public immutable dvt; uint256 public endTimestamp; uint256 public maxDvtPerSecond; uint256 public dvtPerSecond; uint256 public totalRewardsEarned; //Cumulative revenue per lp token uint256 public accDvtPerShare; uint256 public totalLpToken; uint256 public devtTotalDeposits; uint256 public lastRewardTimestamp; //Target pledge amount uint256 public immutable targetPledgeAmount; struct UserInfo { uint256 depositAmount; uint256 lpAmount; uint256 lockedUntil; int256 rewardDebt; Lock lock; bool isDeposit; } /// @notice user => UserInfo mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event Harvest(address indexed user, uint256 amount); event LogUpdateRewards( uint256 indexed lastRewardTimestamp, uint256 lpSupply, uint256 accDvtPerShare ); /// @notice Refresh the development rate according to the ratio of the current pledge amount to the target pledge amount function refreshDevtRate() private { uint256 util = utilization(); if (util < 5e16) { dvtPerSecond = 0; } else if (util < 1e17) { // >5% // 50% dvtPerSecond = (maxDvtPerSecond * 5) / 10; } else if (util < (1e17 + 5e16)) { // >10% // 60% dvtPerSecond = (maxDvtPerSecond * 6) / 10; } else if (util < 2e17) { // >15% // 80% dvtPerSecond = (maxDvtPerSecond * 8) / 10; } else if (util < (2e17 + 5e16)) { // >20% // 90% dvtPerSecond = (maxDvtPerSecond * 9) / 10; } else { // >25% // 100% dvtPerSecond = maxDvtPerSecond; } } /// @notice update totalRewardsEarned, update cumulative profit per lp token function updateRewards() private { if ( block.timestamp > lastRewardTimestamp && lastRewardTimestamp < endTimestamp && endTimestamp != 0 ) { uint256 lpSupply = totalLpToken; if (lpSupply > 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; lastRewardTimestamp = endTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; lastRewardTimestamp = block.timestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; totalRewardsEarned += dvtReward; accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } emit LogUpdateRewards( lastRewardTimestamp, lpSupply, accDvtPerShare ); } } constructor( address _devt, address _dvt, address _owner, uint256 _targetPledgeAmount ) { require(_devt != address(0) && _dvt != address(0) && _owner != address(0), "set address is zero"); require(_targetPledgeAmount != 0,"set targetPledgeAmount is zero" ); targetPledgeAmount = _targetPledgeAmount; devt = ERC20(_devt); dvt = ERC20(_dvt); transferOwnership(_owner); } /// @notice Initialize variables function init() external onlyOwner { require(endTimestamp == 0, "Cannot init again"); uint256 rewardsAmount; if (devt == dvt) { rewardsAmount = dvt.balanceOf(address(this)) - devtTotalDeposits; } else { rewardsAmount = dvt.balanceOf(address(this)); } require(rewardsAmount > 0, "No rewards sent"); maxDvtPerSecond = rewardsAmount / LIFECYCLE; endTimestamp = block.timestamp + LIFECYCLE; lastRewardTimestamp = block.timestamp; refreshDevtRate(); } /// @notice Get mining utilization function utilization() public view returns (uint256 util) { util = (devtTotalDeposits * 1 ether) / targetPledgeAmount; } /// @notice Get mining efficiency bonus for different pledge time function getBoost(Lock _lock) public pure returns (uint256 boost, uint256 timelock) { if (_lock == Lock.twoWeeks) { // 20% return (2e17, 14 days); } else if (_lock == Lock.oneMonth) { // 50% return (5e17, 30 days); } else if (_lock == Lock.twoMonths) { // 100% return (1e18, 60 days); } else { revert("Invalid lock value"); } } /// @notice Get the user's cumulative revenue as of the current time function pendingRewards(address _user) external view returns (uint256 pending) { UserInfo storage user = userInfo[_user]; uint256 _accDvtPerShare = accDvtPerShare; uint256 lpSupply = totalLpToken; if (block.timestamp > lastRewardTimestamp && dvtPerSecond != 0) { uint256 timeDelta; if (block.timestamp > endTimestamp) { timeDelta = endTimestamp - lastRewardTimestamp; } else { timeDelta = block.timestamp - lastRewardTimestamp; } uint256 dvtReward = timeDelta * dvtPerSecond; _accDvtPerShare += (dvtReward * 1 ether) / lpSupply; } pending = (((user.lpAmount * _accDvtPerShare) / 1 ether).toInt256() - user.rewardDebt).toUint256(); } /// @notice Pledge devt function deposit(uint256 _amount, Lock _lock) external { require(!userInfo[msg.sender].isDeposit, "Already desposit"); updateRewards(); require(endTimestamp != 0, "Not initialized"); if (_lock == Lock.twoWeeks) { // give 1 DAY of grace period require( block.timestamp + 14 days - 1 days <= endTimestamp, "Less than 2 weeks left" ); } else if (_lock == Lock.oneMonth) { // give 2 DAY of grace period require( block.timestamp + 30 days - 2 days <= endTimestamp, "Less than 1 month left" ); } else if (_lock == Lock.twoMonths) { // give 3 DAY of grace period require( block.timestamp + 60 days - 3 days <= endTimestamp, "Less than 2 months left" ); } else { revert("Invalid lock value"); } (uint256 boost, uint256 timelock) = getBoost(_lock); uint256 lpAmount = _amount + (_amount * boost) / 1 ether; devtTotalDeposits += _amount; totalLpToken += lpAmount; userInfo[msg.sender] = UserInfo( _amount, lpAmount, block.timestamp + timelock, ((lpAmount * accDvtPerShare) / 1 ether).toInt256(), _lock, true ); devt.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _amount); refreshDevtRate(); } /// @notice Withdraw the principal and income after maturity function withdraw() external { updateRewards(); UserInfo storage user = userInfo[msg.sender]; require(user.depositAmount > 0, "Position does not exists"); // anyone can withdraw when mine ends or kill swith was used if (block.timestamp < endTimestamp) { require( block.timestamp >= user.lockedUntil, "Position is still locked" ); } totalLpToken -= user.lpAmount; devtTotalDeposits -= user.depositAmount; int256 accumulatedDvt = ((user.lpAmount * accDvtPerShare) / 1 ether) .toInt256(); uint256 _pendingDvt = (accumulatedDvt - user.rewardDebt).toUint256(); devt.safeTransfer(msg.sender, user.depositAmount); // Withdrawal income if (_pendingDvt != 0) { dvt.safeTransfer(msg.sender, _pendingDvt); } emit Harvest(msg.sender, _pendingDvt); emit Withdraw(msg.sender, user.depositAmount); delete userInfo[msg.sender]; refreshDevtRate(); } /// @notice After the event is over, recover the unearthed dvt function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } } }
recycleLeftovers
function recycleLeftovers() external onlyOwner { updateRewards(); require(block.timestamp > endTimestamp, "Will not recycle before end"); int256 recycleAmount = (LIFECYCLE * maxDvtPerSecond).toInt256() - // rewards originally sent (totalRewardsEarned).toInt256(); // rewards distributed to users if (recycleAmount > 0){ dvt.safeTransfer(owner(), uint256(recycleAmount)); } }
/// @notice After the event is over, recover the unearthed dvt
NatSpecSingleLine
v0.8.11+commit.d7f03943
{ "func_code_index": [ 8900, 9360 ] }
5,732
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
mul
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 89, 483 ] }
5,733
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
div
function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 567, 858 ] }
5,734
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
sub
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; }
/** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 972, 1094 ] }
5,735
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
add
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 1158, 1293 ] }
5,736
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev Total number of tokens in existence */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 217, 305 ] }
5,737
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 463, 795 ] }
5,738
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 1001, 1105 ] }
5,739
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 401, 891 ] }
5,740
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 1517, 1712 ] }
5,741
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 2036, 2201 ] }
5,742
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
increaseApproval
function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 2661, 2971 ] }
5,743
MundoGold
MundoGold.sol
0x21f7816e12cc0b60a2353c8ebebc94cc44f1e53a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
decreaseApproval
function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://8944a42b762efda223dbdb8c46fb3eaed8711c6cdd3ddcbabe5a8a40f1ce9d0b
{ "func_code_index": [ 3436, 3886 ] }
5,744
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
_loadOriginalMices
function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; }
/** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 1780, 2357 ] }
5,745
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
mintInternal
function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } }
/** * @dev Mint internal, this is to avoid code duplication. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 2437, 3039 ] }
5,746
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
mint
function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); }
/** * @dev Mints new tokens. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3087, 3409 ] }
5,747
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
killForever
function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); }
/** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3522, 3781 ] }
5,748
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
letterToNumber
function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); }
/** * @dev Helper function to reduce pixel size within contract */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4580, 4938 ] }
5,749
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
hashToSVG
function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; }
/** * @dev Hash to SVG function */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4989, 9018 ] }
5,750
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
hashToMetadata
function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); }
/** * @dev Hash to metadata function */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 9074, 11230 ] }
5,751
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
tokenURI
function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); }
/** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 11375, 12790 ] }
5,752
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
_tokenIdToHash
function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; }
/** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 12914, 13814 ] }
5,753
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
walletOfOwner
function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; }
/** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 13972, 14332 ] }
5,754
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
clearBurnedTraits
function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } }
/** * @dev Clears the traits. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 15152, 15321 ] }
5,755
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
addBurnedTraitType
function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; }
/** * @dev Add trait types of burned * @param traits Array of traits to add */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 15422, 15899 ] }
5,756
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
withdraw
function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); }
/** * @dev Collects the total amount in the contract */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 15971, 16115 ] }
5,757
AnonymiceResuscitator
contracts/AnonymiceResuscitator.sol
0x86b130ebb01a1c22f0be5215da29dabbebc43ea8
Solidity
AnonymiceResuscitator
contract AnonymiceResuscitator is ERC721Enumerable, Ownable { using AnonymiceLibrary for uint8; //Mappings uint16[6450] internal tokenToOriginalMiceId; uint256 internal nextOriginalMiceToLoad = 0; OriginalAnonymiceInterface.Trait[] internal burnedTraitType; //uint256s uint256 MAX_SUPPLY = 6450; uint256 FREE_MINTS = 500; uint256 PRICE = .03 ether; //addresses address anonymiceContract = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //events event TokenMinted(uint256 supply); constructor() ERC721("Anonymice Burned", "bMICE") { } // ███╗ ███╗██╗███╗ ██╗████████╗██╗███╗ ██╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ████╗ ████║██║████╗ ██║╚══██╔══╝██║████╗ ██║██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██╔████╔██║██║██╔██╗ ██║ ██║ ██║██╔██╗ ██║██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║╚██╔╝██║██║██║╚██╗██║ ██║ ██║██║╚██╗██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ╚═╝ ██║██║██║ ╚████║ ██║ ██║██║ ╚████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Loads the IDs of burned mices * @param _howMany The number of mices to load. Starts from the last loaded */ function _loadOriginalMices(uint256 _howMany) internal { require(nextOriginalMiceToLoad <= MAX_SUPPLY, "All possible mices loaded"); ERC721Enumerable originalMiceCollection = ERC721Enumerable(anonymiceContract); uint start = nextOriginalMiceToLoad; for (uint i=start; (i<start+_howMany && i<MAX_SUPPLY); i++) { uint id = originalMiceCollection.tokenOfOwnerByIndex(0x000000000000000000000000000000000000dEaD, i); tokenToOriginalMiceId[i] = uint16(id); } nextOriginalMiceToLoad = start + _howMany; } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal(uint256 num_tokens, address to) internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY, 'Sale would exceed max supply'); require(!AnonymiceLibrary.isContract(msg.sender)); if ((num_tokens + _totalSupply) > MAX_SUPPLY) { num_tokens = MAX_SUPPLY - _totalSupply; } _loadOriginalMices(num_tokens); for (uint i=0; i < num_tokens; i++) { _safeMint(to, _totalSupply); emit TokenMinted(_totalSupply); _totalSupply = _totalSupply + 1; } } /** * @dev Mints new tokens. */ function mint(address _to, uint _count) public payable { uint _totalSupply = totalSupply(); if (_totalSupply > FREE_MINTS) { require(PRICE*_count <= msg.value, 'Not enough ether sent (send 0.03 eth for each mice you want to mint)'); } return mintInternal(_count, _to); } /** * @dev Kills the mice again, this time forever. * @param _tokenId The token to burn. */ function killForever(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); } // ██████╗ ███████╗ █████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔══██╗██╔════╝██╔══██╗██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██████╔╝█████╗ ███████║██║ ██║ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ██║ ██║███████╗██║ ██║██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } for ( uint16 j = 0; j < trait.pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( trait.pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}.c65{fill:#4F10FF}.c66{fill:#3D9EFD}.c67{fill:#98FFE0}.c68{fill:#45C4F8}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash, uint _tokenId) public view returns (string memory) { string memory metadataString; OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); OriginalAnonymiceInterface.Trait memory trait; if (i == 0) { trait = OriginalAnonymiceInterface.Trait( burnedTraitType[thisTraitIndex].traitName, burnedTraitType[thisTraitIndex].traitType, burnedTraitType[thisTraitIndex].pixels, burnedTraitType[thisTraitIndex].pixelCount ); } else { (string memory traitName, string memory traitType, string memory pixels, uint pixelCount) = originalMiceCollection.traitTypes(i, thisTraitIndex); trait = OriginalAnonymiceInterface.Trait( traitName, traitType, pixels, pixelCount ); } metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', trait.traitType, '","value":"', trait.traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } // add the property of original token id number metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', 'Original Mice Token Id', '","value":"', AnonymiceLibrary.toString(tokenToOriginalMiceId[_tokenId]), '"}' ) ); return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice Burned is a collection of 6,450 burned mices from the Anonymice collection, with the same traits as the burned ones. Like the original collection, metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain. And a group of resurrected mices", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash, _tokenId), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { OriginalAnonymiceInterface originalMiceCollection = OriginalAnonymiceInterface(anonymiceContract); string memory tokenHash = originalMiceCollection._tokenIdToHash(uint256(tokenToOriginalMiceId[_tokenId])); //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } else { tokenHash = string( abi.encodePacked( "0", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } // ██████╗ ██╗ ██╗███╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ // ██╔═══██╗██║ ██║████╗ ██║██╔════╝██╔══██╗ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ // ██║ ██║██║ █╗ ██║██╔██╗ ██║█████╗ ██████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ // ██║ ██║██║███╗██║██║╚██╗██║██╔══╝ ██╔══██╗ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ // ╚██████╔╝╚███╔███╔╝██║ ╚████║███████╗██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║███████║ // ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ /** * @dev Clears the traits. */ function clearBurnedTraits() public onlyOwner { for (uint256 i = 0; i < burnedTraitType.length; i++) { delete burnedTraitType[i]; } } /** * @dev Add trait types of burned * @param traits Array of traits to add */ function addBurnedTraitType(OriginalAnonymiceInterface.Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { burnedTraitType.push( OriginalAnonymiceInterface.Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Collects the total amount in the contract */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */ function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; } }
// d8888 d8b 888888b. 888 // d88888 Y8P 888 "88b 888 // d88P888 888 .88P 888 // d88P 888 88888b. .d88b. 88888b. 888 888 88888b.d88b. 888 .d8888b .d88b. 8888888K. 888 888 888d888 88888b. .d88b. .d88888 // d88P 888 888 "88b d88""88b 888 "88b 888 888 888 "888 "88b 888 d88P" d8P Y8b 888 "Y88b 888 888 888P" 888 "88b d8P Y8b d88" 888 // d88P 888 888 888 888 888 888 888 888 888 888 888 888 888 888 88888888 888 888 888 888 888 888 888 88888888 888 888 // d8888888888 888 888 Y88..88P 888 888 Y88b 888 888 888 888 888 Y88b. Y8b. 888 d88P Y88b 888 888 888 888 Y8b. Y88b 888 // d88P 888 888 888 "Y88P" 888 888 "Y88888 888 888 888 888 "Y8888P "Y8888 8888888P" "Y88888 888 888 888 "Y8888 "Y88888 // 888 // Y8b d88P // "Y88P"
LineComment
setAnonymiceOriginalContractAddress
function setAnonymiceOriginalContractAddress(address newAddress) public onlyOwner { anonymiceContract = newAddress; }
/** * @dev Collects the total amount in the contract * @param newAddress The new address of the anonymice contract */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 16254, 16387 ] }
5,758
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
MarsToken
function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes }
/** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 840, 1384 ] }
5,759
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
_transfer
function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); }
/** * Internal transfer, only can be called by this contract */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 1468, 2316 ] }
5,760
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
transfer
function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); }
/** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 2522, 2634 ] }
5,761
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; }
/** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 2909, 3210 ] }
5,762
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; }
/** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 3474, 3650 ] }
5,763
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
/** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 4044, 4396 ] }
5,764
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
burn
function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; }
/** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 4566, 4945 ] }
5,765
MarsToken
MarsToken.sol
0xa4ed9049231e764c778ecd9f57f5ba0114a880bb
Solidity
MarsToken
contract MarsToken { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function MarsToken( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
burnFrom
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; }
/** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://d3c5b8ff115a74da5f66c2c6a3e09ce7367543233b08d386c23c008db9d53f56
{ "func_code_index": [ 5203, 5819 ] }
5,766
SMEBankingPlatformSale2
SMEBankingPlatformSale2.sol
0x3cfdef8abfb4cc4c8485fb580658aac352e05874
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://c902121207727c3362958437854bfcb24886b99f27349e89a13e730e54f27c69
{ "func_code_index": [ 89, 272 ] }
5,767
SMEBankingPlatformSale2
SMEBankingPlatformSale2.sol
0x3cfdef8abfb4cc4c8485fb580658aac352e05874
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://c902121207727c3362958437854bfcb24886b99f27349e89a13e730e54f27c69
{ "func_code_index": [ 356, 629 ] }
5,768
SMEBankingPlatformSale2
SMEBankingPlatformSale2.sol
0x3cfdef8abfb4cc4c8485fb580658aac352e05874
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://c902121207727c3362958437854bfcb24886b99f27349e89a13e730e54f27c69
{ "func_code_index": [ 744, 860 ] }
5,769
SMEBankingPlatformSale2
SMEBankingPlatformSale2.sol
0x3cfdef8abfb4cc4c8485fb580658aac352e05874
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://c902121207727c3362958437854bfcb24886b99f27349e89a13e730e54f27c69
{ "func_code_index": [ 924, 1060 ] }
5,770
SMEBankingPlatformSale2
SMEBankingPlatformSale2.sol
0x3cfdef8abfb4cc4c8485fb580658aac352e05874
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() public { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://c902121207727c3362958437854bfcb24886b99f27349e89a13e730e54f27c69
{ "func_code_index": [ 257, 317 ] }
5,771
SMEBankingPlatformSale2
SMEBankingPlatformSale2.sol
0x3cfdef8abfb4cc4c8485fb580658aac352e05874
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://c902121207727c3362958437854bfcb24886b99f27349e89a13e730e54f27c69
{ "func_code_index": [ 636, 812 ] }
5,772
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
setMintPassToken
function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); }
/** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 2802, 2974 ] }
5,773
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
setBaseURI
function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; }
/** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3106, 3259 ] }
5,774
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
pause
function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); }
/** * @notice Pause redeems until unpause is called */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3328, 3421 ] }
5,775
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
unpause
function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); }
/** * @notice Unpause redeems until pause is called */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3490, 3587 ] }
5,776
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
setRedeemStart
function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; }
/** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 3734, 3922 ] }
5,777
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
setRedeemClose
function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; }
/** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4064, 4249 ] }
5,778
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
setMaxRedeemPerTxn
function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; }
/** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4446, 4652 ] }
5,779
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
isRedemptionOpen
function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; }
/** * @notice Check if redemption window is open * * @param passID the pass index to check */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 4769, 5049 ] }
5,780
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
mintNextTokenTo
function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); }
/** * @notice Mint next token * * @param _to receiver address */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 5137, 5296 ] }
5,781
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
redeem
function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); }
/** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 5493, 7010 ] }
5,782
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
setIndividualTokenURI
function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; }
/** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7420, 7687 ] }
5,783
Collectible
contracts/Collectible.sol
0x6c1ab37ae847af0d0381f5792b457ae4f41e1aa1
Solidity
Collectible
contract Collectible is ICollectible, AccessControl, ERC721Enumerable, ERC721Pausable, ERC721Burnable, Ownable { using Strings for uint256; using ECDSA for bytes32; using Counters for Counters.Counter; Counters.Counter private generalCounter; mapping(uint256 => TokenData) public tokenData; mapping(uint256 => RedemptionWindow) public redemptionWindows; struct TokenData { string tokenURI; bool exists; } struct RedemptionWindow { uint256 windowOpens; uint256 windowCloses; uint256 maxRedeemPerTxn; } string private baseTokenURI; string public _contractURI; MintPassFactory public mintPassFactory; event Redeemed(address indexed account, string tokens); /** * @notice Constructor to create Collectible * * @param _symbol the token symbol * @param _mpIndexes the mintpass indexes to accommodate * @param _redemptionWindowsOpen the mintpass redemption window open unix timestamp by index * @param _redemptionWindowsClose the mintpass redemption window close unix timestamp by index * @param _maxRedeemPerTxn the max mint per redemption by index * @param _baseTokenURI the respective base URI * @param _contractMetaDataURI the respective contract meta data URI * @param _mintPassToken contract address of MintPass token to be burned */ constructor ( string memory _name, string memory _symbol, uint256[] memory _mpIndexes, uint256[] memory _redemptionWindowsOpen, uint256[] memory _redemptionWindowsClose, uint256[] memory _maxRedeemPerTxn, string memory _baseTokenURI, string memory _contractMetaDataURI, address _mintPassToken ) ERC721(_name, _symbol) { baseTokenURI = _baseTokenURI; _contractURI = _contractMetaDataURI; mintPassFactory = MintPassFactory(_mintPassToken); generalCounter.increment(); for(uint256 i = 0; i < _mpIndexes.length; i++) { uint passID = _mpIndexes[i]; redemptionWindows[passID].windowOpens = _redemptionWindowsOpen[i]; redemptionWindows[passID].windowCloses = _redemptionWindowsClose[i]; redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn[i]; } _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(DEFAULT_ADMIN_ROLE, 0x81745b7339D5067E82B93ca6BBAd125F214525d3); _setupRole(DEFAULT_ADMIN_ROLE, 0x90bFa85209Df7d86cA5F845F9Cd017fd85179f98); _setupRole(DEFAULT_ADMIN_ROLE, 0x7F379e2ca3c7e626aaF5B76A9507a5e909f72Db5); } /** * @notice Set the mintpass contract address * * @param _mintPassToken the respective Mint Pass contract address */ function setMintPassToken(address _mintPassToken) external override onlyRole(DEFAULT_ADMIN_ROLE) { mintPassFactory = MintPassFactory(_mintPassToken); } /** * @notice Change the base URI for returning metadata * * @param _baseTokenURI the respective base URI */ function setBaseURI(string memory _baseTokenURI) external override onlyRole(DEFAULT_ADMIN_ROLE) { baseTokenURI = _baseTokenURI; } /** * @notice Pause redeems until unpause is called */ function pause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * @notice Unpause redeems until pause is called */ function unpause() external override onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /** * @notice Configure time to enable redeem functionality * * @param _windowOpen UNIX timestamp for redeem start */ function setRedeemStart(uint256 passID, uint256 _windowOpen) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowOpens = _windowOpen; } /** * @notice Configure time to enable redeem functionality * * @param _windowClose UNIX timestamp for redeem close */ function setRedeemClose(uint256 passID, uint256 _windowClose) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].windowCloses = _windowClose; } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param _maxRedeemPerTxn number of passes that can be redeemed */ function setMaxRedeemPerTxn(uint256 passID, uint256 _maxRedeemPerTxn) external override onlyRole(DEFAULT_ADMIN_ROLE) { redemptionWindows[passID].maxRedeemPerTxn = _maxRedeemPerTxn; } /** * @notice Check if redemption window is open * * @param passID the pass index to check */ function isRedemptionOpen(uint256 passID) public view override returns (bool) { if(paused()){ return false; } return block.timestamp > redemptionWindows[passID].windowOpens && block.timestamp < redemptionWindows[passID].windowCloses; } /** * @notice Mint next token * * @param _to receiver address */ function mintNextTokenTo(address _to) external onlyOwner { _safeMint(_to, generalCounter.current()); generalCounter.increment(); } /** * @notice Redeem specified amount of MintPass tokens * * @param mpIndexes the tokenIDs of MintPasses to redeem * @param amounts the amount of MintPasses to redeem */ function redeem(uint256[] calldata mpIndexes, uint256[] calldata amounts) external override{ require(msg.sender == tx.origin, "Redeem: not allowed from contract"); require(!paused(), "Redeem: paused"); //check to make sure all are valid then re-loop for redemption for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); } string memory tokens = ""; for(uint256 i = 0; i < mpIndexes.length; i++) { mintPassFactory.burnFromRedeem(msg.sender, mpIndexes[i], amounts[i]); for(uint256 j = 0; j < amounts[i]; j++) { _safeMint(msg.sender, generalCounter.current()); tokens = string(abi.encodePacked(tokens, generalCounter.current().toString(), ",")); generalCounter.increment(); } } emit Redeemed(msg.sender, tokens); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl,IERC165, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice Configure the max amount of passes that can be redeemed in a txn for a specific pass index * * @param id of token * @param uri to point the token to */ function setIndividualTokenURI(uint256 id, string memory uri) external override onlyRole(DEFAULT_ADMIN_ROLE){ require(_exists(id), "ERC721Metadata: Token does not exist"); tokenData[id].tokenURI = uri; tokenData[id].exists = true; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } function setContractURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE){ _contractURI = uri; } function contractURI() public view returns (string memory) { return _contractURI; } }
/* * @title ERC721 token for Collectible, redeemable through burning MintPass tokens */
Comment
tokenURI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(tokenData[tokenId].exists){ return tokenData[tokenId].tokenURI; } return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); }
/** * @dev See {IERC721Metadata-tokenURI}. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 7753, 8123 ] }
5,784
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() public { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 261, 321 ] }
5,785
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 644, 820 ] }
5,786
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 268, 659 ] }
5,787
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 865, 977 ] }
5,788
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 401, 853 ] }
5,789
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 1485, 1675 ] }
5,790
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 1999, 2130 ] }
5,791
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
increaseApproval
function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 2596, 2860 ] }
5,792
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
decreaseApproval
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 3331, 3741 ] }
5,793
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
MintableToken
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } }
/** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */
NatSpecMultiLine
mint
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; }
/** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 483, 754 ] }
5,794
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
MintableToken
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } }
/** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */
NatSpecMultiLine
finishMinting
function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; }
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 871, 1013 ] }
5,795
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
AltTokenDistribution
contract AltTokenDistribution is Ownable { using SafeMath for uint256; AltTokenInterface public token; event DistributionMint(address indexed to, uint256 amount); function AltTokenDistribution (address _tokenAddress) public { require(_tokenAddress != 0); token = AltTokenInterface(_tokenAddress); } /** * @dev Minting required amount of tokens in a loop * @param _investors The array of addresses of investors * @param _amounts The array of token amounts corresponding to investors */ function bulkMint(address[] _investors, uint256[] _amounts) onlyOwner public returns (bool) { // require(_investors.length < 50); require(_investors.length == _amounts.length); for (uint index = 0; index < _investors.length; index++) { assert(token.mint(_investors[index], _amounts[index])); DistributionMint(_investors[index], _amounts[index]); } } /** * @dev Return ownership to previous owner */ function returnOwnership() onlyOwner public returns (bool) { token.transferOwnership(owner); } }
bulkMint
function bulkMint(address[] _investors, uint256[] _amounts) onlyOwner public returns (bool) { // require(_investors.length < 50); require(_investors.length == _amounts.length); for (uint index = 0; index < _investors.length; index++) { assert(token.mint(_investors[index], _amounts[index])); DistributionMint(_investors[index], _amounts[index]); } }
/** * @dev Minting required amount of tokens in a loop * @param _investors The array of addresses of investors * @param _amounts The array of token amounts corresponding to investors */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 532, 923 ] }
5,796
AltTokenDistribution
AltTokenDistribution.sol
0xd002413b8865f098df5f00da3d9ea32086ee944d
Solidity
AltTokenDistribution
contract AltTokenDistribution is Ownable { using SafeMath for uint256; AltTokenInterface public token; event DistributionMint(address indexed to, uint256 amount); function AltTokenDistribution (address _tokenAddress) public { require(_tokenAddress != 0); token = AltTokenInterface(_tokenAddress); } /** * @dev Minting required amount of tokens in a loop * @param _investors The array of addresses of investors * @param _amounts The array of token amounts corresponding to investors */ function bulkMint(address[] _investors, uint256[] _amounts) onlyOwner public returns (bool) { // require(_investors.length < 50); require(_investors.length == _amounts.length); for (uint index = 0; index < _investors.length; index++) { assert(token.mint(_investors[index], _amounts[index])); DistributionMint(_investors[index], _amounts[index]); } } /** * @dev Return ownership to previous owner */ function returnOwnership() onlyOwner public returns (bool) { token.transferOwnership(owner); } }
returnOwnership
function returnOwnership() onlyOwner public returns (bool) { token.transferOwnership(owner); }
/** * @dev Return ownership to previous owner */
NatSpecMultiLine
v0.4.18+commit.9cf6e910
bzzr://b40d957cdda0995d78da414d62355b2616db479c8fdec65719fa91a9deed9a9e
{ "func_code_index": [ 984, 1089 ] }
5,797
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
Relay3rV1
function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); }
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 456, 793 ] }
5,798
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
totalSupply
function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 981, 1102 ] }
5,799
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
balanceOf
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 1322, 1451 ] }
5,800
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transfer
function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 1795, 2072 ] }
5,801
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approve
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 2580, 2788 ] }
5,802
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; }
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 3319, 3677 ] }
5,803
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
allowance
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 3960, 4116 ] }
5,804
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
approveAndCall
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
// ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 4471, 4788 ] }
5,805
Relay3rV1
Relay3rV1.sol
0x33b8def547be4b4893d6152b9ffe799db5b72092
Solidity
Relay3rV1
contract Relay3rV1 is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Relay3rV1() public { symbol = "RL3R"; name = "Relay3rV1"; decimals = 18; _totalSupply = 200000000000000000000000; balances[0x77d286886559FCdF656ed1688916051d24A57512] = _totalSupply; Transfer(address(0), 0x77d286886559FCdF656ed1688916051d24A57512, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ----------------------------------------------------------------------------
LineComment
function () public payable { revert(); }
// ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------
LineComment
v0.4.23+commit.124ca40d
None
bzzr://f57dea9194362bdf497f1ccbfe9d1c67037ceb88d8a870ea9ac5b388de83d20f
{ "func_code_index": [ 4980, 5039 ] }
5,806