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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
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);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _approve | 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);
}
| /**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
8462,
8813
]
} | 1,107 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ERC20 | contract ERC20 is Context, IERC20 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
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);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
| /**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
9411,
9508
]
} | 1,108 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address owner) external view returns (uint256 balance);
| /**
* @dev Returns the number of tokens in ``owner``'s account.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
719,
798
]
} | 1,109 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | ownerOf | function ownerOf(uint256 tokenId) external view returns (address owner);
| /**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
944,
1021
]
} | 1,110 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(address from, address to, uint256 tokenId) external;
| /**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1733,
1816
]
} | 1,111 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address from, address to, uint256 tokenId) external;
| /**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2342,
2421
]
} | 1,112 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | approve | function approve(address to, uint256 tokenId) external;
| /**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2894,
2954
]
} | 1,113 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | getApproved | function getApproved(uint256 tokenId) external view returns (address operator);
| /**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3108,
3192
]
} | 1,114 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | setApprovalForAll | function setApprovalForAll(address operator, bool _approved) external;
| /**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3519,
3594
]
} | 1,115 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | isApprovedForAll | function isApprovedForAll(address owner, address operator) external view returns (bool);
| /**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3745,
3838
]
} | 1,116 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC721 | interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC721 compliant contract.
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
| /**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
4427,
4531
]
} | 1,117 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC1155 | interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account, uint256 id) external view returns (uint256);
| /**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1411,
1496
]
} | 1,118 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC1155 | interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/ | NatSpecMultiLine | balanceOfBatch | function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
| /**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1699,
1822
]
} | 1,119 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC1155 | interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/ | NatSpecMultiLine | setApprovalForAll | function setApprovalForAll(address operator, bool approved) external;
| /**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2087,
2161
]
} | 1,120 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC1155 | interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/ | NatSpecMultiLine | isApprovedForAll | function isApprovedForAll(address account, address operator) external view returns (bool);
| /**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2309,
2404
]
} | 1,121 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC1155 | interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/ | NatSpecMultiLine | safeTransferFrom | function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
| /**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2984,
3099
]
} | 1,122 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | IERC1155 | interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
} | /**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/ | NatSpecMultiLine | safeBatchTransferFrom | function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
| /**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3508,
3652
]
} | 1,123 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ECDSA | library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
} | /**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/ | NatSpecMultiLine | recover | function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
| /**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
811,
1577
]
} | 1,124 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ECDSA | library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
} | /**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/ | NatSpecMultiLine | recover | function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
| /**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1726,
3160
]
} | 1,125 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ECDSA | library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
} | /**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/ | NatSpecMultiLine | toEthSignedMessageHash | function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| /**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3429,
3703
]
} | 1,126 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | AccessControl | contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
} | /**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/ | NatSpecMultiLine | isSigner | function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
| /**
* @dev Checks if provided address has signer permissions.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1385,
1490
]
} | 1,127 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | AccessControl | contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
} | /**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/ | NatSpecMultiLine | isFrozen | function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
| /**
* @dev Returns true if the target account is frozen.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1570,
1677
]
} | 1,128 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | AccessControl | contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
} | /**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/ | NatSpecMultiLine | _unfreeze | function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
| /**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2029,
2233
]
} | 1,129 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | AccessControl | contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
} | /**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/ | NatSpecMultiLine | withdrawERC20 | function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
| /**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2319,
2521
]
} | 1,130 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | AccessControl | contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
} | /**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/ | NatSpecMultiLine | approveERC721 | function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
| /**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2608,
2749
]
} | 1,131 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | AccessControl | contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
} | /**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/ | NatSpecMultiLine | approveERC1155 | function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
| /**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2837,
2980
]
} | 1,132 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | AccessControl | contract AccessControl {
// The addresses that can co-sign transactions on the wallet
mapping(address => bool) signers;
// Frozen account that cant move funds
mapping (address => bool) private _frozen;
event Frozen(address target);
event Unfrozen(address target);
/**
* Set up multi-sig access by specifying the signers allowed to be used on this contract.
* 3 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
*
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) {
require(allowedSigners.length == 5, "AccessControl: Invalid number of signers");
for (uint8 i = 0; i < allowedSigners.length; i++) {
require(allowedSigners[i] != address(0), "AccessControl: Invalid signer address");
require(!signers[allowedSigners[i]], "AccessControl: Signer address duplication");
signers[allowedSigners[i]] = true;
}
}
/**
* @dev Throws if called by any account other than the signer.
*/
modifier onlySigner() {
require(signers[msg.sender], "AccessControl: Access denied");
_;
}
/**
* @dev Checks if provided address has signer permissions.
*/
function isSigner(address _addr) public view returns (bool) {
return signers[_addr];
}
/**
* @dev Returns true if the target account is frozen.
*/
function isFrozen(address target) public view returns (bool) {
return _frozen[target];
}
function _freeze(address target) internal {
require(!_frozen[target], "AccessControl: Target account is already frozen");
_frozen[target] = true;
emit Frozen(target);
}
/**
* @dev Mark target account as unfrozen.
* Can be called even if the contract doesn't allow to freeze accounts.
*/
function _unfreeze(address target) internal {
require(_frozen[target], "AccessControl: Target account is not frozen");
delete _frozen[target];
emit Unfrozen(target);
}
/**
* @dev Allow to withdraw ERC20 tokens from contract itself
*/
function withdrawERC20(IERC20 _tokenContract) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(msg.sender, balance);
}
/**
* @dev Allow to withdraw ERC721 tokens from contract itself
*/
function approveERC721(IERC721 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ERC1155 tokens from contract itself
*/
function approveERC1155(IERC1155 _tokenContract) external onlySigner {
_tokenContract.setApprovalForAll(msg.sender, true);
}
/**
* @dev Allow to withdraw ETH from contract itself
*/
function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
} | /**
* Access control holds contract signers (board members) and frozen accounts.
* Have utility modifiers for method safe access.
*/ | NatSpecMultiLine | withdrawEth | function withdrawEth(address payable _receiver) external onlySigner {
if (address(this).balance > 0) {
_receiver.transfer(address(this).balance);
}
}
| /**
* @dev Allow to withdraw ETH from contract itself
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3057,
3247
]
} | 1,133 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ERC20Burnable | abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "BCUG: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
} | /**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/ | NatSpecMultiLine | burn | function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
| /**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
161,
257
]
} | 1,134 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ERC20Burnable | abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "BCUG: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
} | /**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/ | NatSpecMultiLine | burnFrom | function burnFrom(address account, uint256 amount) public virtual {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "BCUG: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
| /**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
571,
907
]
} | 1,135 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ERC20Capped | abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap_) {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
}
}
} | /**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/ | NatSpecMultiLine | cap | function cap() public view virtual returns (uint256) {
return _cap;
}
| /**
* @dev Returns the cap on the token's total supply.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
403,
491
]
} | 1,136 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | ERC20Capped | abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap_) {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
}
}
} | /**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded");
}
}
| /**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
673,
994
]
} | 1,137 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | Pausable | abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
} | /**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/ | NatSpecMultiLine | paused | function paused() public view virtual returns (bool) {
return _paused;
}
| /**
* @dev Returns true if the contract is paused, and false otherwise.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
531,
622
]
} | 1,138 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | Pausable | abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
} | /**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/ | NatSpecMultiLine | _pause | function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
| /**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1331,
1454
]
} | 1,139 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | Pausable | abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
} | /**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/ | NatSpecMultiLine | _unpause | function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
| /**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1590,
1715
]
} | 1,140 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | mint | function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
| /**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1986,
2286
]
} | 1,141 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | mintBulk | function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
| /**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2407,
3022
]
} | 1,142 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | freeze | function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
| /**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3126,
3405
]
} | 1,143 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | unfreeze | function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
| /**
* @dev Mark target account as unfrozen.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3472,
3755
]
} | 1,144 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | burnFrozenTokens | function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
| /**
* @dev Burn tokens on frozen account.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
4794,
5192
]
} | 1,145 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | freezeAndBurnTokens | function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
| /**
* @dev Freeze and burn tokens in a single transaction.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
5274,
5618
]
} | 1,146 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | pause | function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
| /**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
5747,
6005
]
} | 1,147 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | unpause | function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
| /**
* @dev Returns to normal state.
* - The contract must be paused.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
6103,
6365
]
} | 1,148 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | getOperationHash | function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
| /**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
6545,
6755
]
} | 1,149 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | _beforeTokenTransfer | function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
| /**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
7072,
7537
]
} | 1,150 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | GovernanceToken | abstract contract GovernanceToken is ERC20Capped, ERC20Burnable, IFungibleToken, AccessControl, Pausable {
using ECDSA for bytes32;
// keccak256("mint(address target, uint256 amount, bytes[] signatures)")
bytes32 constant MINT_TYPEHASH = 0xdaef0006354e6aca5b14786fab16e27867b1ac002611e2fa58e0aa486080141f;
// keccak256("mintBulk(address[] target, uint256[] amount, bytes[] signatures)")
bytes32 constant MINT_BULK_TYPEHASH = 0x84bbfaa2e4384c51c0e71108356af77f996f8a1f97dc229b15ad088f887071c7;
// keccak256("freeze/unfreeze(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_TYPEHASH = 0x0101de85040f7616ce3d91b0b3b5279925bff5ba3cbdc18c318483eec213aba5;
// keccak256("freezeBulk/unfreezeBulk(address[] calldata target, bytes[] memory signatures)")
bytes32 constant FREEZE_BULK_TYPEHASH = 0xfbe23759ad6142178865544766ded4220dd6951de831ca9f926f385026c83a2b;
// keccak256("burnFrozenTokens(address target, bytes[] memory signatures)")
bytes32 constant BURN_FROZEN_TYPEHASH = 0x642bcc36d46a724c301cb6a1e74f954db2da04e41cf92613260aa926b0cc663c;
// keccak256("freezeAndBurnTokens(address target, bytes[] memory signatures)")
bytes32 constant FREEZE_AND_BURN_TYPEHASH = 0xb17ffba690b680e166aba321cd5d08ac8256fa93afb6a8f0573d02ecbfa33e11;
// keccak256("pause/unpause(bytes[] memory signatures)")
bytes32 constant PAUSE_TYPEHASH = 0x4f10db4bd06c1a9ea1a64e78bc5c096dc4b14436b0cdf60a6252f82113e0a57e;
uint public nonce = 0;
event SignedBy(address signer);
constructor (string memory name_, string memory symbol_, uint256 cap_, address[] memory allowedSigners)
ERC20Capped(cap_)
ERC20(name_, symbol_)
AccessControl(allowedSigners) {}
/**
* @dev Mint some tokens to target account
* MultiSig check is used - verifies that contract signers approve minting.
* During minting applied check for the max token cap.
*/
function mint(address target, uint256 amount, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(MINT_TYPEHASH, target, amount).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_mint(target, amount);
}
/**
* @dev Bulk operation to mint tokens to target accounts. There is a check for the cap inside.
*/
function mintBulk(address[] calldata target, uint256[] calldata amount, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
require(target.length == amount.length, "GovernanceToken: target.length != amount.length");
bytes32 operationHash = getOperationHash(MINT_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_mint(target[i], amount[i]);
}
}
/**
* @dev Mark target account as frozen. Frozen accounts can't perform transfers.
*/
function freeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
}
/**
* @dev Mark target account as unfrozen.
*/
function unfreeze(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unfreeze(target);
}
function freezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_freeze(target[i]);
}
}
function unfreezeBulk(address[] calldata target, bytes[] memory signatures) external onlySigner {
require(target.length > 1, "GovernanceToken: cannot perform bulk with single target");
bytes32 operationHash = getOperationHash(FREEZE_BULK_TYPEHASH, target[0], target.length).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
for (uint i = 0; i < target.length; i++) {
_unfreeze(target[i]);
}
}
/**
* @dev Burn tokens on frozen account.
*/
function burnFrozenTokens(address target, bytes[] memory signatures) external onlySigner {
require(isFrozen(target), "GovernanceToken: target account is not frozen");
bytes32 operationHash = getOperationHash(BURN_FROZEN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_burn(target, balanceOf(target));
}
/**
* @dev Freeze and burn tokens in a single transaction.
*/
function freezeAndBurnTokens(address target, bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(FREEZE_AND_BURN_TYPEHASH, target, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_freeze(target);
_burn(target, balanceOf(target));
}
/**
* @dev Triggers stopped state.
* - The contract must not be paused and pause should be allowed.
*/
function pause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_pause();
}
/**
* @dev Returns to normal state.
* - The contract must be paused.
*/
function unpause(bytes[] memory signatures) external onlySigner {
bytes32 operationHash = getOperationHash(PAUSE_TYPEHASH, msg.sender, 1).toEthSignedMessageHash();
_verifySignatures(signatures, operationHash);
_unpause();
}
/**
* @dev Get operation hash for multisig operation
* Nonce used to ensure that signature used only once.
* Use unique typehash for each operation.
*/
function getOperationHash(bytes32 typehash, address target, uint256 value) public view returns (bytes32) {
return keccak256(abi.encodePacked(address(this), typehash, target, value, nonce));
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - do not allow the transfer of funds to the token contract itself. Usually such a call is a mistake.
* - do not allow transfers when contract is paused.
* - only allow to burn frozen tokens.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(to != address(this), "GovernanceToken: can't transfer to token contract self");
require(!paused(), "GovernanceToken: token transfer while paused");
require(!isFrozen(from) || to == address(0x0), "GovernanceToken: source address was frozen");
}
/**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/
function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
} | /**
* Governance Token contract includes multisig protected actions.
* It includes:
* - minting methods
* - freeze methods
* - pause methods
*
* For each call must be provided valid signatures from contract signers (defined in AccessControl)
* and the transaction itself must be sent from the signer address.
* Every succeeded transaction will contain signer addresses for action proof in logs.
*
* It is possible to pause contract transfers in case an exchange is hacked and there is a risk for token holders to lose
* their tokens, delegated to an exchange. After freezing suspicious accounts the contract can be unpaused.
* Board members can burn tokens on frozen accounts to mint new tokens to holders as a recovery after a hacking attack.
*/ | NatSpecMultiLine | _verifySignatures | function _verifySignatures(bytes[] memory signatures, bytes32 operationHash) internal {
require(signatures.length >= 2, "AccessControl: not enough confirmations");
address[] memory recovered = new address[](signatures.length + 1);
recovered[0] = msg.sender;
emit SignedBy(msg.sender);
for (uint i = 0; i < signatures.length; i++) {
address addr = operationHash.recover(signatures[i]);
require(isSigner(addr), "AccessControl: recovered address is not signer");
for (uint j = 0; j < recovered.length; j++) {
require(recovered[j] != addr, "AccessControl: signer address used more than once");
}
recovered[i + 1] = addr;
emit SignedBy(addr);
}
require(recovered.length >= 3, "AccessControl: not enough confirmations");
nonce++;
}
| /**
* @dev Verify provided signatures according to the operation hash
* Ensure that each signature belongs to contract known signer and is unique
*/ | NatSpecMultiLine | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
7712,
8626
]
} | 1,151 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | BCUG | contract BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | /**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | withdrawTokenFromBalance | function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
| // @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract. | LineComment | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
300,
549
]
} | 1,152 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | BCUG | contract BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | /**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | approveAndCall | function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
| // ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------ | LineComment | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1004,
1303
]
} | 1,153 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | BCUG | contract BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | /**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transferBulk | function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
| // ---------------------------- ERC20 Bulk Operations ---------------------------- | LineComment | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
1396,
1708
]
} | 1,154 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | BCUG | contract BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | /**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transfer | function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
| // Function that is called when a user or another contract wants to transfer funds . | LineComment | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2303,
2477
]
} | 1,155 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | BCUG | contract BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | /**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transferToContract | function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
| // function that is called when transaction target is a contract | LineComment | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
2860,
3216
]
} | 1,156 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | BCUG | contract BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | /**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | _isContract | function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
| // assemble the given address bytecode. If bytecode exists then the _addr is a contract. | LineComment | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3313,
3605
]
} | 1,157 |
BCUG | BCUG.sol | 0x14da7b27b2e0fedefe0a664118b0c9bc68e2e9af | Solidity | BCUG | contract BCUG is GovernanceToken {
constructor (address[] memory allowedSigners) GovernanceToken("Blockchain Cuties Universe Governance Token", "BCUG", 10000000 ether, allowedSigners) {}
// @dev Transfers to _withdrawToAddress all tokens controlled by
// contract _tokenContract.
function withdrawTokenFromBalance(IERC20 _tokenContract, address _withdrawToAddress) external onlySigner {
uint256 balance = _tokenContract.balanceOf(address(this));
_tokenContract.transfer(_withdrawToAddress, balance);
}
// ---------------------------- ERC827 approveAndCall ----------------------------
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes calldata data) external override returns (bool success) {
_approve(msg.sender, spender, tokens);
TokenRecipientInterface(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ---------------------------- ERC20 Bulk Operations ----------------------------
function transferBulk(address[] calldata to, uint[] calldata tokens) external override {
require(to.length == tokens.length, "transferBulk: to.length != tokens.length");
for (uint i = 0; i < to.length; i++)
{
_transfer(msg.sender, to[i], tokens[i]);
}
}
function approveBulk(address[] calldata spender, uint[] calldata tokens) external override {
require(spender.length == tokens.length, "approveBulk: spender.length != tokens.length");
for (uint i = 0; i < spender.length; i++)
{
_approve(msg.sender, spender[i], tokens[i]);
}
}
// ---------------------------- ERC223 ----------------------------
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes calldata _data) external override returns (bool success) {
return transferWithData(_to, _value, _data);
}
function transferWithData(address _to, uint _value, bytes calldata _data) public returns (bool success) {
if (_isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value, _data);
TokenFallback receiver = TokenFallback(_to);
receiver.tokenFallback(msg.sender, _value, _data);
return true;
}
// assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return length > 0;
}
// function that is called when transaction target is an address
function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
} | /**
* @title Blockchain Cuties Universe fungible token base contract
* @dev Implementation of the {IERC20}, {IERC827} and {IERC223} interfaces.
* Token holders can burn their tokens.
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | transferToAddress | function transferToAddress(address _to, uint tokens, bytes calldata _data) public returns (bool success) {
_transfer(msg.sender, _to, tokens);
emit Transfer(msg.sender, _to, tokens, _data);
return true;
}
| // function that is called when transaction target is an address | LineComment | v0.8.1+commit.df193b15 | MIT | ipfs://b5a9bf50d6ab20fb6187e0977c4859ef104592e8af65af586f892117edccd45a | {
"func_code_index": [
3678,
3919
]
} | 1,158 |
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | initialize | function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
| /**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
965,
1291
]
} | 1,159 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | archToken | function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
| /**
* @notice Address of ARCH token
* @return Address of ARCH token
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
1383,
1550
]
} | 1,160 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | vestingContract | function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
| /**
* @notice Address of vesting contract
* @return Address of vesting contract
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
1654,
1825
]
} | 1,161 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | stakeWithPermit | function stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
| /**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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.4+commit.3f05b770 | MIT | {
"func_code_index": [
2179,
2696
]
} | 1,162 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | stake | function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
| /**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
2828,
3309
]
} | 1,163 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | addVotingPowerForVestingTokens | function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
| /**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
3509,
3897
]
} | 1,164 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | removeVotingPowerForClaimedTokens | function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
| /**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
4107,
4507
]
} | 1,165 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | withdraw | function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
| /**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
4652,
4920
]
} | 1,166 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | getARCHAmountStaked | function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
| /**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
5103,
5233
]
} | 1,167 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | getAmountStaked | function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
| /**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
5451,
5607
]
} | 1,168 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | getARCHStake | function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
| /**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
5803,
6010
]
} | 1,169 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | getStake | function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
| /**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
6254,
6471
]
} | 1,170 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
| /**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
6661,
6962
]
} | 1,171 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | balanceOfAt | function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
| /**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
7380,
8673
]
} | 1,172 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | _stake | function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
| /**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
8960,
9516
]
} | 1,173 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | _withdraw | function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
| /**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
9811,
10588
]
} | 1,174 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | _increaseVotingPower | function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
| /**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
10779,
11242
]
} | 1,175 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | _decreaseVotingPower | function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
| /**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
11433,
11896
]
} | 1,176 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | _writeCheckpoint | function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
| /**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
12246,
12932
]
} | 1,177 |
|
VotingPower | contracts/VotingPower.sol | 0xd07d77eab98f32f672de1f5b6a6aa824582e74cd | Solidity | VotingPower | contract VotingPower is PrismProxyImplementation, ReentrancyGuardUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @notice An event that's emitted when a user's staked balance increases
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when an account's vote balance changes
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
/**
* @notice Initialize VotingPower contract
* @dev Should be called via VotingPowerPrism before calling anything else
* @param _archToken address of ARCH token
* @param _vestingContract address of Vesting contract
*/
function initialize(
address _archToken,
address _vestingContract
) public initializer {
__ReentrancyGuard_init_unchained();
AppStorage storage app = VotingPowerStorage.appStorage();
app.archToken = IArchToken(_archToken);
app.vesting = IVesting(_vestingContract);
}
/**
* @notice Address of ARCH token
* @return Address of ARCH token
*/
function archToken() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.archToken);
}
/**
* @notice Address of vesting contract
* @return Address of vesting contract
*/
function vestingContract() public view returns (address) {
AppStorage storage app = VotingPowerStorage.appStorage();
return address(app.vesting);
}
/**
* @notice Stake ARCH tokens using offchain approvals to unlock voting power
* @param amount The amount to stake
* @param deadline 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 stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
require(amount > 0, "VP::stakeWithPermit: cannot stake 0");
AppStorage storage app = VotingPowerStorage.appStorage();
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stakeWithPermit: not enough tokens");
app.archToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Stake ARCH tokens to unlock voting power for `msg.sender`
* @param amount The amount to stake
*/
function stake(uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::stake: cannot stake 0");
require(app.archToken.balanceOf(msg.sender) >= amount, "VP::stake: not enough tokens");
require(app.archToken.allowance(msg.sender, address(this)) >= amount, "VP::stake: must approve tokens before staking");
_stake(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Count vesting ARCH tokens toward voting power for `account`
* @param account The recipient of voting power
* @param amount The amount of voting power to add
*/
function addVotingPowerForVestingTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::addVPforVT: cannot add 0 voting power");
require(msg.sender == address(app.vesting), "VP::addVPforVT: only vesting contract");
_increaseVotingPower(account, amount);
}
/**
* @notice Remove claimed vesting ARCH tokens from voting power for `account`
* @param account The account with voting power
* @param amount The amount of voting power to remove
*/
function removeVotingPowerForClaimedTokens(address account, uint256 amount) external nonReentrant {
AppStorage storage app = VotingPowerStorage.appStorage();
require(amount > 0, "VP::removeVPforVT: cannot remove 0 voting power");
require(msg.sender == address(app.vesting), "VP::removeVPforVT: only vesting contract");
_decreaseVotingPower(account, amount);
}
/**
* @notice Withdraw staked ARCH tokens, removing voting power for `msg.sender`
* @param amount The amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "VP::withdraw: cannot withdraw 0");
AppStorage storage app = VotingPowerStorage.appStorage();
_withdraw(msg.sender, address(app.archToken), amount, amount);
}
/**
* @notice Get total amount of ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH amount staked
*/
function getARCHAmountStaked(address staker) public view returns (uint256) {
return getARCHStake(staker).amount;
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) public view returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get staked amount and voting power from ARCH tokens staked in contract by `staker`
* @param staker The user with staked ARCH
* @return total ARCH staked
*/
function getARCHStake(address staker) public view returns (Stake memory) {
AppStorage storage app = VotingPowerStorage.appStorage();
return getStake(staker, address(app.archToken));
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view returns (Stake memory) {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
return ss.stakes[staker][stakedToken];
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function balanceOf(address account) public view returns (uint256) {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
return nCheckpoints > 0 ? cs.checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function balanceOfAt(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "VP::balanceOfAt: not yet determined");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 nCheckpoints = cs.numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (cs.checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return cs.checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (cs.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 = cs.checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return cs.checkpoints[account][lower].votes;
}
/**
* @notice Internal implementation of stake
* @param voter The user that is staking tokens
* @param token The token to stake
* @param tokenAmount The amount of token to stake
* @param votingPower The amount of voting power stake translates into
*/
function _stake(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
IERC20(token).safeTransferFrom(voter, address(this), tokenAmount);
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.add(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.add(votingPower);
emit Staked(voter, token, tokenAmount, votingPower);
_increaseVotingPower(voter, votingPower);
}
/**
* @notice Internal implementation of withdraw
* @param voter The user with tokens staked
* @param token The token that is staked
* @param tokenAmount The amount of token to withdraw
* @param votingPower The amount of voting power stake translates into
*/
function _withdraw(address voter, address token, uint256 tokenAmount, uint256 votingPower) internal {
StakeStorage storage ss = VotingPowerStorage.stakeStorage();
require(ss.stakes[voter][token].amount >= tokenAmount, "VP::_withdraw: not enough tokens staked");
require(ss.stakes[voter][token].votingPower >= votingPower, "VP::_withdraw: not enough voting power");
ss.stakes[voter][token].amount = ss.stakes[voter][token].amount.sub(tokenAmount);
ss.stakes[voter][token].votingPower = ss.stakes[voter][token].votingPower.sub(votingPower);
IERC20(token).safeTransfer(voter, tokenAmount);
emit Withdrawn(voter, token, tokenAmount, votingPower);
_decreaseVotingPower(voter, votingPower);
}
/**
* @notice Increase voting power of voter
* @param voter The voter whose voting power is increasing
* @param amount The amount of voting power to increase by
*/
function _increaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.add(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Decrease voting power of voter
* @param voter The voter whose voting power is decreasing
* @param amount The amount of voting power to decrease by
*/
function _decreaseVotingPower(address voter, uint256 amount) internal {
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
uint32 checkpointNum = cs.numCheckpoints[voter];
uint256 votingPowerOld = checkpointNum > 0 ? cs.checkpoints[voter][checkpointNum - 1].votes : 0;
uint256 votingPowerNew = votingPowerOld.sub(amount);
_writeCheckpoint(voter, checkpointNum, votingPowerOld, votingPowerNew);
}
/**
* @notice Create checkpoint of voting power for voter at current block number
* @param voter The voter whose voting power is changing
* @param nCheckpoints The current checkpoint number for voter
* @param oldVotes The previous voting power of this voter
* @param newVotes The new voting power of this voter
*/
function _writeCheckpoint(address voter, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = _safe32(block.number, "VP::_writeCheckpoint: block number exceeds 32 bits");
CheckpointStorage storage cs = VotingPowerStorage.checkpointStorage();
if (nCheckpoints > 0 && cs.checkpoints[voter][nCheckpoints - 1].fromBlock == blockNumber) {
cs.checkpoints[voter][nCheckpoints - 1].votes = newVotes;
} else {
cs.checkpoints[voter][nCheckpoints] = Checkpoint(blockNumber, newVotes);
cs.numCheckpoints[voter] = nCheckpoints + 1;
}
emit VotingPowerChanged(voter, oldVotes, newVotes);
}
/**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/
function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
} | /**
* @title VotingPower
* @dev Implementation contract for voting power prism proxy
* Calls should not be made directly to this contract, instead make calls to the VotingPowerPrism proxy contract
* The exception to this is the `become` function specified in PrismProxyImplementation
* This function is called once and is used by this contract to accept its role as the implementation for the prism proxy
*/ | NatSpecMultiLine | _safe32 | function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
| /**
* @notice Converts uint256 to uint32 safely
* @param n Number
* @param errorMessage Error message to use if number cannot be converted
* @return uint32 number
*/ | NatSpecMultiLine | v0.7.4+commit.3f05b770 | MIT | {
"func_code_index": [
13129,
13295
]
} | 1,178 |
|
PBCToken | PBCToken.sol | 0x18377e3bad04f08e887540faa15a9850bdfdc66c | Solidity | ERC20Basic | contract ERC20Basic {
// events
event Transfer(address indexed from, address indexed to, uint256 value);
// public functions
function totalSupply() public view returns (uint256);
function balanceOf(address addr) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
} | totalSupply | function totalSupply() public view returns (uint256);
| // public functions | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://e80b1b77d08c1490df6158cf0210faf696e94fd060102ebcafd41c9dd8fdbc69 | {
"func_code_index": [
137,
193
]
} | 1,179 |
||
PBCToken | PBCToken.sol | 0x18377e3bad04f08e887540faa15a9850bdfdc66c | Solidity | ERC20 | contract ERC20 is ERC20Basic {
// events
event Approval(address indexed owner, address indexed agent, uint256 value);
// public functions
function allowance(address owner, address agent) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address agent, uint256 value) public returns (bool);
} | allowance | function allowance(address owner, address agent) public view returns (uint256);
| // public functions | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://e80b1b77d08c1490df6158cf0210faf696e94fd060102ebcafd41c9dd8fdbc69 | {
"func_code_index": [
150,
232
]
} | 1,180 |
||
PBCToken | PBCToken.sol | 0x18377e3bad04f08e887540faa15a9850bdfdc66c | Solidity | Freezeable | contract Freezeable is Freezer {
// public variables
// internal variables
mapping(address => bool) _freezeList;
// events
event Freezed(address indexed freezedAddr);
event UnFreezed(address indexed unfreezedAddr);
// public functions
function freeze(address addr) public onlyFreezer returns (bool) {
require(true != _freezeList[addr]);
_freezeList[addr] = true;
emit Freezed(addr);
return true;
}
function unfreeze(address addr) public onlyFreezer returns (bool) {
require(true == _freezeList[addr]);
_freezeList[addr] = false;
emit UnFreezed(addr);
return true;
}
modifier whenNotFreezed() {
require(true != _freezeList[msg.sender]);
_;
}
function isFreezed(address addr) public view returns (bool) {
if (true == _freezeList[addr]) {
return true;
} else {
return false;
}
}
// internal functions
} | freeze | function freeze(address addr) public onlyFreezer returns (bool) {
require(true != _freezeList[addr]);
_freezeList[addr] = true;
emit Freezed(addr);
return true;
}
| // public functions | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://e80b1b77d08c1490df6158cf0210faf696e94fd060102ebcafd41c9dd8fdbc69 | {
"func_code_index": [
263,
455
]
} | 1,181 |
||
PBCToken | PBCToken.sol | 0x18377e3bad04f08e887540faa15a9850bdfdc66c | Solidity | BasicToken | contract BasicToken is ERC20Basic {
using SafeMath for uint256;
// public variables
string public name;
string public symbol;
uint8 public decimals = 18;
// internal variables
uint256 _totalSupply;
mapping(address => uint256) _balances;
// events
// public functions
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address addr) public view returns (uint256 balance) {
return _balances[addr];
}
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;
}
} | totalSupply | function totalSupply() public view returns (uint256) {
return _totalSupply;
}
| // events
// public functions | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://e80b1b77d08c1490df6158cf0210faf696e94fd060102ebcafd41c9dd8fdbc69 | {
"func_code_index": [
306,
394
]
} | 1,182 |
||
PBCToken | PBCToken.sol | 0x18377e3bad04f08e887540faa15a9850bdfdc66c | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
// public variables
// internal variables
mapping (address => mapping (address => uint256)) _allowances;
// events
// public functions
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowances[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function approve(address agent, uint256 value) public returns (bool) {
_allowances[msg.sender][agent] = value;
emit Approval(msg.sender, agent, value);
return true;
}
function allowance(address owner, address agent) public view returns (uint256) {
return _allowances[owner][agent];
}
function increaseApproval(address agent, uint value) public returns (bool) {
_allowances[msg.sender][agent] = _allowances[msg.sender][agent].add(value);
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
function decreaseApproval(address agent, uint value) public returns (bool) {
uint allowanceValue = _allowances[msg.sender][agent];
if (value > allowanceValue) {
_allowances[msg.sender][agent] = 0;
} else {
_allowances[msg.sender][agent] = allowanceValue.sub(value);
}
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
// internal functions
} | transferFrom | function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowances[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
| // events
// public functions | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://e80b1b77d08c1490df6158cf0210faf696e94fd060102ebcafd41c9dd8fdbc69 | {
"func_code_index": [
203,
657
]
} | 1,183 |
||
PBCToken | PBCToken.sol | 0x18377e3bad04f08e887540faa15a9850bdfdc66c | Solidity | FreezeableToken | contract FreezeableToken is StandardToken, Freezeable, Ownable {
// public variables
// internal variables
// events
// public functions
function transfer(address to, uint256 value) public whenNotFreezed returns (bool) {
require(true != _freezeList[to]);
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(true != _freezeList[from]);
require(true != _freezeList[to]);
return super.transferFrom(from, to, value);
}
function approve(address agent, uint256 value) public whenNotFreezed returns (bool) {
require(true != _freezeList[agent]);
return super.approve(agent, value);
}
function increaseApproval(address agent, uint value) public whenNotFreezed returns (bool success) {
require(true != _freezeList[agent]);
return super.increaseApproval(agent, value);
}
function decreaseApproval(address agent, uint value) public whenNotFreezed returns (bool success) {
require(true != _freezeList[agent]);
return super.decreaseApproval(agent, value);
}
// internal functions
} | transfer | function transfer(address to, uint256 value) public whenNotFreezed returns (bool) {
require(true != _freezeList[to]);
return super.transfer(to, value);
}
| // public variables
// internal variables
// events
// public functions | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://e80b1b77d08c1490df6158cf0210faf696e94fd060102ebcafd41c9dd8fdbc69 | {
"func_code_index": [
156,
325
]
} | 1,184 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | withdraw | function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
| /**
* Payout
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
2399,
2548
]
} | 1,185 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | paused | function paused() external view returns (bool) {
return _paused;
}
| /**
* Pausing
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
2821,
2895
]
} | 1,186 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | getOracle | function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
| /**
* Updating Oracle
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
3008,
3119
]
} | 1,187 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | getGenerativeMinted | function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
| /**
* Methods for Web3
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
3312,
3421
]
} | 1,188 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | mintTrunk | function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
| /**
* Generative minting
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
3669,
5122
]
} | 1,189 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | mintGenesisTrunk | function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
| /**
* Genesis minting
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
6896,
7497
]
} | 1,190 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | fetchGenesisSeedFromVRF | function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
| // Required to be called before first mint to populate genesisRandomSeed. | LineComment | v0.6.6+commit.6c089d02 | {
"func_code_index": [
8190,
8274
]
} | 1,191 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | getRandomGenesisTrunk | function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
| // "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n. | LineComment | v0.6.6+commit.6c089d02 | {
"func_code_index": [
8530,
8693
]
} | 1,192 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | setBaseURI | function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
| // Updates | LineComment | v0.6.6+commit.6c089d02 | {
"func_code_index": [
8708,
8900
]
} | 1,193 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | remoteMint | function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
| // Regular | LineComment | v0.6.6+commit.6c089d02 | {
"func_code_index": [
8951,
9559
]
} | 1,194 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | remoteMintTwenty | function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
| // Minting 20 ("Gamble") | LineComment | v0.6.6+commit.6c089d02 | {
"func_code_index": [
10649,
11215
]
} | 1,195 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | getRandomNumber | function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
| /**
* Chainlink VRF
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
11806,
12022
]
} | 1,196 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | toString | function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
| /**
* Utils
*/ | NatSpecMultiLine | v0.6.6+commit.6c089d02 | {
"func_code_index": [
12184,
12311
]
} | 1,197 |
||
CryptoTrunks | contracts/CryptoTrunks.sol | 0x375ea781c49eafedde07afe6196f885761f166ae | Solidity | CryptoTrunks | contract CryptoTrunks is ERC721, Ownable, ChainlinkClient, VRFConsumerBase {
using Counters for Counters.Counter;
// Pausable.
bool private _paused;
// Represents a minting user, for lookup from Chainlink fulfill.
struct User {
uint256 tokenId;
address addr;
}
// Generative
uint16 constant private generativeSupply = 19500;
Counters.Counter private generativeMinted;
// Genesis
uint16 constant private genesisSupply = 1500;
Counters.Counter private genesisMinted;
uint256 constant private genesisPrime = 22801763477; // Prime chosen at random (10 millionth)
// Chainlink internals.
address private oracle;
bytes32 private jobId;
uint256 private fee;
// Chainlink VRF constants.
bytes32 internal keyHash;
uint256 internal vrfFee;
// Returned from VRF.
uint256 private genesisRandomSeed;
// Mapping from Chainlink `requestId` to the user who triggered it.
mapping (bytes32 => User) private users;
// Mapping from address to the fee the user will pay next.
mapping (address => uint256) private nextFeeTiers;
// Mapping from address to minted count.
mapping (address => uint16) private mintedCount;
// Events
event RemoteMintFulfilled(bytes32 requestId, uint256 tokenId, uint256 resultId);
event RemoteMintTwentyFulfilled(bytes32 requestId, uint256 firstTokenId, uint256 resultId);
/**
* Constructor
*/
// TODO: Change VRFConsumerBase to mainnet .
constructor() public
ERC721("CryptoTrunks", "CT")
VRFConsumerBase(
0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, // VRF Coordinator
0x514910771AF9Ca656af840dff83E8264EcF986CA // LINK Token
)
{
// Metadata setup.
_setBaseURI("https://service.cryptotrunks.co/token/");
// Chainlink setup.
setPublicChainlinkToken();
// Our node
// oracle = 0xDAca12D022D5fe11c857d6f583Bb43D01a8f5B73;
// jobId = "d562d13f83a947d4bb720be4a2682978";
// fee = 1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// Kovan
// oracle = 0xAA1DC356dc4B18f30C347798FD5379F3D77ABC5b;
// jobId = "c7dd72ca14b44f0c9b6cfcd4b7ec0a2c";
// fee = 0.1 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
// VRF setup.
// Kovan network.
// TODO: Change this to mainnet
keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
vrfFee = 2 * 10 ** 18; // 1 * 10 ** 18 = 1 Link
}
/**
* Payout
*/
function withdraw() external onlyOwner {
address payable payableOwner = payable(owner());
payableOwner.transfer(address(this).balance);
}
function withdrawLink() external onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
address payable payableOwner = payable(owner());
link.transfer(payableOwner, link.balanceOf(address(this)));
}
/**
* Pausing
*/
function paused() external view returns (bool) {
return _paused;
}
function togglePaused() external onlyOwner {
_paused = !_paused;
}
/**
* Updating Oracle
*/
function getOracle() external view returns (address, bytes32, uint256) {
return (oracle, jobId, fee);
}
function updateOracle(address _oracle, bytes32 _jobId, uint256 _fee) external onlyOwner {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
/**
* Methods for Web3
*/
function getGenerativeMinted() external view returns (uint256) {
return generativeMinted.current();
}
function getGenesisMinted() external view returns (uint256) {
return genesisMinted.current();
}
function getGenesisRandomSeed() external view returns (uint256) {
return genesisRandomSeed;
}
/**
* Generative minting
*/
function mintTrunk(uint256 randomSeed, bool isBasic) external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= getBaseFeeTier());
require(msg.value >= getFeeTier());
// In pause, prevent "free" mints.
if (_paused) {
require(msg.value >= (0.05 ether));
}
// Update minted count.
mintedCount[msg.sender] = (mintedCount[msg.sender] + 1);
// Limit supply.
require(generativeMinted.current() < generativeSupply); // 0 ..< 19,500
generativeMinted.increment(); // Start at 1 (tokens 1 ..< 19,501)
// Get current token, starting after the last genesis trunk (i.e. 1,501).
uint256 _tokenId = genesisSupply + generativeMinted.current(); // 1,501 ..< 21,001
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// In order to save Link for the most basic combination (Sapling + Noon),
// we skip remoteMint, since no-one would fake the most basic level.
if (isBasic) {
// Skip oracle step for basic trunks.
// Since we aren't storing this with the oracle, set the seed as the token URI.
completeMint(0x00, _tokenId, randomSeed);
} else {
// Generate art on remote URL.
bytes32 requestId = remoteMint(randomSeed, _tokenId);
// Store token to mapping for when request completes.
users[requestId] = User(_tokenId, msg.sender);
}
// Returned so web3 can filter on it.
return _tokenId;
}
function mintTwentyTrunks() external payable returns (uint256 tokenId) {
// Enforce tiered fees.
require(msg.value >= 1 ether);
// Limit supply.
require(generativeMinted.current() + 20 <= generativeSupply);
// First token ID, one more than current.
uint256 firstTokenId = genesisSupply + generativeMinted.current() + 1;
for (uint8 i = 0; i < 20; i++) {
// Mint token itself.
generativeMinted.increment();
_safeMint(msg.sender, (genesisSupply + generativeMinted.current()));
}
// Generate art (x20) on remote URL.
bytes32 requestId = remoteMintTwenty(firstTokenId);
// Store token to mapping for when request completes.
users[requestId] = User(firstTokenId, msg.sender);
// Returned so web3 can filter on it.
return firstTokenId;
}
function getFeeTier() public view returns (uint256 feeTier) {
// Fee tier generated from value returned from our service.
uint256 nextFeeTier = nextFeeTiers[msg.sender];
if (nextFeeTier == 0) {
return 0;
} else {
return nextFeeTier;
}
}
function getBaseFeeTier() public view returns (uint256 baseFeeTier) {
// Fallback check to guard the base price.
uint16 minted = mintedCount[msg.sender];
if (minted == 0) {
return 0;
} else {
// Multiplier is divided by 10 at the end to avoid floating point.
uint256 multiplier = 10;
if (minted < 5) {
multiplier = 10;
} else if (minted < 20) {
multiplier = 15;
} else if (minted < 50) {
multiplier = 20;
} else if (minted < 100) {
multiplier = 25;
} else {
multiplier = 30;
}
return ((0.05 ether) * multiplier) / 10;
}
}
/**
* Genesis minting
*/
function mintGenesisTrunk(uint256 numberToMint) external payable returns (uint256[] memory tokenIds) {
// Minting constraints.
require(numberToMint >= 1);
require(numberToMint <= 20);
require(numberToMint <= (genesisSupply - genesisMinted.current()));
// Ensure we collect enough eth!
require(msg.value >= (0.5 ether) * numberToMint);
// Loop minting.
uint256[] memory _tokenIds = new uint256[](numberToMint);
for (uint256 i = 0; i < numberToMint; i++) {
uint256 tokenId = mintGenesisTrunk();
_tokenIds[i] = tokenId;
}
return _tokenIds;
}
function mintGenesisTrunk() private returns (uint256 tokenId) {
// Limit supply.
require(genesisMinted.current() < genesisSupply); // 0 ..< 1,500
genesisMinted.increment(); // Start at 1 (tokens 1 ..< 1,501)
// Check we seeded the genesis random seed.
require(genesisRandomSeed != 0);
// Get current token.
// Turns 1 ..< 1,501 into a random (but unminted) number in that range.
uint256 _tokenId = getRandomGenesisTrunk(genesisMinted.current());
// Mint token itself.
_safeMint(msg.sender, _tokenId);
// Returned so web3 can filter on it.
return _tokenId;
}
// Required to be called before first mint to populate genesisRandomSeed.
function fetchGenesisSeedFromVRF() external onlyOwner {
getRandomNumber();
}
// "Shuffles" our list, from random seed, without using much storage, starting at 1.
// This works because (a x + b) modulo n visits all integers in 0..<n exactly once
// as x iterates through the integers in 0..<n, so long as a is coprime with n.
function getRandomGenesisTrunk(uint256 index) private view returns (uint256) {
return (((index * genesisPrime) + genesisRandomSeed) % genesisSupply) + 1;
}
// Updates
function setBaseURI(string calldata baseURI_) external onlyOwner {
// Allows us to update the baseURI after deploy, so we can move to IPFS if we choose to.
_setBaseURI(baseURI_);
}
/**
* Chainlink fetch
*/
// Regular
function remoteMint(uint256 randomSeed, uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint?address=", toString(msg.sender),
"&seed=", randomSeed.toString(),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfill(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// _resultId is made up of returned token id + next minting fee.
// e.g. if token = 1234 and fee = 0.15 ether, oracle returns 1234150.
// Inlined below to save space.
// uint256 returnedFeeTier = _resultId % 1000; // Get last digits.
// uint256 returnedTokenId = _resultId / 1000; // Get other digits.
// Store tree age for future mints.
nextFeeTiers[user.addr] = ((_resultId % 1000) * 1 ether) / 1000;
completeMint(_requestId, user.tokenId, (_resultId / 1000));
}
function completeMint(bytes32 _requestId, uint256 _tokenId, uint256 _returnedTokenId) private {
// Update our token URI in case it changed.
_setTokenURI(_tokenId, _returnedTokenId.toString());
// Emit event for Web3.
emit RemoteMintFulfilled(_requestId, _tokenId, _returnedTokenId);
}
// Minting 20 ("Gamble")
function remoteMintTwenty(uint256 tokenId) private returns (bytes32 requestId) {
// Make the Chainlink request.
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfillTwenty.selector);
string memory url = string(
abi.encodePacked(
"https://service.cryptotrunks.co/mint_twenty?address=", toString(msg.sender),
"&token=", tokenId.toString()
)
);
request.add("get", url);
request.add("path", "result"); // jsonpath.com
return sendChainlinkRequestTo(oracle, request, fee);
}
function fulfillTwenty(bytes32 _requestId, uint256 _resultId) public recordChainlinkFulfillment(_requestId) {
require(_resultId > 0);
// Retrieve user from mapping.
User memory user = users[_requestId];
require(user.addr != address(0));
// Gambling doesn't affect fee tier.
// Since we can't afford the gas, the service will assume token ID is the baseURI,
// i.e. we're not going make 20 _setTokenURI() calls here.
// Emit event for Web3.
emit RemoteMintTwentyFulfilled(_requestId, user.tokenId, _resultId);
}
/**
* Chainlink VRF
*/
function getRandomNumber() private returns (bytes32 requestId) {
// Only permit if this has never been run.
require(genesisRandomSeed == 0);
return requestRandomness(keyHash, vrfFee, block.number);
}
function fulfillRandomness(bytes32 /* requestId */, uint256 randomness) internal override {
genesisRandomSeed = randomness;
}
/**
* Utils
*/
function toString(address account) private pure returns (string memory) {
return toString(abi.encodePacked(account));
}
// https://ethereum.stackexchange.com/a/58341/68257
function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
} | // Remix
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/token/ERC721/ERC721.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/access/Ownable.sol";
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/utils/Counters.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.6/VRFConsumerBase.sol"; | LineComment | toString | function toString(bytes memory data) private pure returns (string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < data.length; i++) {
str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
| // https://ethereum.stackexchange.com/a/58341/68257 | LineComment | v0.6.6+commit.6c089d02 | {
"func_code_index": [
12367,
12780
]
} | 1,198 |
||
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | CriptaliaRewards | function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
| // ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
463,
757
]
} | 1,199 |
|
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | totalSupply | function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
| // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
945,
1066
]
} | 1,200 |
|
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | balanceOf | function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
| // ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
1286,
1415
]
} | 1,201 |
|
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transfer | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
1759,
2036
]
} | 1,202 |
|
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approve | function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
2544,
2752
]
} | 1,203 |
|
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transferFrom | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
3283,
3641
]
} | 1,204 |
|
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | allowance | function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| // ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
3924,
4080
]
} | 1,205 |
|
CriptaliaRewards | CriptaliaRewards.sol | 0x2c821a3ce3b5c0a471862eb63a2ef99a4d285d43 | Solidity | CriptaliaRewards | contract CriptaliaRewards is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function CriptaliaRewards() public {
symbol = "CRIPTRE";
name = "CRIPTALIA REWARDS";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
Transfer(address(0), msg.sender, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approveAndCall | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------ | LineComment | v0.4.19+commit.c4cbbb05 | bzzr://8aa82eb5fe2ca991432d5ab5fda049a82fadf2c17c6a727dbc5bb442ea49e4de | {
"func_code_index": [
4435,
4752
]
} | 1,206 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.