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
Americo
Americo.sol
0x09eaf7b80ec741fa8a163cd4dde8367fab37e8a0
Solidity
Americo
contract Americo { /* Variables públicas del token */ string public standard = 'Token 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; uint256 public totalSupply; /* Esto crea una matriz con todos los saldos */ mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; /* Inicializa el contrato con los tokens de suministro inicial al creador del contrato */ function Americo() { initialSupply=160000000; name="Americo"; decimals=6; symbol="A"; balanceOf[msg.sender] = initialSupply; // Americo recibe todas las fichas iniciales totalSupply = initialSupply; // Actualizar la oferta total } /* Send coins */ function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; // Compruebe si el remitente tiene suficiente if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Verificar desbordamientos balanceOf[msg.sender] -= _value; // Reste del remitente balanceOf[_to] += _value; // Agregue lo mismo al destinatario } /* Esta función sin nombre se llama cada vez que alguien intenta enviar éter a ella */ function () { throw; // Evita el envío accidental de éter } }
function () { throw; // Evita el envío accidental de éter }
/* Esta función sin nombre se llama cada vez que alguien intenta enviar éter a ella */
Comment
v0.4.19+commit.c4cbbb05
bzzr://2bb40ed958008e5bbe69da40c3b5da723d2539387782f8a45ee0dd3e5e3eb1b4
{ "func_code_index": [ 1482, 1564 ] }
3,707
SharkOutlawSquad
/contracts/SharkOutlawSquad.sol
0xa4eacdf4af749060a22aefe06337cb9fb96d45fb
Solidity
SharkOutlawSquad
contract SharkOutlawSquad is Ownable, EIP712, ERC721Enumerable { using Strings for uint256; // Whitelist bytes32 public constant WHITELIST_TYPEHASH = keccak256("Whitelist(address buyer,uint256 signedQty)"); address public whitelistSigner; // Specification uint256 public constant TOTAL_MAX_QTY = 7777; uint256 public constant GIFT_MAX_QTY = 77; uint256 public constant PRESALES_MAX_QTY = 3333; uint256 public constant PRESALES_MAX_QTY_PER_MINTER = 3; uint256 public constant PUBLIC_SALES_MAX_QTY_PER_TRANSACTION = 5; uint256 public constant PUBLIC_SALES_MAX_QTY_PER_MINTER = 10; // Remaining presale quantity can be purchase through public sale uint256 public constant PUBLIC_SALES_MAX_QTY = TOTAL_MAX_QTY - GIFT_MAX_QTY; uint256 public constant PRESALES_PRICE = 0.05 ether; uint256 public constant PUBLIC_SALES_PRICE = 0.06 ether; string private _contractURI; string private _tokenBaseURI; // Minter to token mapping(address => uint256) public presalesMinterToTokenQty; mapping(address => uint256) public publicSalesMinterToTokenQty; // Quantity minted uint256 public presalesMintedQty = 0; uint256 public publicSalesMintedQty = 0; uint256 public giftedQty = 0; // Sales status bool public isPresalesActivated; bool public isPublicSalesActivated; constructor() ERC721("Shark Outlaw Squad", "SHARK") EIP712("Shark Outlaw Squad", "1") {} function setWhitelistSigner(address _address) external onlyOwner { whitelistSigner = _address; } function getSigner( address _buyer, uint256 _signedQty, bytes memory _signature ) public view returns (address) { bytes32 digest = _hashTypedDataV4( keccak256(abi.encode(WHITELIST_TYPEHASH, _buyer, _signedQty)) ); return ECDSA.recover(digest, _signature); } function presalesMint( uint256 _mintQty, uint256 _signedQty, bytes memory _signature ) external payable { require( totalSupply() + _mintQty <= TOTAL_MAX_QTY, "Exceed total max limit" ); require(isPresalesActivated, "Presales is closed"); require( getSigner(msg.sender, _signedQty, _signature) == whitelistSigner, "Invalid signature" ); require( presalesMintedQty + _mintQty <= PRESALES_MAX_QTY, "Exceed presales max limit" ); require( presalesMinterToTokenQty[msg.sender] + _mintQty <= _signedQty, "Exceed presales signed quantity" ); require( presalesMinterToTokenQty[msg.sender] + _mintQty <= PRESALES_MAX_QTY_PER_MINTER, "Exceed presales max quantity per minter" ); require(msg.value >= PRESALES_PRICE * _mintQty, "Insufficient ETH"); presalesMinterToTokenQty[msg.sender] += _mintQty; for (uint256 i = 0; i < _mintQty; i++) { presalesMintedQty++; _safeMint(msg.sender, totalSupply() + 1); } } function publicSalesMint(uint256 _mintQty) external payable { require( totalSupply() + _mintQty <= TOTAL_MAX_QTY, "Exceed total max limit" ); require(isPublicSalesActivated, "Public sale is closed"); require( presalesMintedQty + publicSalesMintedQty + _mintQty <= PUBLIC_SALES_MAX_QTY, "Exceed public sale max limit" ); require( publicSalesMinterToTokenQty[msg.sender] + _mintQty <= PUBLIC_SALES_MAX_QTY_PER_MINTER, "Exceed public sales max quantity per minter" ); require( _mintQty <= PUBLIC_SALES_MAX_QTY_PER_TRANSACTION, "Exceed public sales max quantity per transaction" ); require(msg.value >= PUBLIC_SALES_PRICE * _mintQty, "Insufficient ETH"); publicSalesMinterToTokenQty[msg.sender] += _mintQty; for (uint256 i = 0; i < _mintQty; i++) { publicSalesMintedQty++; _safeMint(msg.sender, totalSupply() + 1); } } function gift(address[] calldata receivers) external onlyOwner { require( totalSupply() + receivers.length <= TOTAL_MAX_QTY, "Exceed total max limit" ); require( giftedQty + receivers.length <= GIFT_MAX_QTY, "Exceed gift max limit" ); for (uint256 i = 0; i < receivers.length; i++) { giftedQty++; _safeMint(receivers[i], totalSupply() + 1); } } function withdrawAll() external onlyOwner { require(address(this).balance > 0, "No amount to withdraw"); payable(msg.sender).transfer(address(this).balance); } function togglePresalesStatus() external onlyOwner { isPresalesActivated = !isPresalesActivated; } function togglePublicSalesStatus() external onlyOwner { isPublicSalesActivated = !isPublicSalesActivated; } function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; } // To support Opensea contract-level metadata // https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return _contractURI; } function setBaseURI(string calldata URI) external onlyOwner { _tokenBaseURI = URI; } // To support Opensea token metadata // https://docs.opensea.io/docs/metadata-standards function tokenURI(uint256 _tokenId) public view override(ERC721) returns (string memory) { require(_exists(_tokenId), "Token not exist"); return string(abi.encodePacked(_tokenBaseURI, _tokenId.toString())); } }
contractURI
function contractURI() public view returns (string memory) { return _contractURI; }
// To support Opensea contract-level metadata // https://docs.opensea.io/docs/contract-level-metadata
LineComment
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 5343, 5442 ] }
3,708
SharkOutlawSquad
/contracts/SharkOutlawSquad.sol
0xa4eacdf4af749060a22aefe06337cb9fb96d45fb
Solidity
SharkOutlawSquad
contract SharkOutlawSquad is Ownable, EIP712, ERC721Enumerable { using Strings for uint256; // Whitelist bytes32 public constant WHITELIST_TYPEHASH = keccak256("Whitelist(address buyer,uint256 signedQty)"); address public whitelistSigner; // Specification uint256 public constant TOTAL_MAX_QTY = 7777; uint256 public constant GIFT_MAX_QTY = 77; uint256 public constant PRESALES_MAX_QTY = 3333; uint256 public constant PRESALES_MAX_QTY_PER_MINTER = 3; uint256 public constant PUBLIC_SALES_MAX_QTY_PER_TRANSACTION = 5; uint256 public constant PUBLIC_SALES_MAX_QTY_PER_MINTER = 10; // Remaining presale quantity can be purchase through public sale uint256 public constant PUBLIC_SALES_MAX_QTY = TOTAL_MAX_QTY - GIFT_MAX_QTY; uint256 public constant PRESALES_PRICE = 0.05 ether; uint256 public constant PUBLIC_SALES_PRICE = 0.06 ether; string private _contractURI; string private _tokenBaseURI; // Minter to token mapping(address => uint256) public presalesMinterToTokenQty; mapping(address => uint256) public publicSalesMinterToTokenQty; // Quantity minted uint256 public presalesMintedQty = 0; uint256 public publicSalesMintedQty = 0; uint256 public giftedQty = 0; // Sales status bool public isPresalesActivated; bool public isPublicSalesActivated; constructor() ERC721("Shark Outlaw Squad", "SHARK") EIP712("Shark Outlaw Squad", "1") {} function setWhitelistSigner(address _address) external onlyOwner { whitelistSigner = _address; } function getSigner( address _buyer, uint256 _signedQty, bytes memory _signature ) public view returns (address) { bytes32 digest = _hashTypedDataV4( keccak256(abi.encode(WHITELIST_TYPEHASH, _buyer, _signedQty)) ); return ECDSA.recover(digest, _signature); } function presalesMint( uint256 _mintQty, uint256 _signedQty, bytes memory _signature ) external payable { require( totalSupply() + _mintQty <= TOTAL_MAX_QTY, "Exceed total max limit" ); require(isPresalesActivated, "Presales is closed"); require( getSigner(msg.sender, _signedQty, _signature) == whitelistSigner, "Invalid signature" ); require( presalesMintedQty + _mintQty <= PRESALES_MAX_QTY, "Exceed presales max limit" ); require( presalesMinterToTokenQty[msg.sender] + _mintQty <= _signedQty, "Exceed presales signed quantity" ); require( presalesMinterToTokenQty[msg.sender] + _mintQty <= PRESALES_MAX_QTY_PER_MINTER, "Exceed presales max quantity per minter" ); require(msg.value >= PRESALES_PRICE * _mintQty, "Insufficient ETH"); presalesMinterToTokenQty[msg.sender] += _mintQty; for (uint256 i = 0; i < _mintQty; i++) { presalesMintedQty++; _safeMint(msg.sender, totalSupply() + 1); } } function publicSalesMint(uint256 _mintQty) external payable { require( totalSupply() + _mintQty <= TOTAL_MAX_QTY, "Exceed total max limit" ); require(isPublicSalesActivated, "Public sale is closed"); require( presalesMintedQty + publicSalesMintedQty + _mintQty <= PUBLIC_SALES_MAX_QTY, "Exceed public sale max limit" ); require( publicSalesMinterToTokenQty[msg.sender] + _mintQty <= PUBLIC_SALES_MAX_QTY_PER_MINTER, "Exceed public sales max quantity per minter" ); require( _mintQty <= PUBLIC_SALES_MAX_QTY_PER_TRANSACTION, "Exceed public sales max quantity per transaction" ); require(msg.value >= PUBLIC_SALES_PRICE * _mintQty, "Insufficient ETH"); publicSalesMinterToTokenQty[msg.sender] += _mintQty; for (uint256 i = 0; i < _mintQty; i++) { publicSalesMintedQty++; _safeMint(msg.sender, totalSupply() + 1); } } function gift(address[] calldata receivers) external onlyOwner { require( totalSupply() + receivers.length <= TOTAL_MAX_QTY, "Exceed total max limit" ); require( giftedQty + receivers.length <= GIFT_MAX_QTY, "Exceed gift max limit" ); for (uint256 i = 0; i < receivers.length; i++) { giftedQty++; _safeMint(receivers[i], totalSupply() + 1); } } function withdrawAll() external onlyOwner { require(address(this).balance > 0, "No amount to withdraw"); payable(msg.sender).transfer(address(this).balance); } function togglePresalesStatus() external onlyOwner { isPresalesActivated = !isPresalesActivated; } function togglePublicSalesStatus() external onlyOwner { isPublicSalesActivated = !isPublicSalesActivated; } function setContractURI(string calldata URI) external onlyOwner { _contractURI = URI; } // To support Opensea contract-level metadata // https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return _contractURI; } function setBaseURI(string calldata URI) external onlyOwner { _tokenBaseURI = URI; } // To support Opensea token metadata // https://docs.opensea.io/docs/metadata-standards function tokenURI(uint256 _tokenId) public view override(ERC721) returns (string memory) { require(_exists(_tokenId), "Token not exist"); return string(abi.encodePacked(_tokenBaseURI, _tokenId.toString())); } }
tokenURI
function tokenURI(uint256 _tokenId) public view override(ERC721) returns (string memory) { require(_exists(_tokenId), "Token not exist"); return string(abi.encodePacked(_tokenBaseURI, _tokenId.toString())); }
// To support Opensea token metadata // https://docs.opensea.io/docs/metadata-standards
LineComment
v0.8.9+commit.e5eed63a
{ "func_code_index": [ 5642, 5911 ] }
3,709
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
delegate
function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); }
/** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 2115, 2230 ] }
3,710
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
delegateBySig
function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); }
/** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 2742, 4011 ] }
3,711
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
getCurrentVotes
function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
/** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 4268, 4508 ] }
3,712
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
getPriorVotes
function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; }
/** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 4783, 6000 ] }
3,713
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
_delegate
function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); }
/** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 7016, 7438 ] }
3,714
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
_moveDelegates
function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } }
/** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 7884, 9211 ] }
3,715
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
_writeCheckpoint
function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); }
/** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 9600, 10281 ] }
3,716
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
safe32
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); }
/** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 10448, 10613 ] }
3,717
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
safe96
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); }
/** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 10780, 10945 ] }
3,718
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
add96
function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; }
/** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 11106, 11324 ] }
3,719
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
sub96
function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; }
/** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 11495, 11691 ] }
3,720
TimeLockRegistry
contracts/token/VoteToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
VoteToken
abstract contract VoteToken is Context, ERC20, Ownable, IVoteToken, ReentrancyGuard { using LowGasSafeMath for uint256; using Address for address; /* ============ Events ============ */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /* ============ Modifiers ============ */ /* ============ State Variables ============ */ /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @dev A record of votes checkpoints for each account, by index mapping(address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Delegating votes from msg.sender to delegatee * * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * PRIVILEGED GOVERNANCE FUNCTION. Delegate votes using signature to 'delegatee' * * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external override { address signatory; bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); if (prefix) { bytes32 digestHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', digest)); signatory = ecrecover(digestHash, v, r, s); } else { signatory = ecrecover(digest, v, r, s); } require(balanceOf(signatory) > 0, 'VoteToken::delegateBySig: invalid delegator'); require(signatory != address(0), 'VoteToken::delegateBySig: invalid signature'); require(nonce == nonces[signatory], 'VoteToken::delegateBySig: invalid nonce'); nonces[signatory]++; require(block.timestamp <= expiry, 'VoteToken::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * GOVERNANCE FUNCTION. Check Delegate votes using signature to 'delegatee' * * @notice Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) external view virtual override returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * GOVERNANCE FUNCTION. Get voting power at a specific block for an account * * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) external view virtual override returns (uint96) { require(blockNumber < block.number, 'BABLToken::getPriorVotes: not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getMyDelegatee() external view override returns (address) { return delegates[msg.sender]; } function getDelegatee(address account) external view override returns (address) { return delegates[account]; } function getCheckpoints(address account, uint32 id) external view override returns (uint32 fromBlock, uint96 votes) { Checkpoint storage getCheckpoint = checkpoints[account][id]; return (getCheckpoint.fromBlock, getCheckpoint.votes); } function getNumberOfCheckpoints(address account) external view override returns (uint32) { return numCheckpoints[account]; } /* ============ Internal Only Function ============ */ /** * GOVERNANCE FUNCTION. Make a delegation * * @dev Internal function to delegate voting power to an account * @param delegator The address of the account delegating votes from * @param delegatee The address to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = safe96(_balanceOf(delegator), 'VoteToken::_delegate: uint96 overflow'); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf(account); } /** * GOVERNANCE FUNCTION. Move the delegates * * @dev Internal function to move delegates between accounts * @param srcRep The address of the account delegating votes from * @param dstRep The address of the account delegating votes to * @param amount The voting power to move */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { // It must not revert but do nothing in cases of address(0) being part of the move // Sub voting amount to source in case it is not the zero address (e.g. transfers) if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'VoteToken::_moveDelegates: vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // Add it to destination in case it is not the zero address (e.g. any transfer of tokens or delegations except a first mint to a specific address) uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'VoteToken::_moveDelegates: vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * GOVERNANCE FUNCTION. Internal function to write a checkpoint for voting power * * @dev internal function to write a checkpoint for voting power * @param delegatee The address of the account delegating votes to * @param nCheckpoints The num checkpoint * @param oldVotes The previous voting power * @param newVotes The new voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, 'VoteToken::_writeCheckpoint: block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint32 * * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * INTERNAL FUNCTION. Internal function to convert from uint256 to uint96 * * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * INTERNAL FUNCTION. Internal function to add two uint96 numbers * * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * INTERNAL FUNCTION. Internal function to subtract two uint96 numbers * * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
/** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by BABL to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */
NatSpecMultiLine
getChainId
function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; }
/** * INTERNAL FUNCTION. Internal function to get chain ID * * @dev internal function to get chain ID */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 11822, 11998 ] }
3,721
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
disableTokensTransfers
function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 3776, 3986 ] }
3,722
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
enableTokensTransfers
function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 4147, 4248 ] }
3,723
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
setTimeLockRegistry
function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 4542, 5114 ] }
3,724
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
setRewardsDistributor
function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 5457, 6057 ] }
3,725
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
registerLockup
function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 6981, 8219 ] }
3,726
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
cancelVestedTokens
function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); }
/** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 8641, 8814 ] }
3,727
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
claimMyTokens
function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); }
/** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 9058, 9811 ] }
3,728
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
unlockedBalance
function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); }
/** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 10059, 10240 ] }
3,729
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
viewLockedBalance
function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; }
/** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 10475, 11514 ] }
3,730
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
lockedBalance
function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; }
/** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 11742, 12409 ] }
3,731
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
getTimeLockRegistry
function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); }
/** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 12598, 12714 ] }
3,732
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
approve
function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 13392, 14462 ] }
3,733
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 14990, 15688 ] }
3,734
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 16275, 17172 ] }
3,735
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
_transfer
function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); }
/** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 17778, 18794 ] }
3,736
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
_beforeTokenTransfer
function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); }
// Disable garden token transfers. Allow minting and burning.
LineComment
v0.7.6+commit.7338295f
{ "func_code_index": [ 19475, 19980 ] }
3,737
TimeLockRegistry
contracts/token/TimeLockedToken.sol
0xae171d3e9f8e755bb8547d4165fd79b148be45de
Solidity
TimeLockedToken
abstract contract TimeLockedToken is VoteToken { using LowGasSafeMath for uint256; /* ============ Events ============ */ /// @notice An event that emitted when a new lockout ocurr event NewLockout( address account, uint256 tokenslocked, bool isTeamOrAdvisor, uint256 startingVesting, uint256 endingVesting ); /// @notice An event that emitted when a new Time Lock is registered event NewTimeLockRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a new Rewards Distributor is registered event NewRewardsDistributorRegistration(address previousAddress, address newAddress); /// @notice An event that emitted when a cancellation of Lock tokens is registered event Cancel(address account, uint256 amount); /// @notice An event that emitted when a claim of tokens are registered event Claim(address _receiver, uint256 amount); /// @notice An event that emitted when a lockedBalance query is done event LockedBalance(address _account, uint256 amount); /* ============ Modifiers ============ */ modifier onlyTimeLockRegistry() { require( msg.sender == address(timeLockRegistry), 'TimeLockedToken:: onlyTimeLockRegistry: can only be executed by TimeLockRegistry' ); _; } modifier onlyTimeLockOwner() { if (address(timeLockRegistry) != address(0)) { require( msg.sender == Ownable(timeLockRegistry).owner(), 'TimeLockedToken:: onlyTimeLockOwner: can only be executed by the owner of TimeLockRegistry' ); } _; } modifier onlyUnpaused() { // Do not execute if Globally or individually paused _require(!IBabController(controller).isPaused(address(this)), Errors.ONLY_UNPAUSED); _; } /* ============ State Variables ============ */ // represents total distribution for locked balances mapping(address => uint256) distribution; /// @notice The profile of each token owner under its particular vesting conditions /** * @param team Indicates whether or not is a Team member or Advisor (true = team member/advisor, false = private investor) * @param vestingBegin When the vesting begins for such token owner * @param vestingEnd When the vesting ends for such token owner * @param lastClaim When the last claim was done */ struct VestedToken { bool teamOrAdvisor; uint256 vestingBegin; uint256 vestingEnd; uint256 lastClaim; } /// @notice A record of token owners under vesting conditions for each account, by index mapping(address => VestedToken) public vestedToken; // address of Time Lock Registry contract IBabController public controller; // address of Time Lock Registry contract TimeLockRegistry public timeLockRegistry; // address of Rewards Distriburor contract IRewardsDistributor public rewardsDistributor; // Enable Transfer of ERC20 BABL Tokens // Only Minting or transfers from/to TimeLockRegistry and Rewards Distributor can transfer tokens until the protocol is fully decentralized bool private tokenTransfersEnabled; bool private tokenTransfersWereDisabled; /* ============ Functions ============ */ /* ============ Constructor ============ */ constructor(string memory _name, string memory _symbol) VoteToken(_name, _symbol) { tokenTransfersEnabled = true; } /* ============ External Functions ============ */ /* =========== Token related Gov Functions ====== */ /** * PRIVILEGED GOVERNANCE FUNCTION. Disables transfers of ERC20 BABL Tokens */ function disableTokensTransfers() external onlyOwner { require(!tokenTransfersWereDisabled, 'BABL must flow'); tokenTransfersEnabled = false; tokenTransfersWereDisabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Allows transfers of ERC20 BABL Tokens * Can only happen after the protocol is fully decentralized. */ function enableTokensTransfers() external onlyOwner { tokenTransfersEnabled = true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Time Lock Registry contract to control token vesting conditions * * @notice Set the Time Lock Registry contract to control token vesting conditions * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(TimeLockRegistry newTimeLockRegistry) external onlyTimeLockOwner returns (bool) { require(address(newTimeLockRegistry) != address(0), 'cannot be zero address'); require(address(newTimeLockRegistry) != address(this), 'cannot be this contract'); require(address(newTimeLockRegistry) != address(timeLockRegistry), 'must be new TimeLockRegistry'); emit NewTimeLockRegistration(address(timeLockRegistry), address(newTimeLockRegistry)); timeLockRegistry = newTimeLockRegistry; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Set the Rewards Distributor contract to control either BABL Mining or profit rewards * * @notice Set the Rewards Distriburor contract to control both types of rewards (profit and BABL Mining program) * @param newRewardsDistributor Address of Rewards Distributor contract */ function setRewardsDistributor(IRewardsDistributor newRewardsDistributor) external onlyOwner returns (bool) { require(address(newRewardsDistributor) != address(0), 'cannot be zero address'); require(address(newRewardsDistributor) != address(this), 'cannot be this contract'); require(address(newRewardsDistributor) != address(rewardsDistributor), 'must be new Rewards Distributor'); emit NewRewardsDistributorRegistration(address(rewardsDistributor), address(newRewardsDistributor)); rewardsDistributor = newRewardsDistributor; return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Register new token lockup conditions for vested tokens defined only by Time Lock Registry * * @notice Tokens are completely delivered during the registration however lockup conditions apply for vested tokens * locking them according to the distribution epoch periods and the type of recipient (Team, Advisor, Investor) * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param _receiver Address to receive the tokens * @param _amount Tokens to be transferred * @param _profile True if is a Team Member or Advisor * @param _vestingBegin Unix Time when the vesting for that particular address * @param _vestingEnd Unix Time when the vesting for that particular address * @param _lastClaim Unix Time when the claim was done from that particular address * */ function registerLockup( address _receiver, uint256 _amount, bool _profile, uint256 _vestingBegin, uint256 _vestingEnd, uint256 _lastClaim ) external onlyTimeLockRegistry returns (bool) { require(balanceOf(msg.sender) >= _amount, 'insufficient balance'); require(_receiver != address(0), 'cannot be zero address'); require(_receiver != address(this), 'cannot be this contract'); require(_receiver != address(timeLockRegistry), 'cannot be the TimeLockRegistry contract itself'); require(_receiver != msg.sender, 'the owner cannot lockup itself'); // update amount of locked distribution distribution[_receiver] = distribution[_receiver].add(_amount); VestedToken storage newVestedToken = vestedToken[_receiver]; newVestedToken.teamOrAdvisor = _profile; newVestedToken.vestingBegin = _vestingBegin; newVestedToken.vestingEnd = _vestingEnd; newVestedToken.lastClaim = _lastClaim; // transfer tokens to the recipient _transfer(msg.sender, _receiver, _amount); emit NewLockout(_receiver, _amount, _profile, _vestingBegin, _vestingEnd); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors as it does not apply to investors. * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function cancelVestedTokens(address lockedAccount) external onlyTimeLockRegistry returns (uint256) { return _cancelVestedTokensFromTimeLock(lockedAccount); } /** * GOVERNANCE FUNCTION. Each token owner can claim its own specific tokens with its own specific vesting conditions from the Time Lock Registry * * @dev Claim msg.sender tokens (if any available in the registry) */ function claimMyTokens() external { // claim msg.sender tokens from timeLockRegistry uint256 amount = timeLockRegistry.claim(msg.sender); // After a proper claim, locked tokens of Team and Advisors profiles are under restricted special vesting conditions so they automatic grant // rights to the Time Lock Registry to only retire locked tokens if non-compliance vesting conditions take places along the vesting periods. // It does not apply to Investors under vesting (their locked tokens cannot be removed). if (vestedToken[msg.sender].teamOrAdvisor == true) { approve(address(timeLockRegistry), amount); } // emit claim event emit Claim(msg.sender, amount); } /** * GOVERNANCE FUNCTION. Get unlocked balance for an account * * @notice Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public returns (uint256) { // totalBalance - lockedBalance return balanceOf(account).sub(lockedBalance(account)); } /** * GOVERNANCE FUNCTION. View the locked balance for an account * * @notice View locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function viewLockedBalance(address account) public view returns (uint256) { // distribution of locked tokens // get amount from distributions uint256 amount = distribution[account]; uint256 lockedAmount = amount; // Team and investors cannot transfer tokens in the first year if (vestedToken[account].vestingBegin.add(365 days) > block.timestamp && amount != 0) { return lockedAmount; } // in case of vesting has passed, all tokens are now available, if no vesting lock is 0 as well if (block.timestamp >= vestedToken[account].vestingEnd || amount == 0) { lockedAmount = 0; } else if (amount != 0) { // in case of still under vesting period, locked tokens are recalculated lockedAmount = amount.mul(vestedToken[account].vestingEnd.sub(block.timestamp)).div( vestedToken[account].vestingEnd.sub(vestedToken[account].vestingBegin) ); } return lockedAmount; } /** * GOVERNANCE FUNCTION. Get locked balance for an account * * @notice Get locked balance for an account * @param account Account to check * @return Amount locked in the time of checking */ function lockedBalance(address account) public returns (uint256) { // get amount from distributions locked tokens (if any) uint256 lockedAmount = viewLockedBalance(account); // in case of vesting has passed, all tokens are now available so we set mapping to 0 only for accounts under vesting if ( block.timestamp >= vestedToken[account].vestingEnd && msg.sender == account && lockedAmount == 0 && vestedToken[account].vestingEnd != 0 ) { delete distribution[account]; } emit LockedBalance(account, lockedAmount); return lockedAmount; } /** * PUBLIC FUNCTION. Get the address of Time Lock Registry * * @notice Get the address of Time Lock Registry * @return Address of the Time Lock Registry */ function getTimeLockRegistry() external view returns (address) { return address(timeLockRegistry); } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Approval of allowances of ERC20 with special conditions for vesting * * @notice Override of "Approve" function to allow the `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` except in the case of spender is Time Lock Registry * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 rawAmount) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::approve: spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::approve: spender cannot be the msg.sender'); uint96 amount; if (rawAmount == uint256(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, 'TimeLockedToken::approve: amount exceeds 96 bits'); } // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens if ((spender == address(timeLockRegistry)) && (amount < allowance(msg.sender, address(timeLockRegistry)))) { amount = safe96( allowance(msg.sender, address(timeLockRegistry)), 'TimeLockedToken::approve: cannot decrease allowance to timelockregistry' ); } _approve(msg.sender, spender, amount); emit Approval(msg.sender, spender, amount); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the Increase of allowances of ERC20 with special conditions for vesting * * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an override with respect to the fulfillment of vesting conditions along the way * However an user can increase allowance many times, it will never be able to transfer locked tokens during vesting period * @return Whether or not the increaseAllowance succeeded */ function increaseAllowance(address spender, uint256 addedValue) public override nonReentrant returns (bool) { require( unlockedBalance(msg.sender) >= allowance(msg.sender, spender).add(addedValue) || spender == address(timeLockRegistry), 'TimeLockedToken::increaseAllowance:Not enough unlocked tokens' ); require(spender != address(0), 'TimeLockedToken::increaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::increaseAllowance:Spender cannot be the msg.sender'); _approve(msg.sender, spender, allowance(msg.sender, spender).add(addedValue)); return true; } /** * PRIVILEGED GOVERNANCE FUNCTION. Override the decrease of allowances of ERC20 with special conditions for vesting * * @notice Atomically decrease the allowance granted to `spender` by the caller. * * @dev Atomically decreases the allowance granted to `spender` by the caller. * This is an override with respect to the fulfillment of vesting conditions along the way * An user cannot decrease the allowance to the Time Lock Registry who is in charge of vesting conditions * @return Whether or not the decreaseAllowance succeeded */ function decreaseAllowance(address spender, uint256 subtractedValue) public override nonReentrant returns (bool) { require(spender != address(0), 'TimeLockedToken::decreaseAllowance:Spender cannot be zero address'); require(spender != msg.sender, 'TimeLockedToken::decreaseAllowance:Spender cannot be the msg.sender'); require( allowance(msg.sender, spender) >= subtractedValue, 'TimeLockedToken::decreaseAllowance:Underflow condition' ); // There is no option to decreaseAllowance to timeLockRegistry in case of vested tokens require( address(spender) != address(timeLockRegistry), 'TimeLockedToken::decreaseAllowance:cannot decrease allowance to timeLockRegistry' ); _approve(msg.sender, spender, allowance(msg.sender, spender).sub(subtractedValue)); return true; } /* ============ Internal Only Function ============ */ /** * PRIVILEGED GOVERNANCE FUNCTION. Override the _transfer of ERC20 BABL tokens only allowing the transfer of unlocked tokens * * @dev Transfer function which includes only unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal override onlyUnpaused { require(_from != address(0), 'TimeLockedToken:: _transfer: cannot transfer from the zero address'); require(_to != address(0), 'TimeLockedToken:: _transfer: cannot transfer to the zero address'); require( _to != address(this), 'TimeLockedToken:: _transfer: do not transfer tokens to the token contract itself' ); require(balanceOf(_from) >= _value, 'TimeLockedToken:: _transfer: insufficient balance'); // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, 'TimeLockedToken:: _transfer: attempting to transfer locked funds'); super._transfer(_from, _to, _value); // voting power _moveDelegates( delegates[_from], delegates[_to], safe96(_value, 'TimeLockedToken:: _transfer: uint96 overflow') ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Disable BABL token transfer until certain conditions are met * * @dev Override the _beforeTokenTransfer of ERC20 BABL tokens until certain conditions are met: * Only allowing minting or transfers from Time Lock Registry and Rewards Distributor until transfers are allowed in the controller * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ // Disable garden token transfers. Allow minting and burning. function _beforeTokenTransfer( address _from, address _to, uint256 _value ) internal virtual override { super._beforeTokenTransfer(_from, _to, _value); _require( _from == address(0) || _from == address(timeLockRegistry) || _from == address(rewardsDistributor) || _to == address(timeLockRegistry) || tokenTransfersEnabled, Errors.BABL_TRANSFERS_DISABLED ); } /** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */ function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; } }
/** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Babylon Finance * @dev Contract which gives the ability to time-lock tokens specially for vesting purposes usage * * By overriding the balanceOf() and transfer() functions in ERC20, * an account can show its full, post-distribution balance and use it for voting power * but only transfer or spend up to an allowed amount * * A portion of previously non-spendable tokens are allowed to be transferred * along the time depending on each vesting conditions, and after all epochs have passed, the full * account balance is unlocked. In case on non-completion vesting period, only the Time Lock Registry can cancel * the delivery of the pending tokens and only can cancel the remaining locked ones. */
NatSpecMultiLine
_cancelVestedTokensFromTimeLock
function _cancelVestedTokensFromTimeLock(address lockedAccount) internal onlyTimeLockRegistry returns (uint256) { require(distribution[lockedAccount] != 0, 'TimeLockedToken::cancelTokens:Not registered'); // get an update on locked amount from distributions at this precise moment uint256 loosingAmount = lockedBalance(lockedAccount); require(loosingAmount > 0, 'TimeLockedToken::cancelTokens:There are no more locked tokens'); require( vestedToken[lockedAccount].teamOrAdvisor == true, 'TimeLockedToken::cancelTokens:cannot cancel locked tokens to Investors' ); // set distribution mapping to 0 delete distribution[lockedAccount]; // set tokenVested mapping to 0 delete vestedToken[lockedAccount]; // transfer only locked tokens back to TimeLockRegistry Owner (msg.sender) require( transferFrom(lockedAccount, address(timeLockRegistry), loosingAmount), 'TimeLockedToken::cancelTokens:Transfer failed' ); // emit cancel event emit Cancel(lockedAccount, loosingAmount); return loosingAmount; }
/** * PRIVILEGED GOVERNANCE FUNCTION. Cancel and remove locked tokens due to non-completion of vesting period * applied only by Time Lock Registry and specifically to Team or Advisors * * @dev Cancel distribution registration * @param lockedAccount that should have its still locked distribution removed due to non-completion of its vesting period */
NatSpecMultiLine
v0.7.6+commit.7338295f
{ "func_code_index": [ 20368, 21551 ] }
3,738
ZmineRandom
ZmineRandom.sol
0xf912efb4e59cd2910d90a78b1c1491a870c54b12
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. */ constructor() 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)); emit 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)); emit 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.25+commit.59dbf8f1
bzzr://472d9bfef76d6056bd18b026db487e6be397fd41a31211630cf3f8da72e80fe2
{ "func_code_index": [ 675, 872 ] }
3,739
ZmineRandom
ZmineRandom.sol
0xf912efb4e59cd2910d90a78b1c1491a870c54b12
Solidity
Authorizable
contract Authorizable is Ownable { mapping(address => bool) public authorized; event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization); /** * @dev The Authorizable constructor sets the first `authorized` of the contract to the sender * account. */ constructor() public { authorize(msg.sender); } /** * @dev Throws if called by any account other than the authorized. */ modifier onlyAuthorized() { require(authorized[msg.sender]); _; } /** * @dev Allows * @param _address The address to change authorization. */ function authorize(address _address) public onlyOwner { require(!authorized[_address]); emit AuthorizationSet(_address, true); authorized[_address] = true; } /** * @dev Disallows * @param _address The address to change authorization. */ function deauthorize(address _address) public onlyOwner { require(authorized[_address]); emit AuthorizationSet(_address, false); authorized[_address] = false; } }
/** * @title Authorizable * @dev The Authorizable contract has authorized addresses, and provides basic authorization control * functions, this simplifies the implementation of "multiple user permissions". */
NatSpecMultiLine
authorize
function authorize(address _address) public onlyOwner { require(!authorized[_address]); emit AuthorizationSet(_address, true); authorized[_address] = true; }
/** * @dev Allows * @param _address The address to change authorization. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://472d9bfef76d6056bd18b026db487e6be397fd41a31211630cf3f8da72e80fe2
{ "func_code_index": [ 675, 869 ] }
3,740
ZmineRandom
ZmineRandom.sol
0xf912efb4e59cd2910d90a78b1c1491a870c54b12
Solidity
Authorizable
contract Authorizable is Ownable { mapping(address => bool) public authorized; event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization); /** * @dev The Authorizable constructor sets the first `authorized` of the contract to the sender * account. */ constructor() public { authorize(msg.sender); } /** * @dev Throws if called by any account other than the authorized. */ modifier onlyAuthorized() { require(authorized[msg.sender]); _; } /** * @dev Allows * @param _address The address to change authorization. */ function authorize(address _address) public onlyOwner { require(!authorized[_address]); emit AuthorizationSet(_address, true); authorized[_address] = true; } /** * @dev Disallows * @param _address The address to change authorization. */ function deauthorize(address _address) public onlyOwner { require(authorized[_address]); emit AuthorizationSet(_address, false); authorized[_address] = false; } }
/** * @title Authorizable * @dev The Authorizable contract has authorized addresses, and provides basic authorization control * functions, this simplifies the implementation of "multiple user permissions". */
NatSpecMultiLine
deauthorize
function deauthorize(address _address) public onlyOwner { require(authorized[_address]); emit AuthorizationSet(_address, false); authorized[_address] = false; }
/** * @dev Disallows * @param _address The address to change authorization. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://472d9bfef76d6056bd18b026db487e6be397fd41a31211630cf3f8da72e80fe2
{ "func_code_index": [ 972, 1169 ] }
3,741
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev protection against short address attack */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /** * @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 onlyPayloadSize(2) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(transfersEnabled); // 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 constant returns (uint256 balance) { return balances[_owner]; } }
transfer
function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(transfersEnabled); // 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.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 476, 954 ] }
3,742
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev protection against short address attack */ modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /** * @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 onlyPayloadSize(2) returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(transfersEnabled); // 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 constant returns (uint256 balance) { return balances[_owner]; } }
balanceOf
function balanceOf(address _owner) public constant 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.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 1170, 1294 ] }
3,743
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
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 onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); 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 onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); 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.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 411, 954 ] }
3,744
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
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 onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); 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 onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
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.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 1606, 1812 ] }
3,745
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
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 onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); 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 onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
allowance
function allowance(address _owner, address _spender) public onlyPayloadSize(2) constant returns (uint256 remaining) { 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.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 2148, 2320 ] }
3,746
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
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 onlyPayloadSize(3) returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(transfersEnabled); 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 onlyPayloadSize(2) constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
increaseApproval
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * 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 */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 2577, 2865 ] }
3,747
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
Solidity
BytechTechnology
contract BytechTechnology is StandardToken { string public constant name = "Bytech Technology"; string public constant symbol = "BYT"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 70 * 10**7 * (10**uint256(decimals)); uint256 public weiRaised; uint256 public tokenAllocated; address public owner; bool public saleToken = true; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Transfer(address indexed _from, address indexed _to, uint256 _value); function BytechTechnology() public { totalSupply = INITIAL_SUPPLY; owner = msg.sender; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(saleToken == true); address wallet = owner; uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (addTokens > balances[owner]) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } /** * If the user sends 0 ether, he receives 200 * If he sends 0.001 ether, he receives 300 * If he sends 0.005 ether, he receives 1500 * If he sends 0.01 ether, he receives 3000 * If he sends 0.1 ether he receives 30000 * If he sends 1 ether, he receives 300,000 +100% */ function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 200 * (10**uint256(decimals)); } if( _weiAmount == 0.001 ether){ amountOfTokens = 300 * (10**uint256(decimals)); } if( _weiAmount == 0.002 ether){ amountOfTokens = 600 * (10**uint256(decimals)); } if( _weiAmount == 0.003 ether){ amountOfTokens = 900 * (10**uint256(decimals)); } if( _weiAmount == 0.004 ether){ amountOfTokens = 1200 * (10**uint256(decimals)); } if( _weiAmount == 0.005 ether){ amountOfTokens = 1500 * (10**uint256(decimals)); } if( _weiAmount == 0.006 ether){ amountOfTokens = 1800 * (10**uint256(decimals)); } if( _weiAmount == 0.007 ether){ amountOfTokens = 2100 * (10**uint256(decimals)); } if( _weiAmount == 0.008 ether){ amountOfTokens = 2400 * (10**uint256(decimals)); } if( _weiAmount == 0.009 ether){ amountOfTokens = 2700 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 12000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 15000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 18000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 21000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 24000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 27000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 30 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 60 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 90 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 120 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 225 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 180 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 210 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 240 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 270 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 600 * 10**3 * (10**uint256(decimals)); } return amountOfTokens; } function mint(address _to, uint256 _amount, address _owner) internal returns (bool) { require(_to != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Transfer(_owner, _to, _amount); return true; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public returns (bool){ require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; return true; } function startSale() public onlyOwner { saleToken = true; } function stopSale() public onlyOwner { saleToken = false; } function enableTransfers(bool _transfersEnabled) onlyOwner public { transfersEnabled = _transfersEnabled; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); } }
function() payable public { buyTokens(msg.sender); }
// fallback function can be used to buy tokens
LineComment
v0.4.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 1053, 1124 ] }
3,748
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
Solidity
BytechTechnology
contract BytechTechnology is StandardToken { string public constant name = "Bytech Technology"; string public constant symbol = "BYT"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 70 * 10**7 * (10**uint256(decimals)); uint256 public weiRaised; uint256 public tokenAllocated; address public owner; bool public saleToken = true; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Transfer(address indexed _from, address indexed _to, uint256 _value); function BytechTechnology() public { totalSupply = INITIAL_SUPPLY; owner = msg.sender; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(saleToken == true); address wallet = owner; uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (addTokens > balances[owner]) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } /** * If the user sends 0 ether, he receives 200 * If he sends 0.001 ether, he receives 300 * If he sends 0.005 ether, he receives 1500 * If he sends 0.01 ether, he receives 3000 * If he sends 0.1 ether he receives 30000 * If he sends 1 ether, he receives 300,000 +100% */ function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 200 * (10**uint256(decimals)); } if( _weiAmount == 0.001 ether){ amountOfTokens = 300 * (10**uint256(decimals)); } if( _weiAmount == 0.002 ether){ amountOfTokens = 600 * (10**uint256(decimals)); } if( _weiAmount == 0.003 ether){ amountOfTokens = 900 * (10**uint256(decimals)); } if( _weiAmount == 0.004 ether){ amountOfTokens = 1200 * (10**uint256(decimals)); } if( _weiAmount == 0.005 ether){ amountOfTokens = 1500 * (10**uint256(decimals)); } if( _weiAmount == 0.006 ether){ amountOfTokens = 1800 * (10**uint256(decimals)); } if( _weiAmount == 0.007 ether){ amountOfTokens = 2100 * (10**uint256(decimals)); } if( _weiAmount == 0.008 ether){ amountOfTokens = 2400 * (10**uint256(decimals)); } if( _weiAmount == 0.009 ether){ amountOfTokens = 2700 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 12000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 15000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 18000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 21000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 24000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 27000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 30 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 60 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 90 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 120 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 225 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 180 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 210 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 240 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 270 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 600 * 10**3 * (10**uint256(decimals)); } return amountOfTokens; } function mint(address _to, uint256 _amount, address _owner) internal returns (bool) { require(_to != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Transfer(_owner, _to, _amount); return true; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public returns (bool){ require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; return true; } function startSale() public onlyOwner { saleToken = true; } function stopSale() public onlyOwner { saleToken = false; } function enableTransfers(bool _transfersEnabled) onlyOwner public { transfersEnabled = _transfersEnabled; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); } }
getTotalAmountOfTokens
function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 200 * (10**uint256(decimals)); } if( _weiAmount == 0.001 ether){ amountOfTokens = 300 * (10**uint256(decimals)); } if( _weiAmount == 0.002 ether){ amountOfTokens = 600 * (10**uint256(decimals)); } if( _weiAmount == 0.003 ether){ amountOfTokens = 900 * (10**uint256(decimals)); } if( _weiAmount == 0.004 ether){ amountOfTokens = 1200 * (10**uint256(decimals)); } if( _weiAmount == 0.005 ether){ amountOfTokens = 1500 * (10**uint256(decimals)); } if( _weiAmount == 0.006 ether){ amountOfTokens = 1800 * (10**uint256(decimals)); } if( _weiAmount == 0.007 ether){ amountOfTokens = 2100 * (10**uint256(decimals)); } if( _weiAmount == 0.008 ether){ amountOfTokens = 2400 * (10**uint256(decimals)); } if( _weiAmount == 0.009 ether){ amountOfTokens = 2700 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 12000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 15000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 18000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 21000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 24000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 27000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 30 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 60 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 90 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 120 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 225 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 180 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 210 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 240 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 270 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 600 * 10**3 * (10**uint256(decimals)); } return amountOfTokens; }
/** * If the user sends 0 ether, he receives 200 * If he sends 0.001 ether, he receives 300 * If he sends 0.005 ether, he receives 1500 * If he sends 0.01 ether, he receives 3000 * If he sends 0.1 ether he receives 30000 * If he sends 1 ether, he receives 300,000 +100% */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 2354, 5853 ] }
3,749
BytechTechnology
BytechTechnology.sol
0xb772c656f5021b6f0ab5d701c8e2b3c06735071a
Solidity
BytechTechnology
contract BytechTechnology is StandardToken { string public constant name = "Bytech Technology"; string public constant symbol = "BYT"; uint8 public constant decimals = 8; uint256 public constant INITIAL_SUPPLY = 70 * 10**7 * (10**uint256(decimals)); uint256 public weiRaised; uint256 public tokenAllocated; address public owner; bool public saleToken = true; event OwnerChanged(address indexed previousOwner, address indexed newOwner); event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken); event Transfer(address indexed _from, address indexed _to, uint256 _value); function BytechTechnology() public { totalSupply = INITIAL_SUPPLY; owner = msg.sender; //owner = msg.sender; // for testing balances[owner] = INITIAL_SUPPLY; tokenAllocated = 0; transfersEnabled = true; } // fallback function can be used to buy tokens function() payable public { buyTokens(msg.sender); } function buyTokens(address _investor) public payable returns (uint256){ require(_investor != address(0)); require(saleToken == true); address wallet = owner; uint256 weiAmount = msg.value; uint256 tokens = validPurchaseTokens(weiAmount); if (tokens == 0) {revert();} weiRaised = weiRaised.add(weiAmount); tokenAllocated = tokenAllocated.add(tokens); mint(_investor, tokens, owner); TokenPurchase(_investor, weiAmount, tokens); wallet.transfer(weiAmount); return tokens; } function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) { uint256 addTokens = getTotalAmountOfTokens(_weiAmount); if (addTokens > balances[owner]) { TokenLimitReached(tokenAllocated, addTokens); return 0; } return addTokens; } /** * If the user sends 0 ether, he receives 200 * If he sends 0.001 ether, he receives 300 * If he sends 0.005 ether, he receives 1500 * If he sends 0.01 ether, he receives 3000 * If he sends 0.1 ether he receives 30000 * If he sends 1 ether, he receives 300,000 +100% */ function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) { uint256 amountOfTokens = 0; if(_weiAmount == 0){ amountOfTokens = 200 * (10**uint256(decimals)); } if( _weiAmount == 0.001 ether){ amountOfTokens = 300 * (10**uint256(decimals)); } if( _weiAmount == 0.002 ether){ amountOfTokens = 600 * (10**uint256(decimals)); } if( _weiAmount == 0.003 ether){ amountOfTokens = 900 * (10**uint256(decimals)); } if( _weiAmount == 0.004 ether){ amountOfTokens = 1200 * (10**uint256(decimals)); } if( _weiAmount == 0.005 ether){ amountOfTokens = 1500 * (10**uint256(decimals)); } if( _weiAmount == 0.006 ether){ amountOfTokens = 1800 * (10**uint256(decimals)); } if( _weiAmount == 0.007 ether){ amountOfTokens = 2100 * (10**uint256(decimals)); } if( _weiAmount == 0.008 ether){ amountOfTokens = 2400 * (10**uint256(decimals)); } if( _weiAmount == 0.009 ether){ amountOfTokens = 2700 * (10**uint256(decimals)); } if( _weiAmount == 0.01 ether){ amountOfTokens = 3000 * (10**uint256(decimals)); } if( _weiAmount == 0.02 ether){ amountOfTokens = 6000 * (10**uint256(decimals)); } if( _weiAmount == 0.03 ether){ amountOfTokens = 9000 * (10**uint256(decimals)); } if( _weiAmount == 0.04 ether){ amountOfTokens = 12000 * (10**uint256(decimals)); } if( _weiAmount == 0.05 ether){ amountOfTokens = 15000 * (10**uint256(decimals)); } if( _weiAmount == 0.06 ether){ amountOfTokens = 18000 * (10**uint256(decimals)); } if( _weiAmount == 0.07 ether){ amountOfTokens = 21000 * (10**uint256(decimals)); } if( _weiAmount == 0.08 ether){ amountOfTokens = 24000 * (10**uint256(decimals)); } if( _weiAmount == 0.09 ether){ amountOfTokens = 27000 * (10**uint256(decimals)); } if( _weiAmount == 0.1 ether){ amountOfTokens = 30 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.2 ether){ amountOfTokens = 60 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.3 ether){ amountOfTokens = 90 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.4 ether){ amountOfTokens = 120 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.5 ether){ amountOfTokens = 225 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.6 ether){ amountOfTokens = 180 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.7 ether){ amountOfTokens = 210 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.8 ether){ amountOfTokens = 240 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 0.9 ether){ amountOfTokens = 270 * 10**3 * (10**uint256(decimals)); } if( _weiAmount == 1 ether){ amountOfTokens = 600 * 10**3 * (10**uint256(decimals)); } return amountOfTokens; } function mint(address _to, uint256 _amount, address _owner) internal returns (bool) { require(_to != address(0)); require(_amount <= balances[_owner]); balances[_to] = balances[_to].add(_amount); balances[_owner] = balances[_owner].sub(_amount); Transfer(_owner, _to, _amount); return true; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner public returns (bool){ require(_newOwner != address(0)); OwnerChanged(owner, _newOwner); owner = _newOwner; return true; } function startSale() public onlyOwner { saleToken = true; } function stopSale() public onlyOwner { saleToken = false; } function enableTransfers(bool _transfersEnabled) onlyOwner public { transfersEnabled = _transfersEnabled; } /** * Peterson's Law Protection * Claim tokens */ function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); } }
claimTokens
function claimTokens() public onlyOwner { owner.transfer(this.balance); uint256 balance = balanceOf(this); transfer(owner, balance); Transfer(this, owner, balance); }
/** * Peterson's Law Protection * Claim tokens */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://b1d4334e6db6c8dd8d65765e38ecf62e2648591cded1ff8b88f815b9cd29b870
{ "func_code_index": [ 6892, 7104 ] }
3,750
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 89, 476 ] }
3,751
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 560, 840 ] }
3,752
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 954, 1070 ] }
3,753
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1134, 1264 ] }
3,754
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 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(_to != address(0)); require(_value <= balances[msg.sender]); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 199, 287 ] }
3,755
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 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(_to != address(0)); require(_value <= balances[msg.sender]); 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(_to != address(0)); require(_value <= balances[msg.sender]); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 445, 777 ] }
3,756
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 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(_to != address(0)); require(_value <= balances[msg.sender]); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 983, 1087 ] }
3,757
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() 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 relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @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 { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit 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
renounceOwnership
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); }
/** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 815, 932 ] }
3,758
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() 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 relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @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 { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit 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 { _transferOwnership(_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.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1097, 1205 ] }
3,759
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
Ownable
contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() 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 relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @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 { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit 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) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; }
/** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1343, 1521 ] }
3,760
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
pause
function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); }
/** * @dev called by the owner to pause, triggers stopped state */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 513, 609 ] }
3,761
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
unpause
function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); }
/** * @dev called by the owner to unpause, returns to normal state */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 693, 791 ] }
3,762
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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); 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(_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); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 401, 891 ] }
3,763
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1517, 1712 ] }
3,764
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 2036, 2201 ] }
3,765
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 2661, 2971 ] }
3,766
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
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); 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
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 3436, 3885 ] }
3,767
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
SuccinctWhitelist
contract SuccinctWhitelist is Ownable { mapping(address => bool) public whitelisted; event WhitelistAdded(address indexed operator); event WhitelistRemoved(address indexed operator); /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { require(whitelisted[_operator]); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, * or was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = true; emit WhitelistAdded(_operator); return true; } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { bool result = whitelisted[_operator]; return result; } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if all addresses was added to the whitelist, * or were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(addAddressToWhitelist(_operators[i])); } return true; } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * or the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = false; emit WhitelistRemoved(_operator); return true; } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if all addresses were removed from the whitelist, * or weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(removeAddressFromWhitelist(_operators[i])); } return true; } }
/** * @title SuccinctWhitelist * @dev The SuccinctWhitelist contract has a whitelist of addresses, and provides basic authorization control functions. * Note: this is a succinct, straightforward and easy to understand implementation of openzeppelin-solidity's Whitelisted, * but with full functionalities and APIs of openzeppelin-solidity's Whitelisted without inheriting RBAC. */
NatSpecMultiLine
addAddressToWhitelist
function addAddressToWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = true; emit WhitelistAdded(_operator); return true; }
/** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, * or was already in the whitelist */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 584, 784 ] }
3,768
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
SuccinctWhitelist
contract SuccinctWhitelist is Ownable { mapping(address => bool) public whitelisted; event WhitelistAdded(address indexed operator); event WhitelistRemoved(address indexed operator); /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { require(whitelisted[_operator]); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, * or was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = true; emit WhitelistAdded(_operator); return true; } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { bool result = whitelisted[_operator]; return result; } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if all addresses was added to the whitelist, * or were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(addAddressToWhitelist(_operators[i])); } return true; } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * or the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = false; emit WhitelistRemoved(_operator); return true; } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if all addresses were removed from the whitelist, * or weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(removeAddressFromWhitelist(_operators[i])); } return true; } }
/** * @title SuccinctWhitelist * @dev The SuccinctWhitelist contract has a whitelist of addresses, and provides basic authorization control functions. * Note: this is a succinct, straightforward and easy to understand implementation of openzeppelin-solidity's Whitelisted, * but with full functionalities and APIs of openzeppelin-solidity's Whitelisted without inheriting RBAC. */
NatSpecMultiLine
whitelist
function whitelist(address _operator) public view returns (bool) { bool result = whitelisted[_operator]; return result; }
/** * @dev getter to determine if address is in whitelist */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 859, 1014 ] }
3,769
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
SuccinctWhitelist
contract SuccinctWhitelist is Ownable { mapping(address => bool) public whitelisted; event WhitelistAdded(address indexed operator); event WhitelistRemoved(address indexed operator); /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { require(whitelisted[_operator]); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, * or was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = true; emit WhitelistAdded(_operator); return true; } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { bool result = whitelisted[_operator]; return result; } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if all addresses was added to the whitelist, * or were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(addAddressToWhitelist(_operators[i])); } return true; } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * or the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = false; emit WhitelistRemoved(_operator); return true; } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if all addresses were removed from the whitelist, * or weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(removeAddressFromWhitelist(_operators[i])); } return true; } }
/** * @title SuccinctWhitelist * @dev The SuccinctWhitelist contract has a whitelist of addresses, and provides basic authorization control functions. * Note: this is a succinct, straightforward and easy to understand implementation of openzeppelin-solidity's Whitelisted, * but with full functionalities and APIs of openzeppelin-solidity's Whitelisted without inheriting RBAC. */
NatSpecMultiLine
addAddressesToWhitelist
function addAddressesToWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(addAddressToWhitelist(_operators[i])); } return true; }
/** * @dev add addresses to the whitelist * @param _operators addresses * @return true if all addresses was added to the whitelist, * or were already in the whitelist */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1210, 1458 ] }
3,770
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
SuccinctWhitelist
contract SuccinctWhitelist is Ownable { mapping(address => bool) public whitelisted; event WhitelistAdded(address indexed operator); event WhitelistRemoved(address indexed operator); /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { require(whitelisted[_operator]); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, * or was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = true; emit WhitelistAdded(_operator); return true; } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { bool result = whitelisted[_operator]; return result; } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if all addresses was added to the whitelist, * or were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(addAddressToWhitelist(_operators[i])); } return true; } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * or the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = false; emit WhitelistRemoved(_operator); return true; } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if all addresses were removed from the whitelist, * or weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(removeAddressFromWhitelist(_operators[i])); } return true; } }
/** * @title SuccinctWhitelist * @dev The SuccinctWhitelist contract has a whitelist of addresses, and provides basic authorization control functions. * Note: this is a succinct, straightforward and easy to understand implementation of openzeppelin-solidity's Whitelisted, * but with full functionalities and APIs of openzeppelin-solidity's Whitelisted without inheriting RBAC. */
NatSpecMultiLine
removeAddressFromWhitelist
function removeAddressFromWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = false; emit WhitelistRemoved(_operator); return true; }
/** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * or the address wasn't in the whitelist in the first place */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1684, 1892 ] }
3,771
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
SuccinctWhitelist
contract SuccinctWhitelist is Ownable { mapping(address => bool) public whitelisted; event WhitelistAdded(address indexed operator); event WhitelistRemoved(address indexed operator); /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { require(whitelisted[_operator]); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, * or was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = true; emit WhitelistAdded(_operator); return true; } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { bool result = whitelisted[_operator]; return result; } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if all addresses was added to the whitelist, * or were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(addAddressToWhitelist(_operators[i])); } return true; } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * or the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public returns (bool) { whitelisted[_operator] = false; emit WhitelistRemoved(_operator); return true; } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if all addresses were removed from the whitelist, * or weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(removeAddressFromWhitelist(_operators[i])); } return true; } }
/** * @title SuccinctWhitelist * @dev The SuccinctWhitelist contract has a whitelist of addresses, and provides basic authorization control functions. * Note: this is a succinct, straightforward and easy to understand implementation of openzeppelin-solidity's Whitelisted, * but with full functionalities and APIs of openzeppelin-solidity's Whitelisted without inheriting RBAC. */
NatSpecMultiLine
removeAddressesFromWhitelist
function removeAddressesFromWhitelist(address[] _operators) onlyOwner public returns (bool) { for (uint256 i = 0; i < _operators.length; i++) { require(removeAddressFromWhitelist(_operators[i])); } return true; }
/** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if all addresses were removed from the whitelist, * or weren't in the whitelist in the first place */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 2112, 2370 ] }
3,772
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
CelerToken
contract CelerToken is PausableToken, SuccinctWhitelist { string public constant name = "SexToken"; string public constant symbol = "SEX"; uint256 public constant decimals = 18; // 10 billion tokens with 18 decimals uint256 public constant INITIAL_SUPPLY = 1e28; // Indicate whether token transferability is opened to everyone bool public transferOpened = false; modifier onlyIfTransferable() { require(transferOpened || whitelisted[msg.sender] || msg.sender == owner); _; } modifier onlyValidReceiver(address _to) { require(_to != address(this)); _; } constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * @dev Extend parent behavior requiring transfer * to respect transferability and receiver's validity. */ function transfer( address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transfer(_to, _value); } /** * @dev Extend parent behavior requiring transferFrom * to respect transferability and receiver's validity. */ function transferFrom( address _from, address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Open token transferability. */ function openTransfer() external onlyOwner { transferOpened = true; } }
/** * @title CelerToken * @dev Celer Network's token contract. */
NatSpecMultiLine
transfer
function transfer( address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transfer(_to, _value); }
/** * @dev Extend parent behavior requiring transfer * to respect transferability and receiver's validity. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 856, 1055 ] }
3,773
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
CelerToken
contract CelerToken is PausableToken, SuccinctWhitelist { string public constant name = "SexToken"; string public constant symbol = "SEX"; uint256 public constant decimals = 18; // 10 billion tokens with 18 decimals uint256 public constant INITIAL_SUPPLY = 1e28; // Indicate whether token transferability is opened to everyone bool public transferOpened = false; modifier onlyIfTransferable() { require(transferOpened || whitelisted[msg.sender] || msg.sender == owner); _; } modifier onlyValidReceiver(address _to) { require(_to != address(this)); _; } constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * @dev Extend parent behavior requiring transfer * to respect transferability and receiver's validity. */ function transfer( address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transfer(_to, _value); } /** * @dev Extend parent behavior requiring transferFrom * to respect transferability and receiver's validity. */ function transferFrom( address _from, address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Open token transferability. */ function openTransfer() external onlyOwner { transferOpened = true; } }
/** * @title CelerToken * @dev Celer Network's token contract. */
NatSpecMultiLine
transferFrom
function transferFrom( address _from, address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transferFrom(_from, _to, _value); }
/** * @dev Extend parent behavior requiring transferFrom * to respect transferability and receiver's validity. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1188, 1422 ] }
3,774
CelerToken
CelerToken.sol
0xb555bcb2cadebfde53438ac5c329fea5f045a769
Solidity
CelerToken
contract CelerToken is PausableToken, SuccinctWhitelist { string public constant name = "SexToken"; string public constant symbol = "SEX"; uint256 public constant decimals = 18; // 10 billion tokens with 18 decimals uint256 public constant INITIAL_SUPPLY = 1e28; // Indicate whether token transferability is opened to everyone bool public transferOpened = false; modifier onlyIfTransferable() { require(transferOpened || whitelisted[msg.sender] || msg.sender == owner); _; } modifier onlyValidReceiver(address _to) { require(_to != address(this)); _; } constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * @dev Extend parent behavior requiring transfer * to respect transferability and receiver's validity. */ function transfer( address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transfer(_to, _value); } /** * @dev Extend parent behavior requiring transferFrom * to respect transferability and receiver's validity. */ function transferFrom( address _from, address _to, uint256 _value ) public onlyIfTransferable onlyValidReceiver(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Open token transferability. */ function openTransfer() external onlyOwner { transferOpened = true; } }
/** * @title CelerToken * @dev Celer Network's token contract. */
NatSpecMultiLine
openTransfer
function openTransfer() external onlyOwner { transferOpened = true; }
/** * @dev Open token transferability. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
None
bzzr://3633fb4531732896a451a3e6cce382e04e23cec15ba6f11964da7667b0d31bf2
{ "func_code_index": [ 1479, 1559 ] }
3,775
FluxContract
FluxContract.sol
0xb2993d177971165890f634f0e52f13d89160013a
Solidity
IERC20
interface IERC20 { //저는 7년 동안 한국에서 살았어요 //한국어능력시험 //대한민국 function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
totalSupply
function totalSupply() external view returns (uint256);
//저는 7년 동안 한국에서 살았어요 //한국어능력시험 //대한민국
LineComment
v0.6.6+commit.6c089d02
None
ipfs://0ec466099f91e6050ea3d8f659be6ac94ec071296e0dbe88ad39334faa48fddc
{ "func_code_index": [ 74, 134 ] }
3,776
FluxContract
FluxContract.sol
0xb2993d177971165890f634f0e52f13d89160013a
Solidity
SafeMath
library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } //그 집은 한국에서 지어졌어요 //저는 한국에서 살고 있어요 function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
//그 집은 한국에서 지어졌어요 //저는 한국에서 살고 있어요
LineComment
v0.6.6+commit.6c089d02
None
ipfs://0ec466099f91e6050ea3d8f659be6ac94ec071296e0dbe88ad39334faa48fddc
{ "func_code_index": [ 394, 589 ] }
3,777
FluxContract
FluxContract.sol
0xb2993d177971165890f634f0e52f13d89160013a
Solidity
Address
library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } //번역 사이트 : 영어-> 한국어 / 한국어-> 영어 한국어를 배우는 학생들 당신의 고도를 결정하는 것은 당신의 적성 이 아니라 당신의 태도입니다 //저는 한국어를 한국에서 배웠어요 function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
//저는 한국어를 한국에서 배웠어요 //그는 그녀의 호의를 순수하게 받아들였다
LineComment
functionCall
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
//번역 사이트 : 영어-> 한국어 / 한국어-> 영어 한국어를 배우는 학생들 당신의 고도를 결정하는 것은 당신의 적성 이 아니라 당신의 태도입니다 //저는 한국어를 한국에서 배웠어요
LineComment
v0.6.6+commit.6c089d02
None
ipfs://0ec466099f91e6050ea3d8f659be6ac94ec071296e0dbe88ad39334faa48fddc
{ "func_code_index": [ 639, 817 ] }
3,778
FluxContract
FluxContract.sol
0xb2993d177971165890f634f0e52f13d89160013a
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; //그 집은 한국에서 지어졌어요 //저는 한국에서 살고 있어요 constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /* Integer pharetra massa eget facilisis commodo. Integer in dolor vitae eros pretium suscipit et scelerisque neque. Duis condimentum justo ac volutpat consequat. Curabitur id erat suscipit, pharetra neque ac, luctus urna. Sed maximus augue et mauris interdum tristique. Proin et sem viverra, fringilla massa non, egestas sem. Nulla id mauris tristique, porta eros sit amet, mollis mauris. Pellentesque eu magna eu nunc molestie interdum nec nec felis. Sed non ante at lectus accumsan lobortis nec vitae lectus. Ut fringilla mi ac est rhoncus, molestie convallis massa consectetur. Duis cursus sem nec metus commodo, quis consequat est congue. Fusce convallis erat at lectus pharetra venenatis. Donec porta ligula et massa congue, lobortis scelerisque quam tempor. Suspendisse dictum arcu et nibh ullamcorper laoreet. Fusce quis ex pellentesque, varius erat at, interdum elit. Nunc sed ex vel neque malesuada cursus. Donec a mi viverra, venenatis sapien ac, cursus sapien. Suspendisse mattis felis eget ligula gravida fermentum. Ut faucibus mauris euismod porta lacinia. Nam rhoncus tortor non leo lobortis, id commodo ex egestas. Suspendisse ac leo vel orci aliquam congue. Vivamus ornare sem vitae metus lacinia hendrerit. Quisque eget odio a ex sodales sagittis. Vestibulum auctor ligula ac neque auctor, nec varius metus vulputate. Pellentesque vitae ex id lectus semper cursus. Vestibulum eu tellus fringilla, venenatis lacus vel, rutrum elit. Nam ut velit non magna euismod porttitor non ut odio. Aenean commodo leo sit amet lobortis pharetra. Proin eu felis at dui rutrum feugiat. Nullam cursus metus eu eros volutpat, sed placerat quam condimentum. Sed mollis leo et arcu tempor, quis lacinia erat rhoncus. Etiam aliquam augue sed ipsum pretium, ac efficitur lacus varius. Morbi ac felis fringilla ligula sagittis vehicula ac eu erat. Nullam aliquam justo scelerisque tortor egestas molestie. Curabitur fringilla risus vel urna ullamcorper, id placerat nibh fermentum. Mauris sed dui a dolor dictum bibendum. Suspendisse lacinia mi eu ligula eleifend varius. Maecenas blandit ipsum non nulla rhoncus, sed dapibus augue pellentesque. Vestibulum at lectus pharetra enim mattis ultricies sit amet eget est. Nulla euismod eros sed cursus vestibulum. Mauris tincidunt dui quis libero dignissim, nec blandit odio vulputate. Pellentesque in elit tristique, maximus mauris non, gravida nibh. Maecenas condimentum dolor et eros tempor, vel consequat ante convallis. Etiam ultricies lorem vel molestie semper. Curabitur venenatis diam sit amet porta blandit. Maecenas eget urna at urna ullamcorper consectetur. Praesent luctus velit eget elit ultricies malesuada. Nam tincidunt purus quis lorem cursus, viverra mattis orci tempor. Vestibulum mollis urna sed nisi faucibus imperdiet. Etiam imperdiet turpis quis quam vehicula sollicitudin. Ut efficitur leo in ultrices dignissim. Etiam tempor lorem volutpat, rhoncus nunc ac, porta turpis. Pellentesque vehicula ligula non mi ultricies, vitae convallis libero hendrerit. Praesent ultrices neque at erat accumsan sagittis. Duis eget risus in ligula lacinia fermentum sit amet ac est. Aenean sed turpis elementum, tincidunt nisi vitae, porttitor velit. Maecenas sed sem porta, vulputate ex eu, tempus sem. Aenean in est sed tortor imperdiet auctor eu et velit. Morbi faucibus odio vestibulum, vestibulum eros eu, commodo erat. Duis ac orci et arcu accumsan porttitor id vitae mauris. Pellentesque in nisl laoreet, condimentum nulla sit amet, dignissim quam. Proin aliquet libero at placerat fringilla. Duis aliquam elit eget massa malesuada pellentesque eget vel tortor. Suspendisse ut justo ut sem accumsan hendrerit vitae sed purus. Integer et ex in magna aliquam fringilla. Suspendisse nec libero ut lorem egestas pretium quis et nibh. Quisque at augue gravida, aliquam enim eu, hendrerit quam. Phasellus a ligula vulputate, blandit sem nec, porttitor urna. Duis ac massa quis purus tincidunt laoreet. Etiam elementum sem a elit ornare, quis ornare eros suscipit. Sed sed ante venenatis, scelerisque libero ut, consequat magna. Vivamus maximus lectus sed varius laoreet. Fusce eu ligula hendrerit, auctor libero vitae, vestibulum risus. Duis in mi tempus, sollicitudin metus et, faucibus justo. Sed quis eros in diam semper faucibus vel in turpis. Integer vulputate tortor non eleifend tempor. Nunc volutpat velit et ex rhoncus tincidunt. Nullam eleifend massa ut sapien facilisis, ornare gravida orci varius. Nam et eros a sapien pellentesque laoreet eget in velit. Mauris vitae velit pellentesque eros luctus dignissim ut eu eros. Donec vitae ligula vehicula, finibus risus nec, auctor magna. Curabitur ut tortor in urna bibendum accumsan. Maecenas tincidunt justo in varius fringilla. Donec tristique eros quis erat tempus, nec scelerisque quam tempor. Vestibulum eget sapien non odio rhoncus viverra nec ut nunc. Maecenas fringilla eros vitae rutrum dignissim. Aenean ornare mauris vitae ligula euismod placerat. In sagittis nibh in tempus cursus. Aenean sodales dui vel quam bibendum, id interdum ligula suscipit. Nam imperdiet felis et nisl lacinia ultrices. Praesent ac arcu quis est fringilla fringilla. Ut venenatis lorem vel arcu congue, id vehicula nunc commodo. Donec at lectus ullamcorper tellus gravida hendrerit. Curabitur quis risus eu neque lacinia rhoncus. Duis dictum nulla id lacus rutrum finibus. Nullam eget erat egestas, interdum sem eu, pellentesque nunc. Proin id nisi ut risus cursus fringilla quis vitae libero. Morbi convallis nulla ut turpis mattis, a dapibus leo feugiat. Integer quis erat ac lorem eleifend mollis. Praesent et est bibendum sem varius vestibulum. Praesent eu orci nec libero auctor euismod ut vitae leo. Curabitur et sem sed lacus bibendum vehicula quis vel lorem. Vivamus posuere lacus id arcu dignissim feugiat. Pellentesque vel enim sollicitudin dolor suscipit faucibus. Duis ac tellus vitae lacus vulputate finibus a a justo. Cras vel urna ut est pharetra porttitor. Ut dignissim ante eget mauris bibendum sollicitudin. Vivamus cursus elit sit amet malesuada pharetra. Etiam finibus lorem sed mi viverra, ut ultrices ex gravida. Pellentesque gravida ipsum a risus luctus, vehicula molestie lacus placerat. Nunc in quam sit amet odio placerat lobortis. Ut id est bibendum, pulvinar turpis nec, facilisis arcu. Vestibulum blandit mi eu eros dapibus placerat a eget nisi. Donec tristique ex in vestibulum malesuada. Integer non erat cursus, vehicula libero vel, porttitor metus. Duis id libero et lectus dictum interdum eu tempus turpis. Sed pellentesque sapien ut auctor ultricies. Vestibulum et mi at orci convallis semper. Mauris interdum orci et turpis dapibus, nec porta lorem iaculis. Nam sed erat et dui rutrum aliquet in sit amet nunc. Donec egestas tellus id gravida lacinia. Nulla egestas mauris in dolor imperdiet, id sodales libero blandit. Duis scelerisque ante et enim lobortis, posuere iaculis nunc auctor. Donec ac dui mollis, dignissim lorem pretium, cursus lorem. Morbi laoreet sapien sed mauris vestibulum sollicitudin. Sed ultrices nisi in venenatis porta. Vestibulum eu est porttitor, facilisis ligula nec, dapibus justo. Curabitur aliquam dolor at nibh lacinia maximus. Nam ut nisl nec lectus tincidunt hendrerit. Cras vehicula lectus nec mauris tristique, a finibus arcu semper. Cras facilisis erat ornare lacus facilisis, nec posuere nisi lacinia. Donec ut nibh lacinia, pellentesque augue sit amet, molestie lorem. Sed rhoncus ligula non ante dapibus pulvinar. Sed varius leo vel iaculis egestas. Duis tristique dolor cursus nisi pellentesque, sed lacinia eros tempus. Phasellus at libero sodales, hendrerit mi a, feugiat quam. Suspendisse mattis tellus sed felis sodales, et finibus velit consectetur. In in massa accumsan, sollicitudin sem at, dapibus lacus. Quisque consequat nisi ac sem vestibulum, sit amet auctor libero vestibulum. Sed non libero vel urna interdum vehicula in ut est. Mauris at orci sagittis, interdum nunc ac, dignissim magna. Nullam fringilla velit ac quam placerat, vitae facilisis eros molestie. Mauris lacinia augue id dui commodo, quis molestie dolor mattis. Vestibulum ac mi sed libero dictum sagittis. Aliquam maximus augue eget ipsum elementum viverra. Praesent vehicula nunc in convallis molestie. Cras scelerisque purus vel euismod vestibulum. Vestibulum sed augue interdum, commodo mi sit amet, luctus neque. Etiam efficitur dui dignissim ipsum egestas dignissim. Donec eget ex sit amet orci vulputate efficitur. Fusce suscipit velit vitae quam fringilla ultrices. Vivamus non felis tempor, gravida ligula vitae, facilisis nunc. Maecenas commodo quam sit amet dolor consectetur tempor. Ut a lorem suscipit, viverra velit non, rhoncus enim. Sed nec metus nec mauris dapibus ultrices. Morbi porttitor purus at purus euismod, ac eleifend augue ornare. Ut quis enim molestie, sollicitudin tellus quis, hendrerit urna. Donec eu odio a dolor aliquam tincidunt. Sed eu velit vel dui posuere accumsan ac in mi. Praesent vehicula mauris non ex sagittis lacinia. Sed ut est ultricies, tincidunt erat sit amet, efficitur quam. Ut tincidunt dolor sed sollicitudin interdum. Vivamus in velit quis neque facilisis pulvinar sed quis odio. Pellentesque lacinia magna sit amet turpis posuere elementum. In in risus dignissim, feugiat mi et, placerat metus. Mauris id felis sit amet dui sodales dapibus. Donec a mi a ante facilisis efficitur ac sit amet lectus. Sed rutrum ante faucibus lobortis interdum. Nulla ut massa et eros finibus placerat. Ut sed odio nec felis varius ornare a at urna. Sed scelerisque ex non eros hendrerit, sed ullamcorper ante rhoncus. Quisque a turpis ac velit suscipit porta. Nulla gravida neque vitae dolor congue bibendum. Nullam nec neque sed nibh interdum interdum et eget quam. Duis sit amet enim et quam tempor accumsan. Fusce nec mauris non nulla sodales ultrices eget a mauris. Etiam quis felis tincidunt, consequat sapien vel, consequat erat. Nam pretium tellus vitae rhoncus commodo. Nam sed urna ullamcorper, condimentum metus eget, aliquam lectus. Sed quis massa eu odio tincidunt sagittis vitae eget sem. Sed placerat ligula sed eros porttitor tincidunt. Maecenas auctor odio vel ante iaculis facilisis. Pellentesque quis erat suscipit, feugiat felis at, dapibus est. Etiam at sem quis neque cursus ullamcorper. Donec pharetra magna ut diam hendrerit, ut tincidunt est feugiat. Quisque convallis arcu vel nibh malesuada tristique. Maecenas in felis ac erat aliquam venenatis venenatis vel tortor. Suspendisse vulputate lorem et lacus varius imperdiet. Nullam tristique nisl at gravida imperdiet. Aenean luctus mi eu ligula tempor ultricies. Cras et velit sed ligula cursus molestie. Phasellus placerat leo vel lacus finibus convallis. Vivamus varius felis eget sollicitudin pellentesque. Pellentesque quis nulla blandit, consectetur tellus ut, dictum massa. Cras vel nunc vitae nibh pharetra dignissim at nec urna. Etiam ac nunc sollicitudin, pharetra justo quis, accumsan nibh. Ut eleifend tellus a odio rutrum ornare. Praesent tempor lectus eu tortor viverra euismod. Mauris eu erat vel magna iaculis rutrum gravida nec turpis. Sed non nisi vitae enim convallis efficitur ut ac quam. Suspendisse ac lorem vitae dui sollicitudin fringilla. Vestibulum in sapien vitae elit congue faucibus in et urna. Integer sagittis purus ornare quam placerat, id consectetur ex vulputate. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /* Vivamus egestas neque eget ultrices hendrerit. Donec elementum odio nec ex malesuada cursus. Curabitur condimentum ante id ipsum porta ullamcorper. Vivamus ut est elementum, interdum eros vitae, laoreet neque. Pellentesque elementum risus tincidunt erat viverra hendrerit. Donec nec velit ut lectus fringilla lacinia. Donec laoreet enim at diam blandit tincidunt. Aenean sollicitudin sem vitae dui sollicitudin finibus. Donec vitae massa varius erat cursus commodo nec a lectus. Vivamus egestas neque eget ultrices hendrerit. Donec elementum odio nec ex malesuada cursus. Curabitur condimentum ante id ipsum porta ullamcorper. Vivamus ut est elementum, interdum eros vitae, laoreet neque. Pellentesque elementum risus tincidunt erat viverra hendrerit. Donec nec velit ut lectus fringilla lacinia. Donec laoreet enim at diam blandit tincidunt. Aenean sollicitudin sem vitae dui sollicitudin finibus. Donec vitae massa varius erat cursus commodo nec a lectus. Nulla dapibus sapien ut gravida commodo. Phasellus dignissim justo et nisi fermentum commodo. Etiam non sapien quis erat lacinia tempor. Suspendisse egestas diam in vestibulum sagittis. Pellentesque eget tellus volutpat, interdum erat eget, viverra nunc. Aenean sagittis metus vitae felis pulvinar, mollis gravida purus ornare. Morbi hendrerit eros sed suscipit bibendum. Suspendisse egestas ante in mi maximus, quis aliquam elit porttitor. Donec eget sem aliquam, placerat purus at, lobortis lorem. Sed feugiat lectus non justo auctor placerat. Sed sit amet nulla volutpat, sagittis risus non, congue nibh. Integer vel ligula gravida, sollicitudin eros non, dictum nibh. Quisque non nisi molestie, interdum mi eget, ultrices nisl. Quisque maximus risus quis dignissim tempor. Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero. Integer consequat velit ut auctor ullamcorper. Pellentesque mattis quam sed sollicitudin mattis. Sed feugiat lectus non justo auctor placerat. Sed sit amet nulla volutpat, sagittis risus non, congue nibh. Integer vel ligula gravida, sollicitudin eros non, dictum nibh. Quisque non nisi molestie, interdum mi eget, ultrices nisl. Quisque maximus risus quis dignissim tempor. Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero. Integer consequat velit ut auctor ullamcorper. Pellentesque mattis quam sed sollicitudin mattis. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
approve
function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
/* Integer pharetra massa eget facilisis commodo. Integer in dolor vitae eros pretium suscipit et scelerisque neque. Duis condimentum justo ac volutpat consequat. Curabitur id erat suscipit, pharetra neque ac, luctus urna. Sed maximus augue et mauris interdum tristique. Proin et sem viverra, fringilla massa non, egestas sem. Nulla id mauris tristique, porta eros sit amet, mollis mauris. Pellentesque eu magna eu nunc molestie interdum nec nec felis. Sed non ante at lectus accumsan lobortis nec vitae lectus. Ut fringilla mi ac est rhoncus, molestie convallis massa consectetur. Duis cursus sem nec metus commodo, quis consequat est congue. Fusce convallis erat at lectus pharetra venenatis. Donec porta ligula et massa congue, lobortis scelerisque quam tempor. Suspendisse dictum arcu et nibh ullamcorper laoreet. Fusce quis ex pellentesque, varius erat at, interdum elit. Nunc sed ex vel neque malesuada cursus. Donec a mi viverra, venenatis sapien ac, cursus sapien. Suspendisse mattis felis eget ligula gravida fermentum. Ut faucibus mauris euismod porta lacinia. Nam rhoncus tortor non leo lobortis, id commodo ex egestas. Suspendisse ac leo vel orci aliquam congue. Vivamus ornare sem vitae metus lacinia hendrerit. Quisque eget odio a ex sodales sagittis. Vestibulum auctor ligula ac neque auctor, nec varius metus vulputate. Pellentesque vitae ex id lectus semper cursus. Vestibulum eu tellus fringilla, venenatis lacus vel, rutrum elit. Nam ut velit non magna euismod porttitor non ut odio. Aenean commodo leo sit amet lobortis pharetra. Proin eu felis at dui rutrum feugiat. Nullam cursus metus eu eros volutpat, sed placerat quam condimentum. Sed mollis leo et arcu tempor, quis lacinia erat rhoncus. Etiam aliquam augue sed ipsum pretium, ac efficitur lacus varius. Morbi ac felis fringilla ligula sagittis vehicula ac eu erat. Nullam aliquam justo scelerisque tortor egestas molestie. Curabitur fringilla risus vel urna ullamcorper, id placerat nibh fermentum. Mauris sed dui a dolor dictum bibendum. Suspendisse lacinia mi eu ligula eleifend varius. Maecenas blandit ipsum non nulla rhoncus, sed dapibus augue pellentesque. Vestibulum at lectus pharetra enim mattis ultricies sit amet eget est. Nulla euismod eros sed cursus vestibulum. Mauris tincidunt dui quis libero dignissim, nec blandit odio vulputate. Pellentesque in elit tristique, maximus mauris non, gravida nibh. Maecenas condimentum dolor et eros tempor, vel consequat ante convallis. Etiam ultricies lorem vel molestie semper. Curabitur venenatis diam sit amet porta blandit. Maecenas eget urna at urna ullamcorper consectetur. Praesent luctus velit eget elit ultricies malesuada. Nam tincidunt purus quis lorem cursus, viverra mattis orci tempor. Vestibulum mollis urna sed nisi faucibus imperdiet. Etiam imperdiet turpis quis quam vehicula sollicitudin. Ut efficitur leo in ultrices dignissim. Etiam tempor lorem volutpat, rhoncus nunc ac, porta turpis. Pellentesque vehicula ligula non mi ultricies, vitae convallis libero hendrerit. Praesent ultrices neque at erat accumsan sagittis. Duis eget risus in ligula lacinia fermentum sit amet ac est. Aenean sed turpis elementum, tincidunt nisi vitae, porttitor velit. Maecenas sed sem porta, vulputate ex eu, tempus sem. Aenean in est sed tortor imperdiet auctor eu et velit. Morbi faucibus odio vestibulum, vestibulum eros eu, commodo erat. Duis ac orci et arcu accumsan porttitor id vitae mauris. Pellentesque in nisl laoreet, condimentum nulla sit amet, dignissim quam. Proin aliquet libero at placerat fringilla. Duis aliquam elit eget massa malesuada pellentesque eget vel tortor. Suspendisse ut justo ut sem accumsan hendrerit vitae sed purus. Integer et ex in magna aliquam fringilla. Suspendisse nec libero ut lorem egestas pretium quis et nibh. Quisque at augue gravida, aliquam enim eu, hendrerit quam. Phasellus a ligula vulputate, blandit sem nec, porttitor urna. Duis ac massa quis purus tincidunt laoreet. Etiam elementum sem a elit ornare, quis ornare eros suscipit. Sed sed ante venenatis, scelerisque libero ut, consequat magna. Vivamus maximus lectus sed varius laoreet. Fusce eu ligula hendrerit, auctor libero vitae, vestibulum risus. Duis in mi tempus, sollicitudin metus et, faucibus justo. Sed quis eros in diam semper faucibus vel in turpis. Integer vulputate tortor non eleifend tempor. Nunc volutpat velit et ex rhoncus tincidunt. Nullam eleifend massa ut sapien facilisis, ornare gravida orci varius. Nam et eros a sapien pellentesque laoreet eget in velit. Mauris vitae velit pellentesque eros luctus dignissim ut eu eros. Donec vitae ligula vehicula, finibus risus nec, auctor magna. Curabitur ut tortor in urna bibendum accumsan. Maecenas tincidunt justo in varius fringilla. Donec tristique eros quis erat tempus, nec scelerisque quam tempor. Vestibulum eget sapien non odio rhoncus viverra nec ut nunc. Maecenas fringilla eros vitae rutrum dignissim. Aenean ornare mauris vitae ligula euismod placerat. In sagittis nibh in tempus cursus. Aenean sodales dui vel quam bibendum, id interdum ligula suscipit. Nam imperdiet felis et nisl lacinia ultrices. Praesent ac arcu quis est fringilla fringilla. Ut venenatis lorem vel arcu congue, id vehicula nunc commodo. Donec at lectus ullamcorper tellus gravida hendrerit. Curabitur quis risus eu neque lacinia rhoncus. Duis dictum nulla id lacus rutrum finibus. Nullam eget erat egestas, interdum sem eu, pellentesque nunc. Proin id nisi ut risus cursus fringilla quis vitae libero. Morbi convallis nulla ut turpis mattis, a dapibus leo feugiat. Integer quis erat ac lorem eleifend mollis. Praesent et est bibendum sem varius vestibulum. Praesent eu orci nec libero auctor euismod ut vitae leo. Curabitur et sem sed lacus bibendum vehicula quis vel lorem. Vivamus posuere lacus id arcu dignissim feugiat. Pellentesque vel enim sollicitudin dolor suscipit faucibus. Duis ac tellus vitae lacus vulputate finibus a a justo. Cras vel urna ut est pharetra porttitor. Ut dignissim ante eget mauris bibendum sollicitudin. Vivamus cursus elit sit amet malesuada pharetra. Etiam finibus lorem sed mi viverra, ut ultrices ex gravida. Pellentesque gravida ipsum a risus luctus, vehicula molestie lacus placerat. Nunc in quam sit amet odio placerat lobortis. Ut id est bibendum, pulvinar turpis nec, facilisis arcu. Vestibulum blandit mi eu eros dapibus placerat a eget nisi. Donec tristique ex in vestibulum malesuada. Integer non erat cursus, vehicula libero vel, porttitor metus. Duis id libero et lectus dictum interdum eu tempus turpis. Sed pellentesque sapien ut auctor ultricies. Vestibulum et mi at orci convallis semper. Mauris interdum orci et turpis dapibus, nec porta lorem iaculis. Nam sed erat et dui rutrum aliquet in sit amet nunc. Donec egestas tellus id gravida lacinia. Nulla egestas mauris in dolor imperdiet, id sodales libero blandit. Duis scelerisque ante et enim lobortis, posuere iaculis nunc auctor. Donec ac dui mollis, dignissim lorem pretium, cursus lorem. Morbi laoreet sapien sed mauris vestibulum sollicitudin. Sed ultrices nisi in venenatis porta. Vestibulum eu est porttitor, facilisis ligula nec, dapibus justo. Curabitur aliquam dolor at nibh lacinia maximus. Nam ut nisl nec lectus tincidunt hendrerit. Cras vehicula lectus nec mauris tristique, a finibus arcu semper. Cras facilisis erat ornare lacus facilisis, nec posuere nisi lacinia. Donec ut nibh lacinia, pellentesque augue sit amet, molestie lorem. Sed rhoncus ligula non ante dapibus pulvinar. Sed varius leo vel iaculis egestas. Duis tristique dolor cursus nisi pellentesque, sed lacinia eros tempus. Phasellus at libero sodales, hendrerit mi a, feugiat quam. Suspendisse mattis tellus sed felis sodales, et finibus velit consectetur. In in massa accumsan, sollicitudin sem at, dapibus lacus. Quisque consequat nisi ac sem vestibulum, sit amet auctor libero vestibulum. Sed non libero vel urna interdum vehicula in ut est. Mauris at orci sagittis, interdum nunc ac, dignissim magna. Nullam fringilla velit ac quam placerat, vitae facilisis eros molestie. Mauris lacinia augue id dui commodo, quis molestie dolor mattis. Vestibulum ac mi sed libero dictum sagittis. Aliquam maximus augue eget ipsum elementum viverra. Praesent vehicula nunc in convallis molestie. Cras scelerisque purus vel euismod vestibulum. Vestibulum sed augue interdum, commodo mi sit amet, luctus neque. Etiam efficitur dui dignissim ipsum egestas dignissim. Donec eget ex sit amet orci vulputate efficitur. Fusce suscipit velit vitae quam fringilla ultrices. Vivamus non felis tempor, gravida ligula vitae, facilisis nunc. Maecenas commodo quam sit amet dolor consectetur tempor. Ut a lorem suscipit, viverra velit non, rhoncus enim. Sed nec metus nec mauris dapibus ultrices. Morbi porttitor purus at purus euismod, ac eleifend augue ornare. Ut quis enim molestie, sollicitudin tellus quis, hendrerit urna. Donec eu odio a dolor aliquam tincidunt. Sed eu velit vel dui posuere accumsan ac in mi. Praesent vehicula mauris non ex sagittis lacinia. Sed ut est ultricies, tincidunt erat sit amet, efficitur quam. Ut tincidunt dolor sed sollicitudin interdum. Vivamus in velit quis neque facilisis pulvinar sed quis odio. Pellentesque lacinia magna sit amet turpis posuere elementum. In in risus dignissim, feugiat mi et, placerat metus. Mauris id felis sit amet dui sodales dapibus. Donec a mi a ante facilisis efficitur ac sit amet lectus. Sed rutrum ante faucibus lobortis interdum. Nulla ut massa et eros finibus placerat. Ut sed odio nec felis varius ornare a at urna. Sed scelerisque ex non eros hendrerit, sed ullamcorper ante rhoncus. Quisque a turpis ac velit suscipit porta. Nulla gravida neque vitae dolor congue bibendum. Nullam nec neque sed nibh interdum interdum et eget quam. Duis sit amet enim et quam tempor accumsan. Fusce nec mauris non nulla sodales ultrices eget a mauris. Etiam quis felis tincidunt, consequat sapien vel, consequat erat. Nam pretium tellus vitae rhoncus commodo. Nam sed urna ullamcorper, condimentum metus eget, aliquam lectus. Sed quis massa eu odio tincidunt sagittis vitae eget sem. Sed placerat ligula sed eros porttitor tincidunt. Maecenas auctor odio vel ante iaculis facilisis. Pellentesque quis erat suscipit, feugiat felis at, dapibus est. Etiam at sem quis neque cursus ullamcorper. Donec pharetra magna ut diam hendrerit, ut tincidunt est feugiat. Quisque convallis arcu vel nibh malesuada tristique. Maecenas in felis ac erat aliquam venenatis venenatis vel tortor. Suspendisse vulputate lorem et lacus varius imperdiet. Nullam tristique nisl at gravida imperdiet. Aenean luctus mi eu ligula tempor ultricies. Cras et velit sed ligula cursus molestie. Phasellus placerat leo vel lacus finibus convallis. Vivamus varius felis eget sollicitudin pellentesque. Pellentesque quis nulla blandit, consectetur tellus ut, dictum massa. Cras vel nunc vitae nibh pharetra dignissim at nec urna. Etiam ac nunc sollicitudin, pharetra justo quis, accumsan nibh. Ut eleifend tellus a odio rutrum ornare. Praesent tempor lectus eu tortor viverra euismod. Mauris eu erat vel magna iaculis rutrum gravida nec turpis. Sed non nisi vitae enim convallis efficitur ut ac quam. Suspendisse ac lorem vitae dui sollicitudin fringilla. Vestibulum in sapien vitae elit congue faucibus in et urna. Integer sagittis purus ornare quam placerat, id consectetur ex vulputate. */
Comment
v0.6.6+commit.6c089d02
None
ipfs://0ec466099f91e6050ea3d8f659be6ac94ec071296e0dbe88ad39334faa48fddc
{ "func_code_index": [ 12975, 13149 ] }
3,779
FluxContract
FluxContract.sol
0xb2993d177971165890f634f0e52f13d89160013a
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; //그 집은 한국에서 지어졌어요 //저는 한국에서 살고 있어요 constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /* Integer pharetra massa eget facilisis commodo. Integer in dolor vitae eros pretium suscipit et scelerisque neque. Duis condimentum justo ac volutpat consequat. Curabitur id erat suscipit, pharetra neque ac, luctus urna. Sed maximus augue et mauris interdum tristique. Proin et sem viverra, fringilla massa non, egestas sem. Nulla id mauris tristique, porta eros sit amet, mollis mauris. Pellentesque eu magna eu nunc molestie interdum nec nec felis. Sed non ante at lectus accumsan lobortis nec vitae lectus. Ut fringilla mi ac est rhoncus, molestie convallis massa consectetur. Duis cursus sem nec metus commodo, quis consequat est congue. Fusce convallis erat at lectus pharetra venenatis. Donec porta ligula et massa congue, lobortis scelerisque quam tempor. Suspendisse dictum arcu et nibh ullamcorper laoreet. Fusce quis ex pellentesque, varius erat at, interdum elit. Nunc sed ex vel neque malesuada cursus. Donec a mi viverra, venenatis sapien ac, cursus sapien. Suspendisse mattis felis eget ligula gravida fermentum. Ut faucibus mauris euismod porta lacinia. Nam rhoncus tortor non leo lobortis, id commodo ex egestas. Suspendisse ac leo vel orci aliquam congue. Vivamus ornare sem vitae metus lacinia hendrerit. Quisque eget odio a ex sodales sagittis. Vestibulum auctor ligula ac neque auctor, nec varius metus vulputate. Pellentesque vitae ex id lectus semper cursus. Vestibulum eu tellus fringilla, venenatis lacus vel, rutrum elit. Nam ut velit non magna euismod porttitor non ut odio. Aenean commodo leo sit amet lobortis pharetra. Proin eu felis at dui rutrum feugiat. Nullam cursus metus eu eros volutpat, sed placerat quam condimentum. Sed mollis leo et arcu tempor, quis lacinia erat rhoncus. Etiam aliquam augue sed ipsum pretium, ac efficitur lacus varius. Morbi ac felis fringilla ligula sagittis vehicula ac eu erat. Nullam aliquam justo scelerisque tortor egestas molestie. Curabitur fringilla risus vel urna ullamcorper, id placerat nibh fermentum. Mauris sed dui a dolor dictum bibendum. Suspendisse lacinia mi eu ligula eleifend varius. Maecenas blandit ipsum non nulla rhoncus, sed dapibus augue pellentesque. Vestibulum at lectus pharetra enim mattis ultricies sit amet eget est. Nulla euismod eros sed cursus vestibulum. Mauris tincidunt dui quis libero dignissim, nec blandit odio vulputate. Pellentesque in elit tristique, maximus mauris non, gravida nibh. Maecenas condimentum dolor et eros tempor, vel consequat ante convallis. Etiam ultricies lorem vel molestie semper. Curabitur venenatis diam sit amet porta blandit. Maecenas eget urna at urna ullamcorper consectetur. Praesent luctus velit eget elit ultricies malesuada. Nam tincidunt purus quis lorem cursus, viverra mattis orci tempor. Vestibulum mollis urna sed nisi faucibus imperdiet. Etiam imperdiet turpis quis quam vehicula sollicitudin. Ut efficitur leo in ultrices dignissim. Etiam tempor lorem volutpat, rhoncus nunc ac, porta turpis. Pellentesque vehicula ligula non mi ultricies, vitae convallis libero hendrerit. Praesent ultrices neque at erat accumsan sagittis. Duis eget risus in ligula lacinia fermentum sit amet ac est. Aenean sed turpis elementum, tincidunt nisi vitae, porttitor velit. Maecenas sed sem porta, vulputate ex eu, tempus sem. Aenean in est sed tortor imperdiet auctor eu et velit. Morbi faucibus odio vestibulum, vestibulum eros eu, commodo erat. Duis ac orci et arcu accumsan porttitor id vitae mauris. Pellentesque in nisl laoreet, condimentum nulla sit amet, dignissim quam. Proin aliquet libero at placerat fringilla. Duis aliquam elit eget massa malesuada pellentesque eget vel tortor. Suspendisse ut justo ut sem accumsan hendrerit vitae sed purus. Integer et ex in magna aliquam fringilla. Suspendisse nec libero ut lorem egestas pretium quis et nibh. Quisque at augue gravida, aliquam enim eu, hendrerit quam. Phasellus a ligula vulputate, blandit sem nec, porttitor urna. Duis ac massa quis purus tincidunt laoreet. Etiam elementum sem a elit ornare, quis ornare eros suscipit. Sed sed ante venenatis, scelerisque libero ut, consequat magna. Vivamus maximus lectus sed varius laoreet. Fusce eu ligula hendrerit, auctor libero vitae, vestibulum risus. Duis in mi tempus, sollicitudin metus et, faucibus justo. Sed quis eros in diam semper faucibus vel in turpis. Integer vulputate tortor non eleifend tempor. Nunc volutpat velit et ex rhoncus tincidunt. Nullam eleifend massa ut sapien facilisis, ornare gravida orci varius. Nam et eros a sapien pellentesque laoreet eget in velit. Mauris vitae velit pellentesque eros luctus dignissim ut eu eros. Donec vitae ligula vehicula, finibus risus nec, auctor magna. Curabitur ut tortor in urna bibendum accumsan. Maecenas tincidunt justo in varius fringilla. Donec tristique eros quis erat tempus, nec scelerisque quam tempor. Vestibulum eget sapien non odio rhoncus viverra nec ut nunc. Maecenas fringilla eros vitae rutrum dignissim. Aenean ornare mauris vitae ligula euismod placerat. In sagittis nibh in tempus cursus. Aenean sodales dui vel quam bibendum, id interdum ligula suscipit. Nam imperdiet felis et nisl lacinia ultrices. Praesent ac arcu quis est fringilla fringilla. Ut venenatis lorem vel arcu congue, id vehicula nunc commodo. Donec at lectus ullamcorper tellus gravida hendrerit. Curabitur quis risus eu neque lacinia rhoncus. Duis dictum nulla id lacus rutrum finibus. Nullam eget erat egestas, interdum sem eu, pellentesque nunc. Proin id nisi ut risus cursus fringilla quis vitae libero. Morbi convallis nulla ut turpis mattis, a dapibus leo feugiat. Integer quis erat ac lorem eleifend mollis. Praesent et est bibendum sem varius vestibulum. Praesent eu orci nec libero auctor euismod ut vitae leo. Curabitur et sem sed lacus bibendum vehicula quis vel lorem. Vivamus posuere lacus id arcu dignissim feugiat. Pellentesque vel enim sollicitudin dolor suscipit faucibus. Duis ac tellus vitae lacus vulputate finibus a a justo. Cras vel urna ut est pharetra porttitor. Ut dignissim ante eget mauris bibendum sollicitudin. Vivamus cursus elit sit amet malesuada pharetra. Etiam finibus lorem sed mi viverra, ut ultrices ex gravida. Pellentesque gravida ipsum a risus luctus, vehicula molestie lacus placerat. Nunc in quam sit amet odio placerat lobortis. Ut id est bibendum, pulvinar turpis nec, facilisis arcu. Vestibulum blandit mi eu eros dapibus placerat a eget nisi. Donec tristique ex in vestibulum malesuada. Integer non erat cursus, vehicula libero vel, porttitor metus. Duis id libero et lectus dictum interdum eu tempus turpis. Sed pellentesque sapien ut auctor ultricies. Vestibulum et mi at orci convallis semper. Mauris interdum orci et turpis dapibus, nec porta lorem iaculis. Nam sed erat et dui rutrum aliquet in sit amet nunc. Donec egestas tellus id gravida lacinia. Nulla egestas mauris in dolor imperdiet, id sodales libero blandit. Duis scelerisque ante et enim lobortis, posuere iaculis nunc auctor. Donec ac dui mollis, dignissim lorem pretium, cursus lorem. Morbi laoreet sapien sed mauris vestibulum sollicitudin. Sed ultrices nisi in venenatis porta. Vestibulum eu est porttitor, facilisis ligula nec, dapibus justo. Curabitur aliquam dolor at nibh lacinia maximus. Nam ut nisl nec lectus tincidunt hendrerit. Cras vehicula lectus nec mauris tristique, a finibus arcu semper. Cras facilisis erat ornare lacus facilisis, nec posuere nisi lacinia. Donec ut nibh lacinia, pellentesque augue sit amet, molestie lorem. Sed rhoncus ligula non ante dapibus pulvinar. Sed varius leo vel iaculis egestas. Duis tristique dolor cursus nisi pellentesque, sed lacinia eros tempus. Phasellus at libero sodales, hendrerit mi a, feugiat quam. Suspendisse mattis tellus sed felis sodales, et finibus velit consectetur. In in massa accumsan, sollicitudin sem at, dapibus lacus. Quisque consequat nisi ac sem vestibulum, sit amet auctor libero vestibulum. Sed non libero vel urna interdum vehicula in ut est. Mauris at orci sagittis, interdum nunc ac, dignissim magna. Nullam fringilla velit ac quam placerat, vitae facilisis eros molestie. Mauris lacinia augue id dui commodo, quis molestie dolor mattis. Vestibulum ac mi sed libero dictum sagittis. Aliquam maximus augue eget ipsum elementum viverra. Praesent vehicula nunc in convallis molestie. Cras scelerisque purus vel euismod vestibulum. Vestibulum sed augue interdum, commodo mi sit amet, luctus neque. Etiam efficitur dui dignissim ipsum egestas dignissim. Donec eget ex sit amet orci vulputate efficitur. Fusce suscipit velit vitae quam fringilla ultrices. Vivamus non felis tempor, gravida ligula vitae, facilisis nunc. Maecenas commodo quam sit amet dolor consectetur tempor. Ut a lorem suscipit, viverra velit non, rhoncus enim. Sed nec metus nec mauris dapibus ultrices. Morbi porttitor purus at purus euismod, ac eleifend augue ornare. Ut quis enim molestie, sollicitudin tellus quis, hendrerit urna. Donec eu odio a dolor aliquam tincidunt. Sed eu velit vel dui posuere accumsan ac in mi. Praesent vehicula mauris non ex sagittis lacinia. Sed ut est ultricies, tincidunt erat sit amet, efficitur quam. Ut tincidunt dolor sed sollicitudin interdum. Vivamus in velit quis neque facilisis pulvinar sed quis odio. Pellentesque lacinia magna sit amet turpis posuere elementum. In in risus dignissim, feugiat mi et, placerat metus. Mauris id felis sit amet dui sodales dapibus. Donec a mi a ante facilisis efficitur ac sit amet lectus. Sed rutrum ante faucibus lobortis interdum. Nulla ut massa et eros finibus placerat. Ut sed odio nec felis varius ornare a at urna. Sed scelerisque ex non eros hendrerit, sed ullamcorper ante rhoncus. Quisque a turpis ac velit suscipit porta. Nulla gravida neque vitae dolor congue bibendum. Nullam nec neque sed nibh interdum interdum et eget quam. Duis sit amet enim et quam tempor accumsan. Fusce nec mauris non nulla sodales ultrices eget a mauris. Etiam quis felis tincidunt, consequat sapien vel, consequat erat. Nam pretium tellus vitae rhoncus commodo. Nam sed urna ullamcorper, condimentum metus eget, aliquam lectus. Sed quis massa eu odio tincidunt sagittis vitae eget sem. Sed placerat ligula sed eros porttitor tincidunt. Maecenas auctor odio vel ante iaculis facilisis. Pellentesque quis erat suscipit, feugiat felis at, dapibus est. Etiam at sem quis neque cursus ullamcorper. Donec pharetra magna ut diam hendrerit, ut tincidunt est feugiat. Quisque convallis arcu vel nibh malesuada tristique. Maecenas in felis ac erat aliquam venenatis venenatis vel tortor. Suspendisse vulputate lorem et lacus varius imperdiet. Nullam tristique nisl at gravida imperdiet. Aenean luctus mi eu ligula tempor ultricies. Cras et velit sed ligula cursus molestie. Phasellus placerat leo vel lacus finibus convallis. Vivamus varius felis eget sollicitudin pellentesque. Pellentesque quis nulla blandit, consectetur tellus ut, dictum massa. Cras vel nunc vitae nibh pharetra dignissim at nec urna. Etiam ac nunc sollicitudin, pharetra justo quis, accumsan nibh. Ut eleifend tellus a odio rutrum ornare. Praesent tempor lectus eu tortor viverra euismod. Mauris eu erat vel magna iaculis rutrum gravida nec turpis. Sed non nisi vitae enim convallis efficitur ut ac quam. Suspendisse ac lorem vitae dui sollicitudin fringilla. Vestibulum in sapien vitae elit congue faucibus in et urna. Integer sagittis purus ornare quam placerat, id consectetur ex vulputate. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /* Vivamus egestas neque eget ultrices hendrerit. Donec elementum odio nec ex malesuada cursus. Curabitur condimentum ante id ipsum porta ullamcorper. Vivamus ut est elementum, interdum eros vitae, laoreet neque. Pellentesque elementum risus tincidunt erat viverra hendrerit. Donec nec velit ut lectus fringilla lacinia. Donec laoreet enim at diam blandit tincidunt. Aenean sollicitudin sem vitae dui sollicitudin finibus. Donec vitae massa varius erat cursus commodo nec a lectus. Vivamus egestas neque eget ultrices hendrerit. Donec elementum odio nec ex malesuada cursus. Curabitur condimentum ante id ipsum porta ullamcorper. Vivamus ut est elementum, interdum eros vitae, laoreet neque. Pellentesque elementum risus tincidunt erat viverra hendrerit. Donec nec velit ut lectus fringilla lacinia. Donec laoreet enim at diam blandit tincidunt. Aenean sollicitudin sem vitae dui sollicitudin finibus. Donec vitae massa varius erat cursus commodo nec a lectus. Nulla dapibus sapien ut gravida commodo. Phasellus dignissim justo et nisi fermentum commodo. Etiam non sapien quis erat lacinia tempor. Suspendisse egestas diam in vestibulum sagittis. Pellentesque eget tellus volutpat, interdum erat eget, viverra nunc. Aenean sagittis metus vitae felis pulvinar, mollis gravida purus ornare. Morbi hendrerit eros sed suscipit bibendum. Suspendisse egestas ante in mi maximus, quis aliquam elit porttitor. Donec eget sem aliquam, placerat purus at, lobortis lorem. Sed feugiat lectus non justo auctor placerat. Sed sit amet nulla volutpat, sagittis risus non, congue nibh. Integer vel ligula gravida, sollicitudin eros non, dictum nibh. Quisque non nisi molestie, interdum mi eget, ultrices nisl. Quisque maximus risus quis dignissim tempor. Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero. Integer consequat velit ut auctor ullamcorper. Pellentesque mattis quam sed sollicitudin mattis. Sed feugiat lectus non justo auctor placerat. Sed sit amet nulla volutpat, sagittis risus non, congue nibh. Integer vel ligula gravida, sollicitudin eros non, dictum nibh. Quisque non nisi molestie, interdum mi eget, ultrices nisl. Quisque maximus risus quis dignissim tempor. Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero. Integer consequat velit ut auctor ullamcorper. Pellentesque mattis quam sed sollicitudin mattis. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
_burn
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); }
/* Vivamus egestas neque eget ultrices hendrerit. Donec elementum odio nec ex malesuada cursus. Curabitur condimentum ante id ipsum porta ullamcorper. Vivamus ut est elementum, interdum eros vitae, laoreet neque. Pellentesque elementum risus tincidunt erat viverra hendrerit. Donec nec velit ut lectus fringilla lacinia. Donec laoreet enim at diam blandit tincidunt. Aenean sollicitudin sem vitae dui sollicitudin finibus. Donec vitae massa varius erat cursus commodo nec a lectus. Vivamus egestas neque eget ultrices hendrerit. Donec elementum odio nec ex malesuada cursus. Curabitur condimentum ante id ipsum porta ullamcorper. Vivamus ut est elementum, interdum eros vitae, laoreet neque. Pellentesque elementum risus tincidunt erat viverra hendrerit. Donec nec velit ut lectus fringilla lacinia. Donec laoreet enim at diam blandit tincidunt. Aenean sollicitudin sem vitae dui sollicitudin finibus. Donec vitae massa varius erat cursus commodo nec a lectus. Nulla dapibus sapien ut gravida commodo. Phasellus dignissim justo et nisi fermentum commodo. Etiam non sapien quis erat lacinia tempor. Suspendisse egestas diam in vestibulum sagittis. Pellentesque eget tellus volutpat, interdum erat eget, viverra nunc. Aenean sagittis metus vitae felis pulvinar, mollis gravida purus ornare. Morbi hendrerit eros sed suscipit bibendum. Suspendisse egestas ante in mi maximus, quis aliquam elit porttitor. Donec eget sem aliquam, placerat purus at, lobortis lorem. Sed feugiat lectus non justo auctor placerat. Sed sit amet nulla volutpat, sagittis risus non, congue nibh. Integer vel ligula gravida, sollicitudin eros non, dictum nibh. Quisque non nisi molestie, interdum mi eget, ultrices nisl. Quisque maximus risus quis dignissim tempor. Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero. Integer consequat velit ut auctor ullamcorper. Pellentesque mattis quam sed sollicitudin mattis. Sed feugiat lectus non justo auctor placerat. Sed sit amet nulla volutpat, sagittis risus non, congue nibh. Integer vel ligula gravida, sollicitudin eros non, dictum nibh. Quisque non nisi molestie, interdum mi eget, ultrices nisl. Quisque maximus risus quis dignissim tempor. Nam sit amet tellus vulputate, fringilla sapien in, porttitor libero. Integer consequat velit ut auctor ullamcorper. Pellentesque mattis quam sed sollicitudin mattis. */
Comment
v0.6.6+commit.6c089d02
None
ipfs://0ec466099f91e6050ea3d8f659be6ac94ec071296e0dbe88ad39334faa48fddc
{ "func_code_index": [ 17328, 17751 ] }
3,780
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
newSeries
function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); }
/** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 1850, 2437 ] }
3,781
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
lockSeries
function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; }
/** * @dev Permanently lock the series to changes in pixels. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 2728, 3181 ] }
3,782
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setSeriesPatches
function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); }
/** * @dev Update the patches that govern series pixels. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 3396, 3643 ] }
3,783
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setSeriesDimensions
function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); }
/** * @dev Update the dimensions of the series. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 3710, 4008 ] }
3,784
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setSeriesDefaultPalette
function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; }
/** * @dev Update the default palette for a series when the token doesn't have one. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4111, 4388 ] }
3,785
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setSeriesName
function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; }
/** * @dev Update the series name. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4442, 4604 ] }
3,786
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setSeriesDescription
function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; }
/** * @dev Update the series description. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 4665, 4855 ] }
3,787
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setOnlyEarlyAccess
function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); }
/** * @dev Set the onlyEarlyAccess flag. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 5782, 5911 ] }
3,788
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setEarlyAccessGrants
function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } }
/** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 6276, 6507 ] }
3,789
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
earlyAccessFor
function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; }
/** * @dev Returns the total early-access allocation for the address. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 6596, 6710 ] }
3,790
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
safeMintInSeries
function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); }
/** * @dev Allow minting of the genesis pieces. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 6922, 7149 ] }
3,791
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
safeMint
function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); }
/** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 7295, 8610 ] }
3,792
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
tokenSeries
function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; }
/** * @dev Returns the seriesId of a token. The token may not exist. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 9284, 9414 ] }
3,793
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
tokenEditionNum
function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; }
/** * @dev Returns a token's edition within its series. The token may not exist. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 9514, 9648 ] }
3,794
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
_safeMintInSeries
function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); }
/** * @dev Mints the next token in the series. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 9714, 11012 ] }
3,795
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
approveForPalette
function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); }
/** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 11522, 11908 ] }
3,796
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
resetPalette
function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); }
/** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 12596, 13232 ] }
3,797
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setPalette
function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); }
/** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 13359, 13788 ] }
3,798
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
seriesPixels
function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); }
/** * @dev Concatenates a series' patches into a single array. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 13870, 14057 ] }
3,799
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
pixelsOf
function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); }
/** * @dev Token equivalent of seriesPixels(). */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 14123, 14313 ] }
3,800
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
_tokenPalette
function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); }
/** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 14543, 15071 ] }
3,801
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
bmpOf
function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); }
/** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 15215, 15879 ] }
3,802
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
bmpDataURIOf
function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); }
/** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 15979, 16134 ] }
3,803
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
brooksMatelskiOf
function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); }
/** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 16336, 17265 ] }
3,804
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
setBaseExternalUrl
function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; }
/** * @dev Set the base URL for external_url metadata field. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 17485, 17592 ] }
3,805
GermanBakery
/contracts/Brotchain.sol
0x5721be2b7b1403daaea264daa26c29c51398bc2f
Solidity
Brotchain
contract Brotchain is BaseOpenSea, ERC721Enumerable, ERC721Pausable, Ownable, PullPayment { /** * @dev A BMP pixel encoder, supporting arbitrary colour palettes. */ BMP public immutable _bmp; /** * @dev A Mandelbrot-and-friends fractal generator. */ Mandelbrot public immutable _brots; /** * @dev Maximum number of editions per series. */ uint256 public constant MAX_PER_SERIES = 64; /** * @dev Mint price = pi/10. */ uint256 public constant MINT_PRICE = (314159 ether) / 1000000; constructor(string memory name, string memory symbol, address brots, address openSeaProxyRegistry) ERC721(name, symbol) { _bmp = new BMP(); _brots = Mandelbrot(brots); if (openSeaProxyRegistry != address(0)) { _setOpenSeaRegistry(openSeaProxyRegistry); } } /** * @dev Base config for pricing + all tokens in a series. */ struct Series { uint256[] patches; uint256 numMinted; uint32 width; uint32 height; bytes defaultPalette; bool locked; string name; string description; } /** * @dev All existing series configs. */ Series[] public seriesConfigs; /** * @dev Require that the series exists. */ modifier seriesMustExist(uint256 seriesId) { require(seriesId < seriesConfigs.length, "Series doesn't exist"); _; } /** * @dev Creates a new series of brots, based on the precomputed patches. * * The seriesId MUST be equal to seriesConfigs.length. This is a safety * measure for automated deployment of multiple series in case an earlier * transaction fails as series would otherwise be created out of order. This * effectively makes newSeries() idempotent. */ function newSeries(uint256 seriesId, string memory name, string memory description, uint256[] memory patches, uint32 width, uint32 height) external onlyOwner { require(seriesId == seriesConfigs.length, "Invalid new series ID"); seriesConfigs.push(Series({ name: name, description: description, patches: patches, width: width, height: height, numMinted: 0, locked: false, defaultPalette: new bytes(0) })); emit SeriesPixelsChanged(seriesId); } /** * @dev Require that the series isn't locked to updates. */ modifier seriesNotLocked(uint256 seriesId) { require(!seriesConfigs[seriesId].locked, "Series locked"); _; } /** * @dev Permanently lock the series to changes in pixels. */ function lockSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { Series memory series = seriesConfigs[seriesId]; uint256 length; for (uint i = 0; i < series.patches.length; i++) { length += _brots.cachedPatch(series.patches[i]).pixels.length; } require(series.width * series.height == length, "Invalid dimensions"); seriesConfigs[seriesId].locked = true; } /** * @dev Emitted when a series' patches or dimensions change. */ event SeriesPixelsChanged(uint256 indexed seriesId); /** * @dev Update the patches that govern series pixels. */ function setSeriesPatches(uint256 seriesId, uint256[] memory patches) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].patches = patches; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the dimensions of the series. */ function setSeriesDimensions(uint256 seriesId, uint32 width, uint32 height) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { seriesConfigs[seriesId].width = width; seriesConfigs[seriesId].height = height; emit SeriesPixelsChanged(seriesId); } /** * @dev Update the default palette for a series when the token doesn't have one. */ function setSeriesDefaultPalette(uint256 seriesId, bytes memory palette) external seriesMustExist(seriesId) seriesNotLocked(seriesId) onlyOwner { require(palette.length == 768, "256 colours required"); seriesConfigs[seriesId].defaultPalette = palette; } /** * @dev Update the series name. */ function setSeriesName(uint256 seriesId, string memory name) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].name = name; } /** * @dev Update the series description. */ function setSeriesDescription(uint256 seriesId, string memory description) external seriesMustExist(seriesId) onlyOwner { seriesConfigs[seriesId].description = description; } /** * @dev Token configuration such as series (pixels). */ struct TokenConfig { uint256 paletteChanges; address paletteBy; address paletteApproval; // paletteReset is actually a boolean, but sized to align with a 256-bit // boundary for better storage. See resetPalette(); uint192 paletteReset; bytes palette; } /** * @dev All existing token configs. */ mapping(uint256 => TokenConfig) public tokenConfigs; /** * @dev Whether to limit minting only to those in _earlyAccess mapping. */ bool public onlyEarlyAccess = true; /** * @dev Addresses with early minting access. */ mapping(address => uint256) private _earlyAccess; /** * @dev Emitted when setOnlyEarlyAccess(to) is called. */ event OnlyEarlyAccess(); /** * @dev Set the onlyEarlyAccess flag. */ function setOnlyEarlyAccess(bool to) external onlyOwner { onlyEarlyAccess = to; emit OnlyEarlyAccess(); } /** * @dev Call parameter for early access because mapping()s are disallowed. */ struct EarlyAccess { address addr; uint256 totalAllowed; } /** * @dev Set early-access granting or revocation for the addresses. * * The supply is not the amount left, but the total in the early-access * phase. */ function setEarlyAccessGrants(EarlyAccess[] calldata addresses) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i].addr] = addresses[i].totalAllowed; } } /** * @dev Returns the total early-access allocation for the address. */ function earlyAccessFor(address addr) public view returns (uint256) { return _earlyAccess[addr]; } /** * @dev Max number that the contract owner can mint in a specific series. */ uint256 public constant OWNER_ALLOCATION = 2; /** * @dev Allow minting of the genesis pieces. */ function safeMintInSeries(uint256 seriesId) external seriesMustExist(seriesId) onlyOwner { require(seriesConfigs[seriesId].numMinted < OWNER_ALLOCATION, "Don't be greedy"); _safeMintInSeries(seriesId); } /** * @dev Mint one edition, from a randomly selected series. * * # NB see the bug described in _safeMintInSeries(). */ function safeMint() external payable { require(msg.value >= MINT_PRICE, "Insufficient payment"); _asyncTransfer(owner(), msg.value); uint256 numSeries = seriesConfigs.length; // We need some sort of randomness to choose which series is issued // next. sha3 is, by nature of being a cryptographic hash, a good PRNG. // Although this can technically be manipulated by someone in control of // block.timestamp, they're in a race against other blocks and also the // last minted (which is also random). If you can control this and care // enough to do so, then you deserve to choose which series you get! uint256 rand = uint256(keccak256(abi.encodePacked( _msgSender(), block.timestamp, lastTokenMinted ))) % numSeries; // uniform if numSeries is a power of 2 (it is) // Try each, starting from a random index, until a series with // capacity is found. for (uint256 i = 0; i < numSeries; i++) { uint256 seriesId = (rand + i) % numSeries; if (seriesConfigs[seriesId].numMinted < MAX_PER_SERIES) { _safeMintInSeries(seriesId); return; } } revert("All series sold out"); } /** * @dev Last tokenId minted. * * This doesn't increment because the series could be different to the one * before. It's useful for randomly choosing the next token and for testing * too. Even at a gas price of 100, updating this only costs 0.0005 ETH. */ uint256 public lastTokenMinted; /** * @dev Value by which seriesId is multiplied for the prefix of a tokenId. * * Series 0 will have tokens 0, 1, 2…; series 1 will have tokens 1000, 1001, * etc. */ uint256 private constant _tokenIdSeriesMultiplier = 1e4; /** * @dev Returns the seriesId of a token. The token may not exist. */ function tokenSeries(uint256 tokenId) public pure returns (uint256) { return tokenId / _tokenIdSeriesMultiplier; } /** * @dev Returns a token's edition within its series. The token may not exist. */ function tokenEditionNum(uint256 tokenId) public pure returns (uint256) { return tokenId % _tokenIdSeriesMultiplier; } /** * @dev Mints the next token in the series. */ function _safeMintInSeries(uint256 seriesId) internal seriesMustExist(seriesId) { /** * ################################ * There is a bug in this code that we only discovered after deployment. * A minter can move their piece to a different wallet, reducing their * balance, and then mint again. See GermanBakery.sol for the fix. * ################################ */ if (_msgSender() != owner()) { if (onlyEarlyAccess) { require(balanceOf(_msgSender()) < _earlyAccess[_msgSender()], "Early access exhausted for wallet"); } else { require(balanceOf(_msgSender()) < seriesConfigs.length, "Wallet cap reached"); } } Series memory series = seriesConfigs[seriesId]; uint256 tokenId = seriesId * _tokenIdSeriesMultiplier + series.numMinted; lastTokenMinted = tokenId; tokenConfigs[tokenId] = TokenConfig({ paletteChanges: 0, paletteBy: address(0), paletteApproval: address(0), paletteReset: 0, palette: new bytes(0) }); seriesConfigs[seriesId].numMinted++; _safeMint(_msgSender(), tokenId); emit TokenBMPChanged(tokenId); } /** * @dev Emitted when the address is approved to change a token's palette. */ event PaletteApproval(uint256 indexed tokenId, address approved); /** * @dev Approve the address to change the token's palette. * * Set to 0x00 address to revoke. Token owner and ERC721 approved already * have palette approval. This is to allow someone else to modify a palette * without the risk of them transferring the token. * * Revoked upon token transfer. */ function approveForPalette(uint256 tokenId, address approved) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Only owner or approver"); address owner = ownerOf(tokenId); require(approved != owner, "Approving token owner"); tokenConfigs[tokenId].paletteApproval = approved; emit PaletteApproval(tokenId, approved); } /** * @dev Emitted to signal changing of a token's BMP. */ event TokenBMPChanged(uint256 indexed tokenId); /** * @dev Require that the message sender is approved for palette changes. */ modifier approvedForPalette(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId) || tokenConfigs[tokenId].paletteApproval == _msgSender(), "Not approved for palette" ); _; } /** * @dev Clear a token's palette, using the series default instead. * * Does not reset the paletteChanges count, but increments it. * * Emits TokenBMPChanged(tokenId); */ function resetPalette(uint256 tokenId) approvedForPalette(tokenId) external { require(tokenConfigs[tokenId].paletteReset == 0, "Already reset"); tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = address(0); // Initial palette setting costs about 0.01 ETH at 30 gas but changes // are a little over 25% of that. Using a boolean for reset adds // negligible cost to the reset, in exchange for greater savings on the // next setPalette() call. tokenConfigs[tokenId].paletteReset = 1; emit TokenBMPChanged(tokenId); } /** * @dev Set a token's palette if an owner or has approval. * * Emits TokenBMPChanged(tokenId). */ function setPalette(uint256 tokenId, bytes memory palette) approvedForPalette(tokenId) external { require(palette.length == 768, "256 colours required"); tokenConfigs[tokenId].palette = palette; tokenConfigs[tokenId].paletteChanges++; tokenConfigs[tokenId].paletteBy = _msgSender(); tokenConfigs[tokenId].paletteReset = 0; emit TokenBMPChanged(tokenId); } /** * @dev Concatenates a series' patches into a single array. */ function seriesPixels(uint256 seriesId) public view seriesMustExist(seriesId) returns (bytes memory) { return _brots.concatenatePatches(seriesConfigs[seriesId].patches); } /** * @dev Token equivalent of seriesPixels(). */ function pixelsOf(uint256 tokenId) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); return seriesPixels(tokenSeries(tokenId)); } /** * @dev Returns the effective token palette, considering resets. * * Boolean flag indicates whether it's the original palette; i.e. nothing is * set or the palette has been explicitly reset(). */ function _tokenPalette(uint256 tokenId) private view returns (bytes memory, bool) { TokenConfig memory token = tokenConfigs[tokenId]; bytes memory palette = token.palette; bool original = token.paletteReset == 1 || palette.length == 0; if (original) { palette = seriesConfigs[tokenSeries(tokenId)].defaultPalette; if (palette.length == 0) { palette = _bmp.grayscale(); } } return (palette, original); } /** * @dev Returns the BMP-encoded token image, scaling pixels in both dimensions. * * Scale of 0 is treated as 1. */ function bmpOf(uint256 tokenId, uint32 scale) public view returns (bytes memory) { require(_exists(tokenId), "Token doesn't exist"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; (bytes memory palette, ) = _tokenPalette(tokenId); bytes memory pixels = pixelsOf(tokenId); if (scale > 1) { return _bmp.bmp( _bmp.scalePixels(pixels, series.width, series.height, scale), series.width * scale, series.height * scale, palette ); } return _bmp.bmp(pixels, series.width, series.height, palette); } /** * @dev Equivalent to bmpOf() but encoded as a data URI to view in a browser. */ function bmpDataURIOf(uint256 tokenId, uint32 scale) public view returns (string memory) { return _bmp.bmpDataURI(bmpOf(tokenId, scale)); } /** * @dev Renders the token as an ASCII brot. * * This is an homage to Robert W Brooks and Peter Matelski who were the * first to render the Mandelbrot, in this form. */ function brooksMatelskiOf(uint256 tokenId, string memory characters) external view returns (string memory) { bytes memory charset = abi.encodePacked(characters); require(charset.length == 256, "256 characters"); Series memory series = seriesConfigs[tokenSeries(tokenId)]; // Include newlines except for the end. bytes memory ascii = new bytes((series.width+1)*series.height - 1); bytes memory pixels = pixelsOf(tokenId); uint col; uint a; // ascii index for (uint p = 0; p < pixels.length; p++) { ascii[a] = charset[uint8(pixels[p])]; a++; col++; if (col == series.width && a < ascii.length) { ascii[a] = 0x0a; // Not compatible with Windows and typewriters. a++; col = 0; } } return string(ascii); } /** * @dev Base URL for external_url metadata field. */ string private _baseExternalUrl = "https://brotchain.art/brot/"; /** * @dev Set the base URL for external_url metadata field. */ function setBaseExternalUrl(string memory url) public onlyOwner { _baseExternalUrl = url; } /** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */ function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); } /** * @dev Pause the contract. */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract. */ function unpause() external onlyOwner { _unpause(); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || isOwnersOpenSeaProxy(owner, operator); } /** * @dev OpenSea collection config. * * https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory contractURI) external onlyOwner { _setContractURI(contractURI); } /** * @dev Revoke palette approval upon token transfer. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721Enumerable, ERC721Pausable) { tokenConfigs[tokenId].paletteApproval = address(0); super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
tokenURI
function tokenURI(uint256 tokenId) public override view returns (string memory) { TokenConfig memory token = tokenConfigs[tokenId]; Series memory series = seriesConfigs[tokenSeries(tokenId)]; uint256 editionNum = tokenEditionNum(tokenId); bytes memory data = abi.encodePacked( 'data:application/json,{', '"name":"', series.name, ' #', Strings.toString(editionNum) ,'",', '"description":"', series.description, '",' '"external_url":"', _baseExternalUrl, Strings.toString(tokenId),'",' ); // Combining this packing with the one above would result in the stack // being too deep and a failure to compile. data = abi.encodePacked( data, '"attributes":[' '{"value":"', series.name, '"},' '{', '"trait_type":"Palette Changes",', '"value":', Strings.toString(token.paletteChanges), '}' ); if (token.paletteBy != address(0)) { data = abi.encodePacked( data, ',{', '"trait_type":"Palette By",', '"value":"', Strings.toHexString(uint256(uint160(token.paletteBy)), 20),'"', '}' ); } (, bool original) = _tokenPalette(tokenId); if (original) { data = abi.encodePacked( data, ',{"value":"Original Palette"}' ); } if (editionNum == 0) { data = abi.encodePacked( data, ',{"value":"Genesis"}' ); } return string(abi.encodePacked( data, '],', '"image":"', bmpDataURIOf(tokenId, 1), '"', '}' )); }
/** * @dev Returns data URI of token metadata. * * The BMP-encoded image is included in its own base64-encoded data URI. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
{ "func_code_index": [ 17742, 19636 ] }
3,806