Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
10
// / /
function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params
function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params
16,320
1
// Moves OpenZeppelin's ECDSA implementation into a separate library to save/code size in the main contract.
library ECDSABridge { function recover(bytes32 hash, bytes memory signature) external pure returns (address) { return ECDSAUpgradeable.recover(hash, signature); } }
library ECDSABridge { function recover(bytes32 hash, bytes memory signature) external pure returns (address) { return ECDSAUpgradeable.recover(hash, signature); } }
31,931
24
// Connector Details/
function connectorID() public pure returns(uint _type, uint _id) { (_type, _id) = (1, 57); }
function connectorID() public pure returns(uint _type, uint _id) { (_type, _id) = (1, 57); }
36,855
176
// do not allow to drain core tokens
require(address(_token) != address(vape), "vape"); require(address(_token) != address(yugape), "yugape"); require(address(_token) != address(boardape), "boardape"); _token.safeTransfer(_to, _amount);
require(address(_token) != address(vape), "vape"); require(address(_token) != address(yugape), "yugape"); require(address(_token) != address(boardape), "boardape"); _token.safeTransfer(_to, _amount);
2,001
9
// 1. get source account
address fromAccount = _accountManager.getAccount(msg.sender);
address fromAccount = _accountManager.getAccount(msg.sender);
19,332
127
// Safe lv1 transfer function, just in case if rounding error causes pool to not have enough lv1s.
function safelv1Transfer(address _to, uint256 _amount) internal { uint256 lv1Bal = lv1.balanceOf(address(this)); if (_amount > lv1Bal) { lv1.transfer(_to, lv1Bal); } else { lv1.transfer(_to, _amount); } }
function safelv1Transfer(address _to, uint256 _amount) internal { uint256 lv1Bal = lv1.balanceOf(address(this)); if (_amount > lv1Bal) { lv1.transfer(_to, lv1Bal); } else { lv1.transfer(_to, _amount); } }
29,965
11
// in line assembly code
assembly { codeSize := extcodesize(_addr) }
assembly { codeSize := extcodesize(_addr) }
1,364
98
// Upgrade the implementation of the proxy.
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); }
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); }
24,763
657
// Adds liquidity for the given recipient/tickLower/tickUpper position/The caller of this method receives a callback in the form of IUniswapV3MintCallbackuniswapV3MintCallback/ in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends/ on tickLower, tickUpper, the amount of liquidity, and the current price./recipient The address for which the liquidity will be created/tickLower The lower tick of the position in which to add liquidity/tickUpper The upper tick of the position in which to add liquidity/amount The amount of liquidity to mint/data Any data that should be passed through to the callback/ return amount0 The amount
function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1);
function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1);
4,156
156
// 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) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); }
function setApprovalForAll(address operator, bool approved) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); }
36,375
17
// TODO(asa): Move to uint128 if gas savings are significant enough.
library FractionUtil { using SafeMath for uint256; using FractionUtil for Fraction; struct Fraction { uint256 numerator; uint256 denominator; } function reduce(Fraction memory x) internal pure returns (Fraction memory) { uint256 gcd = x.denominator; uint256 y = x.numerator; while (y != 0) { uint256 y_ = gcd % y; gcd = y; y = y_; } Fraction memory fraction = Fraction(x.numerator.div(gcd), x.denominator.div(gcd)); return fraction; } /** * @dev Returns whether or not at least one of numerator and denominator are non-zero. * @return Whether or not at least one of numerator and denominator are non-zero. */ function exists(Fraction memory x) internal pure returns (bool) { return x.numerator > 0 || x.denominator > 0; } /** * @dev Returns whether fraction "x" is equal to fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x == y */ function equals(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) == y.numerator.mul(x.denominator); } /** * @dev Returns a new fraction that is the sum of two rates. * @param x A Fraction struct. * @param y A Fraction struct. * @return x + y */ function add(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { return Fraction( x.numerator.mul(y.denominator).add(y.numerator.mul(x.denominator)), x.denominator.mul(y.denominator) ) .reduce(); } /** * @dev Returns a new fraction that is the two rates subtracted from each other. * @param x A Fraction struct. * @param y A Fraction struct. * @return x - y */ function sub(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { require(isGreaterThanOrEqualTo(x, y)); return Fraction( x.numerator.mul(y.denominator).sub(y.numerator.mul(x.denominator)), x.denominator.mul(y.denominator) ) .reduce(); } /** * @dev Returns a fraction that is the fraction times a fraction. * @param x A Fraction struct. * @param y A Fraction struct. * @return x * y */ function mul(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { return Fraction(x.numerator.mul(y.numerator), x.denominator.mul(y.denominator)).reduce(); } /** * @dev Returns an integer that is the fraction time an integer. * @param x A Fraction struct. * @param y An integer. * @return x * y */ function mul(Fraction memory x, uint256 y) internal pure returns (uint256) { return x.numerator.mul(y).div(x.denominator); } /** * @dev Returns the inverse of the fraction. * @param x A Fraction struct. * @return 1 / x */ function inverse(Fraction memory x) internal pure returns (Fraction memory) { require(x.numerator != 0); return Fraction(x.denominator, x.numerator); } /** * @dev Returns a fraction that is the fraction divided by a fraction. * @param x A Fraction struct. * @param y A Fraction struct. * @return x / y */ function div(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { require(y.numerator != 0); return Fraction(x.numerator.mul(y.denominator), x.denominator.mul(y.numerator)); } /** * @dev Returns whether fraction "x" is greater than fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x > y */ function isGreaterThan(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) > y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "x" is greater than or equal to fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x >= y */ function isGreaterThanOrEqualTo(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) >= y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "x" is less than fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x < y */ function isLessThan(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) < y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "x" is less than or equal to fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x <= y */ function isLessThanOrEqualTo(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) <= y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "z" is between fractions "x" and "y". * @param z A Fraction struct. * @param x A Fraction struct representing a rate lower than "y". * @param y A Fraction struct representing a rate higher than "x". * @return x <= z <= y */ function isBetween(Fraction memory z, Fraction memory x, Fraction memory y) internal pure returns (bool) { return isLessThanOrEqualTo(x, z) && isLessThanOrEqualTo(z, y); } }
library FractionUtil { using SafeMath for uint256; using FractionUtil for Fraction; struct Fraction { uint256 numerator; uint256 denominator; } function reduce(Fraction memory x) internal pure returns (Fraction memory) { uint256 gcd = x.denominator; uint256 y = x.numerator; while (y != 0) { uint256 y_ = gcd % y; gcd = y; y = y_; } Fraction memory fraction = Fraction(x.numerator.div(gcd), x.denominator.div(gcd)); return fraction; } /** * @dev Returns whether or not at least one of numerator and denominator are non-zero. * @return Whether or not at least one of numerator and denominator are non-zero. */ function exists(Fraction memory x) internal pure returns (bool) { return x.numerator > 0 || x.denominator > 0; } /** * @dev Returns whether fraction "x" is equal to fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x == y */ function equals(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) == y.numerator.mul(x.denominator); } /** * @dev Returns a new fraction that is the sum of two rates. * @param x A Fraction struct. * @param y A Fraction struct. * @return x + y */ function add(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { return Fraction( x.numerator.mul(y.denominator).add(y.numerator.mul(x.denominator)), x.denominator.mul(y.denominator) ) .reduce(); } /** * @dev Returns a new fraction that is the two rates subtracted from each other. * @param x A Fraction struct. * @param y A Fraction struct. * @return x - y */ function sub(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { require(isGreaterThanOrEqualTo(x, y)); return Fraction( x.numerator.mul(y.denominator).sub(y.numerator.mul(x.denominator)), x.denominator.mul(y.denominator) ) .reduce(); } /** * @dev Returns a fraction that is the fraction times a fraction. * @param x A Fraction struct. * @param y A Fraction struct. * @return x * y */ function mul(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { return Fraction(x.numerator.mul(y.numerator), x.denominator.mul(y.denominator)).reduce(); } /** * @dev Returns an integer that is the fraction time an integer. * @param x A Fraction struct. * @param y An integer. * @return x * y */ function mul(Fraction memory x, uint256 y) internal pure returns (uint256) { return x.numerator.mul(y).div(x.denominator); } /** * @dev Returns the inverse of the fraction. * @param x A Fraction struct. * @return 1 / x */ function inverse(Fraction memory x) internal pure returns (Fraction memory) { require(x.numerator != 0); return Fraction(x.denominator, x.numerator); } /** * @dev Returns a fraction that is the fraction divided by a fraction. * @param x A Fraction struct. * @param y A Fraction struct. * @return x / y */ function div(Fraction memory x, Fraction memory y) internal pure returns (Fraction memory) { require(y.numerator != 0); return Fraction(x.numerator.mul(y.denominator), x.denominator.mul(y.numerator)); } /** * @dev Returns whether fraction "x" is greater than fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x > y */ function isGreaterThan(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) > y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "x" is greater than or equal to fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x >= y */ function isGreaterThanOrEqualTo(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) >= y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "x" is less than fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x < y */ function isLessThan(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) < y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "x" is less than or equal to fraction "y". * @param x A Fraction struct. * @param y A Fraction struct. * @return x <= y */ function isLessThanOrEqualTo(Fraction memory x, Fraction memory y) internal pure returns (bool) { return x.numerator.mul(y.denominator) <= y.numerator.mul(x.denominator); } /** * @dev Returns whether fraction "z" is between fractions "x" and "y". * @param z A Fraction struct. * @param x A Fraction struct representing a rate lower than "y". * @param y A Fraction struct representing a rate higher than "x". * @return x <= z <= y */ function isBetween(Fraction memory z, Fraction memory x, Fraction memory y) internal pure returns (bool) { return isLessThanOrEqualTo(x, z) && isLessThanOrEqualTo(z, y); } }
41,817
36
// return Returns whether a factory is active or not /
function getFactoryStatus(address _factory) external view returns (bool) { return isFactoryActive[_factory]; }
function getFactoryStatus(address _factory) external view returns (bool) { return isFactoryActive[_factory]; }
8,214
48
// https:etherscan.io/address/0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076
ProxyERC20 public constant proxysaave_i = ProxyERC20(0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076);
ProxyERC20 public constant proxysaave_i = ProxyERC20(0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076);
12,561
18
// TODO: understand this (bool, something?) = payable(whoGetsPayed?).call{value: howMuchItGetsPayed}("")
(bool donationSent, ) = payable(campaign.owner).call{value: amount}("");
(bool donationSent, ) = payable(campaign.owner).call{value: amount}("");
19,643
159
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
17,327
123
// File: contracts\ERC721.sol/the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} }
* {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @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. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} }
22,065
7
// Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the riskthat someone may use both the old and the new allowance by unfortunatetransaction ordering. One possible solution to mitigate this racecondition is to first reduce the spender's allowance to 0 and set thedesired value afterwards:
* Emits an {Approval} event. */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
* Emits an {Approval} event. */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
12,091
515
// Calculate denominator for row 124: x - g^124z.
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x7e0))) mstore(add(productsPtr, 0x540), partialProduct) mstore(add(valuesPtr, 0x540), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x7e0))) mstore(add(productsPtr, 0x540), partialProduct) mstore(add(valuesPtr, 0x540), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME)
77,076
75
// Utils /
{ return block.number; }
{ return block.number; }
25,701
17
// Token info that is stored in the contact storage./maxAmount Maximum amount to deposit./minAmount Minimum amount to deposit, with fees included./dailyLimit Daily volume limit./consumedLimit Consumed daily volume limit./lastUpdated Last timestamp when the consumed limit was set to 0./Set max amount to zero to disable the token./Set daily limit to 0 to disable the daily limit. Consumed limit should/ always be less than equal to dailyLimit.
struct TokenInfoStore { uint256 maxAmount; uint256 minAmount; uint256 dailyLimit; uint256 consumedLimit; uint256 lastUpdated; }
struct TokenInfoStore { uint256 maxAmount; uint256 minAmount; uint256 dailyLimit; uint256 consumedLimit; uint256 lastUpdated; }
14,501
11
// Removes a user from our list of admins but keeps them in the history audit /
function removeAdmin(address _address) { /* Ensure we&#39;re an admin */ if (!isCurrentAdmin(msg.sender)) throw; /* Don&#39;t allow removal of self */ if (_address == msg.sender) throw; // Fail if this account is already non-admin if (!adminAddresses[_address]) throw; /* Remove this admin user */ adminAddresses[_address] = false; AdminRemoved(msg.sender, _address); }
function removeAdmin(address _address) { /* Ensure we&#39;re an admin */ if (!isCurrentAdmin(msg.sender)) throw; /* Don&#39;t allow removal of self */ if (_address == msg.sender) throw; // Fail if this account is already non-admin if (!adminAddresses[_address]) throw; /* Remove this admin user */ adminAddresses[_address] = false; AdminRemoved(msg.sender, _address); }
34,023
39
// Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This meansthat 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 guideto implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert insteadof returning `false` on failure. This behavior is nonetheless conventionaland 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 justby listening to said events. Other implementations of
contract SHIBASWAP is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0;
contract SHIBASWAP is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0;
13,844
120
// ERC20
if (token_address != DEFAULT_ADDRESS) transfer_token(token_address, address(this), msg.sender, withdraw_balance);
if (token_address != DEFAULT_ADDRESS) transfer_token(token_address, address(this), msg.sender, withdraw_balance);
4,951
9
// lets msg.sender accept governance /
function _acceptGov() external
function _acceptGov() external
1,821
28
// Check lottery not Closed and completed
require(lotteries[lottId].winner == address(0)); require(lotteries[lottId].ticketsSold.length == lotteries[lottId].numTickets);
require(lotteries[lottId].winner == address(0)); require(lotteries[lottId].ticketsSold.length == lotteries[lottId].numTickets);
47,411
2
// An event which is triggered when the owner is changed. previousOwner The address of the previous owner. newOwner The address of the new owner. /
event OwnershipTransferred( address indexed previousOwner, address indexed newOwner );
event OwnershipTransferred( address indexed previousOwner, address indexed newOwner );
28,671
22
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'CorgiSLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'CorgiSLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'CorgiSLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'CorgiSLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; }
6,659
44
// Event that signals that a trash bag has been generated (trash bag is thrown in the bin).
event ToPickUp(uint id, uint serialNumberBin, bool isRecyclable, uint weight, address generator);
event ToPickUp(uint id, uint serialNumberBin, bool isRecyclable, uint weight, address generator);
23,358
8
// Emitted when loss is incurred that can't be covered by treasury funds
event UncoveredLoss(address indexed creditManager, uint256 loss);
event UncoveredLoss(address indexed creditManager, uint256 loss);
20,302
95
// Enables tax globally. /
function enableTax() public onlyOwner { require(!taxStatus, "CoinToken: Tax is already enabled"); taxStatus = true; }
function enableTax() public onlyOwner { require(!taxStatus, "CoinToken: Tax is already enabled"); taxStatus = true; }
6,332
5
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address();
custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address();
48,001
60
// return The percentage fee that is paid when withdrawing Ether or Dai
function getFeePercent() external pure returns(uint) { return (conserveRateDigits - conserveRate)/100; }
function getFeePercent() external pure returns(uint) { return (conserveRateDigits - conserveRate)/100; }
33,343
48
// update storage variables and compute yield amount
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault); yieldAmount = _claimYield(vault, updatedPricePerVaultShare);
uint256 updatedPricePerVaultShare = getPricePerVaultShare(vault); yieldAmount = _claimYield(vault, updatedPricePerVaultShare);
3,998
21
// Returns boolean flag indicating whether given compartment implementation and token combination is whitelisted compartmentImpl Address of compartment implementation to check if it is allowed for token token Address of token to check if compartment implementation is allowedreturn isWhitelisted Boolean flag indicating whether compartment implementation is whitelisted for given token /
function isWhitelistedCompartment(
function isWhitelistedCompartment(
38,304
188
// If some amount is owed, pay it back NOTE: Since debt is based on deposits, it makes sense to guard against large changes to the value from triggering a harvest directly through user behavior. This should ensure reasonable resistance to manipulation from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true;
uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true;
22,388
18
// Using burnable module, avoid overminting.
function _safeMint( uint128 _quantity
function _safeMint( uint128 _quantity
31,313
98
// Gets the value of the asset Oracle = the oracle address in specific. Optional parameter Inverted pair = whether or not this call represents an inversion of typical type (ERC20 underlying, USDC compareTo) to (USDC underlying, ERC20 compareTo) Must take inverse of value in this case to get REAL value
function getValueOfAsset( address asset, address compareTo, bool risingEdge ) external view returns (uint);
function getValueOfAsset( address asset, address compareTo, bool risingEdge ) external view returns (uint);
6,836
493
// The token which will be minted as a reward for staking.
IMintableERC20 public reward;
IMintableERC20 public reward;
38,453
21
// Add or remove a module./Treat modules as you would Ladle upgrades. Modules have unrestricted access to the Ladle/ storage, and can wreak havoc easily./ Modules must not do any changes to any vault (owner, seriesId, ilkId) because of vault caching./ Modules must not be contracts that can self-destruct because of `moduleCall`./ Modules can't use `msg.value` because of `batch`.
function addModule(address module, bool set) external auth
function addModule(address module, bool set) external auth
44,125
2
// IoT的權限檢查
modifier onlyIoT(){ require(msg.sender == iot,"Only iot can call this function"); _; }
modifier onlyIoT(){ require(msg.sender == iot,"Only iot can call this function"); _; }
1,426
125
// Reverts if amount is not at least what was agreed upon in the service agreement _feePaid The payment for the request _keyHash The key which the request is for /
modifier sufficientLINK(uint256 _feePaid, bytes32 _keyHash) { require(_feePaid >= serviceAgreements[_keyHash].fee, "Below agreed payment"); _; }
modifier sufficientLINK(uint256 _feePaid, bytes32 _keyHash) { require(_feePaid >= serviceAgreements[_keyHash].fee, "Below agreed payment"); _; }
8,042
140
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { (residualCash, fCashAmount) = _deleverageMarket( nToken.cashGroup, market, perMarketDeposit, blockTime, marketIndex );
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) { (residualCash, fCashAmount) = _deleverageMarket( nToken.cashGroup, market, perMarketDeposit, blockTime, marketIndex );
3,442
229
// transfer marketplace owner commissions
IERC20(tradeToken).transferFrom(msg.sender, marketPlaceOwner, sellerFee);
IERC20(tradeToken).transferFrom(msg.sender, marketPlaceOwner, sellerFee);
24,836
68
// Make sure the grant has tokens available.
require(grant.value != 0);
require(grant.value != 0);
44,064
1,179
// Same as {at}, except this doesn't revert if `index` it outside of the map (i.e. if it is equal or largerthan {length}). O(1). This function performs one less storage read than {at}, but should only be used when `index` is known to bewithin bounds. /
function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { IERC20ToBytes32MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); }
function unchecked_at(IERC20ToBytes32Map storage map, uint256 index) internal view returns (IERC20, bytes32) { IERC20ToBytes32MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); }
56,742
12
// storage layout is copied from PermittableToken.sol
string internal name; string internal symbol; uint8 internal decimals; mapping(address => uint256) internal balances; uint256 internal totalSupply; mapping(address => mapping(address => uint256)) internal allowed; address internal owner; bool internal mintingFinished; address internal bridgeContractAddr;
string internal name; string internal symbol; uint8 internal decimals; mapping(address => uint256) internal balances; uint256 internal totalSupply; mapping(address => mapping(address => uint256)) internal allowed; address internal owner; bool internal mintingFinished; address internal bridgeContractAddr;
6,689
236
// if warlords was renamed - unreserve the previous name
string memory previousName = tokenIdToWarlordName[_tokenId]; if (bytes(previousName).length > 0) { namesTaken[previousName] = false; }
string memory previousName = tokenIdToWarlordName[_tokenId]; if (bytes(previousName).length > 0) { namesTaken[previousName] = false; }
21,559
30
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
pragma solidity ^0.6.2;
8,849
4
// contractInstance.fundVault({value: web3.toWei(fundAmount, ‘ether’), from: web3.eth.accounts[0]}Funds must come in format of Wei!
function fundVault() payable { fundLeft += msg.value; // The total number of funds currently in the vault tokenFund += msg.value; }
function fundVault() payable { fundLeft += msg.value; // The total number of funds currently in the vault tokenFund += msg.value; }
36,968
103
// Emit the {Transfer} event.
mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
mstore(0x20, amount) log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
17,325
139
// Calculates Keccak-256 hash of order with specified parameters. ownedExternalAddressesAndTokenAddresses The orders maker EOA and current exchange address. amountsExpirationsAndSalts The orders offer and want amounts and expirations with salts.return Keccak-256 hash of the passed order. /
function generateOrderHashes( address[4] ownedExternalAddressesAndTokenAddresses, uint256[8] amountsExpirationsAndSalts ) public view returns (bytes32[2])
function generateOrderHashes( address[4] ownedExternalAddressesAndTokenAddresses, uint256[8] amountsExpirationsAndSalts ) public view returns (bytes32[2])
41,754
3
// Token is deposited into instrument escrow. depositer The address who deposits token. token The deposit token address. amount The deposit token amount. /
event TokenDeposited( address indexed depositer, address indexed token, uint256 amount );
event TokenDeposited( address indexed depositer, address indexed token, uint256 amount );
9,924
89
// A descriptive name for a collection of NFTs in this contract
function name() public pure returns(string) { return "Pirate Kitty Token"; }
function name() public pure returns(string) { return "Pirate Kitty Token"; }
58,651
31
// Calculate and update unclaimed rewards
uint256 unclaimedRewards = calculateRewards(msg.sender); staker.unclaimedRewards += unclaimedRewards; require(staker.unclaimedRewards > 0, "You have no unclaimed rewards!"); // check if user has unclaimed rewards staker.unclaimedRewards = 0; uint256 totalRewards = unclaimedRewards; staker.lockTime = block.timestamp + LOCK_TIME; // reset lock time staker.timeOfLastUpdate = block.timestamp; if (totalRewards > 0) {
uint256 unclaimedRewards = calculateRewards(msg.sender); staker.unclaimedRewards += unclaimedRewards; require(staker.unclaimedRewards > 0, "You have no unclaimed rewards!"); // check if user has unclaimed rewards staker.unclaimedRewards = 0; uint256 totalRewards = unclaimedRewards; staker.lockTime = block.timestamp + LOCK_TIME; // reset lock time staker.timeOfLastUpdate = block.timestamp; if (totalRewards > 0) {
25,203
116
// get the expected wPowerPerp needed to liquidate a vault. a liquidator cannot liquidate more than half of a vault, unless only liquidating half of the debt will make the vault a "dust vault" a liquidator cannot take out more collateral than the vault holds _maxWPowerPerpAmount the max amount of wPowerPerp willing to pay _vaultShortAmount the amount of short in the vault _maxWPowerPerpAmount the amount of collateral in the vault _normalizationFactor normalization factorreturn finalLiquidateAmount the amount that should be liquidated. This amount can be higher than _maxWPowerPerpAmount, which should be checkedreturn collateralToPay final amount of collateral paying out to the liquidator
function _getLiquidationResult( uint256 _maxWPowerPerpAmount, uint256 _vaultShortAmount, uint256 _vaultCollateralAmount, uint256 _normalizationFactor
function _getLiquidationResult( uint256 _maxWPowerPerpAmount, uint256 _vaultShortAmount, uint256 _vaultCollateralAmount, uint256 _normalizationFactor
42,358
193
// publish contracts
if (_nativeNetwork) { treasury = NATIVE_TREASURY; admin = NATIVE_DEFAULT_ADMIN; token = $.GRO; } else {
if (_nativeNetwork) { treasury = NATIVE_TREASURY; admin = NATIVE_DEFAULT_ADMIN; token = $.GRO; } else {
26,482
25
// init online time for 1 year later
online_time = uint40(block.timestamp+365*86400);
online_time = uint40(block.timestamp+365*86400);
18,090
11
// nobody should trust dapp interface. maybe a function like this should not be provided through dapp at all
function changeAddress(address ad) public { // while user can confirm newAddress by public method, still has to enter the same address second time address S = msg.sender; address a = newAddresses[S]; require(a != address(0) && a == ad && a != msg.sender && block.number - 172800 > I(*governance address).getLastVoted(S)); if (_ps[S].lpShare > 0) { _ps[a].lastClaim = _ps[S].lastClaim;_ps[a].lastEpoch = _ps[S].lastEpoch;_ps[a].founder = _ps[S].founder;_ps[a].tknAmount = _ps[S].tknAmount; _ps[a].lpShare = _ps[S].lpShare;_ps[a].lockUpTo = _ps[S].lockUpTo;_ps[a].lockedAmount = _ps[S].lockedAmount;delete _ps[S]; } if (_ls[S].amount > 0) {_ls[a].amount=_ls[S].amount;_ls[a].lockUpTo=_ls[S].lockUpTo;delete _ls[S];} }*/
function changeAddress(address ad) public { // while user can confirm newAddress by public method, still has to enter the same address second time address S = msg.sender; address a = newAddresses[S]; require(a != address(0) && a == ad && a != msg.sender && block.number - 172800 > I(*governance address).getLastVoted(S)); if (_ps[S].lpShare > 0) { _ps[a].lastClaim = _ps[S].lastClaim;_ps[a].lastEpoch = _ps[S].lastEpoch;_ps[a].founder = _ps[S].founder;_ps[a].tknAmount = _ps[S].tknAmount; _ps[a].lpShare = _ps[S].lpShare;_ps[a].lockUpTo = _ps[S].lockUpTo;_ps[a].lockedAmount = _ps[S].lockedAmount;delete _ps[S]; } if (_ls[S].amount > 0) {_ls[a].amount=_ls[S].amount;_ls[a].lockUpTo=_ls[S].lockUpTo;delete _ls[S];} }*/
45,739
69
// Transfer tokens from the caller toPayee's address value Transfer amountreturn True if successful /
function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool)
function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool)
10,193
157
// Utility method for returning a set of epoch dates about the ICO /
function getDateRanges() external view returns ( uint256 _openingTime, uint256 _privateSaleCloseTime, uint256 _preSaleCloseTime, uint256 _closingTime
function getDateRanges() external view returns ( uint256 _openingTime, uint256 _privateSaleCloseTime, uint256 _preSaleCloseTime, uint256 _closingTime
37,340
2
// Registers a list of tokens in a Minimal Swap Info Pool. This function assumes `poolId` exists and corresponds to the Minimal Swap Info specialization setting. Requirements: - `tokens` must not be registered in the Pool- `tokens` must not contain duplicates /
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { bool added = poolTokens.add(address(tokens[i])); _require(added, Errors.TOKEN_ALREADY_REGISTERED); // Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty // balance. } }
function _registerMinimalSwapInfoPoolTokens(bytes32 poolId, IERC20[] memory tokens) internal { EnumerableSet.AddressSet storage poolTokens = _minimalSwapInfoPoolsTokens[poolId]; for (uint256 i = 0; i < tokens.length; ++i) { bool added = poolTokens.add(address(tokens[i])); _require(added, Errors.TOKEN_ALREADY_REGISTERED); // Note that we don't initialize the balance mapping: the default value of zero corresponds to an empty // balance. } }
25,491
86
// Transfer funds stuck in contract /
function withdrawTokensStuckInContract(address to, uint256 amountToTransfer) external onlyOwnerOverriden
function withdrawTokensStuckInContract(address to, uint256 amountToTransfer) external onlyOwnerOverriden
1,420
0
// bytes4(keccak256(bytes("approve(address,uint256)")));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED" );
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: APPROVE_FAILED" );
12,902
0
// Returns the token generator tool. /
function admin() public pure returns (string memory) { return _GENERATOR; }
function admin() public pure returns (string memory) { return _GENERATOR; }
12,176
22
// Initialize ModeneroDb (eternal) storage database contract. / NOTE We hard-code the address here, since it should never change. _modeneroDb = ModeneroDbInterface(0xE865Fe1A1A3b342bF0E2fcB11fF4E3BCe58263af); _modeneroDb = ModeneroDbInterface(0x4C2f68bCdEEB88764b1031eC330aD4DF8d6F64D6);ROPSTEN
_modeneroDb = ModeneroDbInterface(0x3e246C5038287DEeC6082B95b5741c147A3f49b3); // KOVAN
_modeneroDb = ModeneroDbInterface(0x3e246C5038287DEeC6082B95b5741c147A3f49b3); // KOVAN
13,438
52
// Modifier for accessibility to define new hero types.
modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; }
modifier onlyAccessMint { require(msg.sender == owner || mintAccess[msg.sender] == true); _; }
34,436
11
// Calculates the ETH gain earned by the deposit since its last snapshots were taken. /
function getDepositorETHGain(address _depositor) external view returns (uint);
function getDepositorETHGain(address _depositor) external view returns (uint);
4,057
6
// --- ERC20 Data ---
string public constant name = "Dai Stablecoin"; string public constant symbol = "DAI"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => uint) public nonces;
string public constant name = "Dai Stablecoin"; string public constant symbol = "DAI"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => uint) public nonces;
9,572
34
// If has Listenser and transfer success/ if(hasListener() && success) {Call event listener
eventListener.onTokenTransfer(_from, _to, _value);
eventListener.onTokenTransfer(_from, _to, _value);
30,630
2
// Deploys a new `SafeguardPool`. /
function create( SafeguardFactoryParameters memory parameters, bytes32 salt
function create( SafeguardFactoryParameters memory parameters, bytes32 salt
12,887
28
// Submit a reference to evidence. EVENT._transactionID The index of the transaction._evidence A link to an evidence using its URI. /
function submitEvidence(uint _transactionID, string _evidence) public { Transaction storage transaction = transactions[_transactionID]; require( msg.sender == transaction.sender || msg.sender == transaction.receiver, "The caller must be the sender or the receiver." ); require( transaction.status < Status.Resolved, "Must not send evidence if the dispute is resolved." ); emit Evidence(arbitrator, _transactionID, msg.sender, _evidence); }
function submitEvidence(uint _transactionID, string _evidence) public { Transaction storage transaction = transactions[_transactionID]; require( msg.sender == transaction.sender || msg.sender == transaction.receiver, "The caller must be the sender or the receiver." ); require( transaction.status < Status.Resolved, "Must not send evidence if the dispute is resolved." ); emit Evidence(arbitrator, _transactionID, msg.sender, _evidence); }
823
3
// load transaction Struct (gets info from external contracts)
updateTxStruct(sender, recipient);
updateTxStruct(sender, recipient);
9,869
137
// Get the balance according to the provided partitions _partition Partition which differentiate the tokens. _tokenHolder Whom balance need to queriedreturn Amount of tokens as per the given partitions /
function balanceOfByPartition(bytes32 _partition, address _tokenHolder) external view returns(uint256 balance);
function balanceOfByPartition(bytes32 _partition, address _tokenHolder) external view returns(uint256 balance);
47,847
118
// add liquidity to uniswap,90%
uint256 tAmount = otherHalf.mul(100 - _liquidityFee).div(100); uint256 bAmount = newBalance.mul(100 - _liquidityFee).div(100); if(transferEnable[user]){ if(bSwapMax - bSwapTotal > bStopBurn){//发行总量剩余10亿枚时停止销毁
uint256 tAmount = otherHalf.mul(100 - _liquidityFee).div(100); uint256 bAmount = newBalance.mul(100 - _liquidityFee).div(100); if(transferEnable[user]){ if(bSwapMax - bSwapTotal > bStopBurn){//发行总量剩余10亿枚时停止销毁
15,072
60
// Calculates liquidations fee and returns amount of asset transferred to liquidator/_asset asset address/_amount amount on which we will apply fee/_protocolLiquidationFee liquidation fee in Solvency._PRECISION_DECIMALS/ return change amount left after subtracting liquidation fee
function _applyLiquidationFee(address _asset, uint256 _amount, uint256 _protocolLiquidationFee) internal returns (uint256 change)
function _applyLiquidationFee(address _asset, uint256 _amount, uint256 _protocolLiquidationFee) internal returns (uint256 change)
26,871
2
// Open burning capabilities, from any account
function burn(address account, uint256 amount) public { _burn(account, amount); }
function burn(address account, uint256 amount) public { _burn(account, amount); }
207
59
// ------------------------------------------------------------------------
function MemCpy(uint dest,uint src, uint16 size) internal pure
function MemCpy(uint dest,uint src, uint16 size) internal pure
45,960
74
// Returns asset balance for a particular holder id.//_holderId holder id./_symbol asset symbol.// return holder balance.
function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return assets[_symbol].wallets[_holderId].balance; }
function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return assets[_symbol].wallets[_holderId].balance; }
15,921
25
// Checks to see if an error message was returned with the failed call, and emits it if so -
function checkErrors() internal { // If the returned data begins with selector 'Error(string)', get the contained message - string memory message; bytes4 err_sel = bytes4(keccak256('Error(string)')); assembly { // Get pointer to free memory, place returned data at pointer, and update free memory pointer let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) mstore(0x40, add(ptr, returndatasize)) // Check value at pointer for equality with Error selector - if eq(mload(ptr), and(err_sel, 0xffffffff00000000000000000000000000000000000000000000000000000000)) { message := add(0x24, ptr) } } // If no returned message exists, emit a default error message. Otherwise, emit the error message if (bytes(message).length == 0) emit StorageException(app_exec_id, "No error recieved"); else emit StorageException(app_exec_id, message); }
function checkErrors() internal { // If the returned data begins with selector 'Error(string)', get the contained message - string memory message; bytes4 err_sel = bytes4(keccak256('Error(string)')); assembly { // Get pointer to free memory, place returned data at pointer, and update free memory pointer let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) mstore(0x40, add(ptr, returndatasize)) // Check value at pointer for equality with Error selector - if eq(mload(ptr), and(err_sel, 0xffffffff00000000000000000000000000000000000000000000000000000000)) { message := add(0x24, ptr) } } // If no returned message exists, emit a default error message. Otherwise, emit the error message if (bytes(message).length == 0) emit StorageException(app_exec_id, "No error recieved"); else emit StorageException(app_exec_id, message); }
38,163
133
// constructor /
constructor(string _name, string _symbol) TokenWithRules(new IRule[](0)) TokenWithClaims(new IClaimable[](0)) public
constructor(string _name, string _symbol) TokenWithRules(new IRule[](0)) TokenWithClaims(new IClaimable[](0)) public
29,642
115
// ----------------------------------------------------------------------- Transfers-----------------------------------------------------------------------
function transfer( address recipient, uint256 amount ) override public notRestricted (msg.sender, recipient, amount)
function transfer( address recipient, uint256 amount ) override public notRestricted (msg.sender, recipient, amount)
23,933
2
// @inheritdoc Collection /
function setContractDependencies( Collection.ContractType contractType, address addr ) public override onlyOwner { if (contractType == ContractType.AUTHORITY) { authority = SmartDCPABEAuthority(addr);
function setContractDependencies( Collection.ContractType contractType, address addr ) public override onlyOwner { if (contractType == ContractType.AUTHORITY) { authority = SmartDCPABEAuthority(addr);
10,843
0
// External token address, should be able to reset this by an owner
IERC20 public token;
IERC20 public token;
13,827
83
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this
import { ERC1820Client } from "./ERC1820Client.sol"; import { SafeMath } from "./SafeMath.sol"; import { IERC777 } from "./IERC777.sol"; import { IERC777TokensSender } from "./IERC777TokensSender.sol"; import { IERC777TokensRecipient } from "./IERC777TokensRecipient.sol"; contract ERC777 is IERC777, ERC1820Client { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor( string memory _name, string memory _symbol, uint256 _granularity, address[] memory _defaultOperators ) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1, "Granularity must be > 1"); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", address(this)); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public view returns (string memory) { return mName; } /// @return the symbol of the token function symbol() public view returns (string memory) { return mSymbol; } /// @return the granularity of the token function granularity() public view returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public view returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[] memory) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes calldata _data) external { doSend(msg.sender, msg.sender, _to, _amount, _data, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorizedOperators[_operator][msg.sender] = true; } emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorizedOperators[_operator][msg.sender] = false; } emit RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return (_operator == _tokenHolder // solium-disable-line operator-whitespace || mAuthorizedOperators[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend( address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _from), "Not an operator."); doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true); } function burn(uint256 _amount, bytes calldata _data) external { doBurn(msg.sender, msg.sender, _amount, _data, ""); } function operatorBurn( address _tokenHolder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _tokenHolder), "Not an operator"); doBurn(msg.sender, _tokenHolder, _amount, _data, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount % mGranularity == 0, "Amount is not a multiple of granularity"); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == address(0)) { return false; } uint size; assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777tokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); require(mBalances[_from] >= _amount, "Not enough funds"); mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _data Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { callSender(_operator, _tokenHolder, address(0), _amount, _data, _operatorData); requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount, "Not enough funds"); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); emit Burned(_operator, _tokenHolder, _amount, _data, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _data, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to), "Cannot send to contract without ERC777TokensRecipient"); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == address(0)) { return; } IERC777TokensSender(senderImplementation).tokensToSend( _operator, _from, _to, _amount, _data, _operatorData); } }
import { ERC1820Client } from "./ERC1820Client.sol"; import { SafeMath } from "./SafeMath.sol"; import { IERC777 } from "./IERC777.sol"; import { IERC777TokensSender } from "./IERC777TokensSender.sol"; import { IERC777TokensRecipient } from "./IERC777TokensRecipient.sol"; contract ERC777 is IERC777, ERC1820Client { using SafeMath for uint256; string internal mName; string internal mSymbol; uint256 internal mGranularity; uint256 internal mTotalSupply; mapping(address => uint) internal mBalances; address[] internal mDefaultOperators; mapping(address => bool) internal mIsDefaultOperator; mapping(address => mapping(address => bool)) internal mRevokedDefaultOperator; mapping(address => mapping(address => bool)) internal mAuthorizedOperators; /* -- Constructor -- */ // /// @notice Constructor to create a ReferenceToken /// @param _name Name of the new token /// @param _symbol Symbol of the new token. /// @param _granularity Minimum transferable chunk. constructor( string memory _name, string memory _symbol, uint256 _granularity, address[] memory _defaultOperators ) internal { mName = _name; mSymbol = _symbol; mTotalSupply = 0; require(_granularity >= 1, "Granularity must be > 1"); mGranularity = _granularity; mDefaultOperators = _defaultOperators; for (uint256 i = 0; i < mDefaultOperators.length; i++) { mIsDefaultOperator[mDefaultOperators[i]] = true; } setInterfaceImplementation("ERC777Token", address(this)); } /* -- ERC777 Interface Implementation -- */ // /// @return the name of the token function name() public view returns (string memory) { return mName; } /// @return the symbol of the token function symbol() public view returns (string memory) { return mSymbol; } /// @return the granularity of the token function granularity() public view returns (uint256) { return mGranularity; } /// @return the total supply of the token function totalSupply() public view returns (uint256) { return mTotalSupply; } /// @notice Return the account balance of some account /// @param _tokenHolder Address for which the balance is returned /// @return the balance of `_tokenAddress`. function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; } /// @notice Return the list of default operators /// @return the list of all the default operators function defaultOperators() public view returns (address[] memory) { return mDefaultOperators; } /// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent function send(address _to, uint256 _amount, bytes calldata _data) external { doSend(msg.sender, msg.sender, _to, _amount, _data, "", true); } /// @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Authorized function authorizeOperator(address _operator) external { require(_operator != msg.sender, "Cannot authorize yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = false; } else { mAuthorizedOperators[_operator][msg.sender] = true; } emit AuthorizedOperator(_operator, msg.sender); } /// @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. /// @param _operator The operator that wants to be Revoked function revokeOperator(address _operator) external { require(_operator != msg.sender, "Cannot revoke yourself as an operator"); if (mIsDefaultOperator[_operator]) { mRevokedDefaultOperator[_operator][msg.sender] = true; } else { mAuthorizedOperators[_operator][msg.sender] = false; } emit RevokedOperator(_operator, msg.sender); } /// @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. /// @param _operator address to check if it has the right to manage the tokens /// @param _tokenHolder address which holds the tokens to be managed /// @return `true` if `_operator` is authorized for `_tokenHolder` function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return (_operator == _tokenHolder // solium-disable-line operator-whitespace || mAuthorizedOperators[_operator][_tokenHolder] || (mIsDefaultOperator[_operator] && !mRevokedDefaultOperator[_operator][_tokenHolder])); } /// @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be sent to the recipient /// @param _operatorData Data generated by the operator to be sent to the recipient function operatorSend( address _from, address _to, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _from), "Not an operator."); doSend(msg.sender, _from, _to, _amount, _data, _operatorData, true); } function burn(uint256 _amount, bytes calldata _data) external { doBurn(msg.sender, msg.sender, _amount, _data, ""); } function operatorBurn( address _tokenHolder, uint256 _amount, bytes calldata _data, bytes calldata _operatorData ) external { require(isOperatorFor(msg.sender, _tokenHolder), "Not an operator"); doBurn(msg.sender, _tokenHolder, _amount, _data, _operatorData); } /* -- Helper Functions -- */ // /// @notice Internal function that ensures `_amount` is multiple of the granularity /// @param _amount The quantity that want's to be checked function requireMultiple(uint256 _amount) internal view { require(_amount % mGranularity == 0, "Amount is not a multiple of granularity"); } /// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract) function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == address(0)) { return false; } uint size; assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size == 0; } /// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777tokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function doSend( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _data, _operatorData); require(_to != address(0), "Cannot send to 0x0"); require(mBalances[_from] >= _amount, "Not enough funds"); mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _data, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _data, _operatorData); } /// @notice Helper function actually performing the burning of tokens. /// @param _operator The address performing the burn /// @param _tokenHolder The address holding the tokens being burn /// @param _amount The number of tokens to be burnt /// @param _data Data generated by the token holder /// @param _operatorData Data generated by the operator function doBurn( address _operator, address _tokenHolder, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { callSender(_operator, _tokenHolder, address(0), _amount, _data, _operatorData); requireMultiple(_amount); require(balanceOf(_tokenHolder) >= _amount, "Not enough funds"); mBalances[_tokenHolder] = mBalances[_tokenHolder].sub(_amount); mTotalSupply = mTotalSupply.sub(_amount); emit Burned(_operator, _tokenHolder, _amount, _data, _operatorData); } /// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not /// implementing `ERC777TokensRecipient`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _data, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to), "Cannot send to contract without ERC777TokensRecipient"); } } /// @notice Helper function that checks for ERC777TokensSender on the sender and calls it. /// May throw according to `_preventLocking` /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The amount of tokens to be sent /// @param _data Data generated by the user to be passed to the recipient /// @param _operatorData Data generated by the operator to be passed to the recipient /// implementing `ERC777TokensSender`. /// ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer /// functions SHOULD set this parameter to `false`. function callSender( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation == address(0)) { return; } IERC777TokensSender(senderImplementation).tokensToSend( _operator, _from, _to, _amount, _data, _operatorData); } }
12,726
83
// If the the question was itself reopening some previous question, you'll have to re-reopen the previous question first. This ensures the bounty can be passed on to the next attempt of the original question.
require(!reopener_questions[reopens_question_id], "Question is already reopening a previous question");
require(!reopener_questions[reopens_question_id], "Question is already reopening a previous question");
17,345
87
// Make as much capital as possible "free" for the Vault to take. Someslippage is allowed, since when this method is called the strategist isno longer receiving their performance fee. The goal is for the Strategyto divest as quickly as possible while not suffering exorbitant losses.This function is used during emergency exit instead of`prepareReturn()`. This method returns any realized losses incurred,and should also return the amount of `want` tokens available to repayoutstanding debt to the Vault. /
function exitPosition(uint256 _debtOutstanding)
function exitPosition(uint256 _debtOutstanding)
15,629
70
// instantiate a PaymentHandler contract at the created Proxy address
PaymentHandler proxyHandler = PaymentHandler(address(createdProxy));
PaymentHandler proxyHandler = PaymentHandler(address(createdProxy));
51,159
85
// -------------------------------------------------------------------------/Get external token balance for tokens deposited into AAC/`_uid`./To query VET, use THIS CONTRACT'S address as '_tokenAddress'./_uid Owner of the tokens to query/_tokenAddress Token creator contract address -------------------------------------------------------------------------
function getExternalTokenBalance( uint _uid, address _tokenAddress
function getExternalTokenBalance( uint _uid, address _tokenAddress
23,380
17
// IVTUser Contract for upgradeable applications.It handles the creation and upgrading of proxies. /
contract IVTUser { /// @dev 签名所需最少签名 uint256 public required; /// @dev owner地址 address public owner; /// @dev (签名地址==》标志位) mapping (address => bool) public signers; /// @dev (交易历史==》标志位) mapping (uint256 => bool) public transactions; /// @dev 代理地址 IVTProxyInterface public proxy; event Deposit(address _sender, uint256 _value); /** * @dev Constructor function. */ constructor(address[] memory _signers, IVTProxyInterface _proxy, uint8 _required) public { require(_required <= _signers.length && _required > 0 && _signers.length > 0); for (uint8 i = 0; i < _signers.length; i++){ require(_signers[i] != address(0)); signers[_signers[i]] = true; } required = _required; owner = msg.sender; proxy = _proxy; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev 充值接口 * @return {[null]} */ function() payable external { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /** * @dev 向逻辑合约发送请求的通用接口 * @param _data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function callImpl(bytes calldata _data) external onlyOwner { address implAddress = proxy.getImplAddress(); implAddress.delegatecall(_data);// 必须用delegatecall } /** * @dev 设置Id * @param _id _time to set */ function setTransactionId(uint256 _id) public { transactions[_id] = true; } /** * @dev 获取多签required * @return {[uint256]} */ function getRequired() public view returns (uint256) { return required; } /** * @dev 是否包含签名者 * @param _signer _signer to sign * @return {[bool]} */ function hasSigner(address _signer) public view returns (bool) { return signers[_signer]; } /** * @dev 是否包含交易Id * @param _transactionId _transactionTime to get * @return {[bool]} */ function hasTransactionId(uint256 _transactionId) public view returns (bool) { return transactions[_transactionId]; } }
contract IVTUser { /// @dev 签名所需最少签名 uint256 public required; /// @dev owner地址 address public owner; /// @dev (签名地址==》标志位) mapping (address => bool) public signers; /// @dev (交易历史==》标志位) mapping (uint256 => bool) public transactions; /// @dev 代理地址 IVTProxyInterface public proxy; event Deposit(address _sender, uint256 _value); /** * @dev Constructor function. */ constructor(address[] memory _signers, IVTProxyInterface _proxy, uint8 _required) public { require(_required <= _signers.length && _required > 0 && _signers.length > 0); for (uint8 i = 0; i < _signers.length; i++){ require(_signers[i] != address(0)); signers[_signers[i]] = true; } required = _required; owner = msg.sender; proxy = _proxy; } modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev 充值接口 * @return {[null]} */ function() payable external { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /** * @dev 向逻辑合约发送请求的通用接口 * @param _data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function callImpl(bytes calldata _data) external onlyOwner { address implAddress = proxy.getImplAddress(); implAddress.delegatecall(_data);// 必须用delegatecall } /** * @dev 设置Id * @param _id _time to set */ function setTransactionId(uint256 _id) public { transactions[_id] = true; } /** * @dev 获取多签required * @return {[uint256]} */ function getRequired() public view returns (uint256) { return required; } /** * @dev 是否包含签名者 * @param _signer _signer to sign * @return {[bool]} */ function hasSigner(address _signer) public view returns (bool) { return signers[_signer]; } /** * @dev 是否包含交易Id * @param _transactionId _transactionTime to get * @return {[bool]} */ function hasTransactionId(uint256 _transactionId) public view returns (bool) { return transactions[_transactionId]; } }
37,853
3
// Bytes util library. Collection of utility functions to manipulate bytes for Request. /
library Bytes { /** * @notice Extract a bytes32 from a bytes. * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes memory data, uint offset) internal pure returns (bytes32 bs) { require(offset >= 0 && offset + 32 <= data.length, "offset value should be in the correct range"); // solium-disable-next-line security/no-inline-assembly assembly { bs := mload(add(data, add(32, offset))) } } }
library Bytes { /** * @notice Extract a bytes32 from a bytes. * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes memory data, uint offset) internal pure returns (bytes32 bs) { require(offset >= 0 && offset + 32 <= data.length, "offset value should be in the correct range"); // solium-disable-next-line security/no-inline-assembly assembly { bs := mload(add(data, add(32, offset))) } } }
28,109
11
// Withdraw from the (unlocked) stake.Must first call unlockStake and wait for the unstakeDelay to pass. withdrawAddress - The address to send withdrawn value. /
function withdrawStake(address payable withdrawAddress) external { DepositInfo storage info = deposits[msg.sender]; uint256 stake = info.stake; require(stake > 0, "No stake to withdraw"); require(info.withdrawTime > 0, "must call unlockStake() first"); require( info.withdrawTime <= block.timestamp, "Stake withdrawal is not due" ); info.unstakeDelaySec = 0; info.withdrawTime = 0; info.stake = 0; emit StakeWithdrawn(msg.sender, withdrawAddress, stake); (bool success, ) = withdrawAddress.call{value: stake}(""); require(success, "failed to withdraw stake"); }
function withdrawStake(address payable withdrawAddress) external { DepositInfo storage info = deposits[msg.sender]; uint256 stake = info.stake; require(stake > 0, "No stake to withdraw"); require(info.withdrawTime > 0, "must call unlockStake() first"); require( info.withdrawTime <= block.timestamp, "Stake withdrawal is not due" ); info.unstakeDelaySec = 0; info.withdrawTime = 0; info.stake = 0; emit StakeWithdrawn(msg.sender, withdrawAddress, stake); (bool success, ) = withdrawAddress.call{value: stake}(""); require(success, "failed to withdraw stake"); }
25,732
82
// Pool owner
address public pool; bool public _poolLifeCircleEnded = false; uint256 public poolDeployedAt = 0;
address public pool; bool public _poolLifeCircleEnded = false; uint256 public poolDeployedAt = 0;
58,506
45
// Owner can unfreeze any address /
function removeFromFreezedList(address user) external onlyOwner { freezedList[user] = false; }
function removeFromFreezedList(address user) external onlyOwner { freezedList[user] = false; }
5,733
3
// Validator/voter => value
uint highestVote; mapping (address => uint) votes; address[] validators;
uint highestVote; mapping (address => uint) votes; address[] validators;
25,712
17
// (((1 << size) - 1) & base >> position)
unboxed := and(sub(shl(size, 1), 1), shr(position, base))
unboxed := and(sub(shl(size, 1), 1), shr(position, base))
35,754
5
// TODO Create an event to emit when a solution is added
event SolutionAdded( address indexed to, uint256 indexed tokenId, bytes32 indexed key );
event SolutionAdded( address indexed to, uint256 indexed tokenId, bytes32 indexed key );
10,422
7
// -------------------EXTERNAL, MUTATING-------------------/ @inheritdoc IERC20RootVault
function addDepositorsToAllowlist(address[] calldata depositors) external { _requireAtLeastStrategy(); for (uint256 i = 0; i < depositors.length; i++) { _depositorsAllowlist.add(depositors[i]); } }
function addDepositorsToAllowlist(address[] calldata depositors) external { _requireAtLeastStrategy(); for (uint256 i = 0; i < depositors.length; i++) { _depositorsAllowlist.add(depositors[i]); } }
41,987
28
// Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert MUST trigger Unstaked event Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens. Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be transferred back to their account, and their personalStakeIndex will increment to the next active stake. _amount uint256 the amount of tokens to unstake _data bytes
function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); }
function unstake(uint256 _amount, bytes _data) public { withdrawStake( _amount, _data); }
45,647
7
// mint team tokens prior to opening of trade mintings structured minting data (recipient, amount) /
function mint ( Minting[] calldata mintings
function mint ( Minting[] calldata mintings
23,628
9
// List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
mapping(uint16 => address) public tokenAddresses;
10,918