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
|
|---|---|---|---|---|
100
|
// Get the referrer address that referred the user. /
|
function getReferrer(address user) external view returns (address);
|
function getReferrer(address user) external view returns (address);
| 23,817
|
301
|
// Rolls the vault's funds into a new short position. /
|
function rollToNextOption() external onlyManager nonReentrant {
require(
block.timestamp >= nextOptionReadyAt,
"Cannot roll before delay"
);
address newOption = nextOption;
require(newOption != address(0), "No found option");
currentOption = newOption;
nextOption = address(0);
uint256 currentBalance = IERC20(asset).balanceOf(address(this));
uint256 shortAmount = wmul(currentBalance, lockedRatio);
lockedAmount = shortAmount;
OtokenInterface otoken = OtokenInterface(newOption);
ProtocolAdapterTypes.OptionTerms memory optionTerms =
ProtocolAdapterTypes.OptionTerms(
otoken.underlyingAsset(),
USDC,
otoken.collateralAsset(),
otoken.expiryTimestamp(),
otoken.strikePrice().mul(10**10), // scale back to 10**18
isPut
? ProtocolAdapterTypes.OptionType.Put
: ProtocolAdapterTypes.OptionType.Call, // isPut
address(0)
);
uint256 shortBalance =
adapter.delegateCreateShort(optionTerms, shortAmount);
IERC20 optionToken = IERC20(newOption);
optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance);
emit OpenShort(newOption, shortAmount, msg.sender);
}
|
function rollToNextOption() external onlyManager nonReentrant {
require(
block.timestamp >= nextOptionReadyAt,
"Cannot roll before delay"
);
address newOption = nextOption;
require(newOption != address(0), "No found option");
currentOption = newOption;
nextOption = address(0);
uint256 currentBalance = IERC20(asset).balanceOf(address(this));
uint256 shortAmount = wmul(currentBalance, lockedRatio);
lockedAmount = shortAmount;
OtokenInterface otoken = OtokenInterface(newOption);
ProtocolAdapterTypes.OptionTerms memory optionTerms =
ProtocolAdapterTypes.OptionTerms(
otoken.underlyingAsset(),
USDC,
otoken.collateralAsset(),
otoken.expiryTimestamp(),
otoken.strikePrice().mul(10**10), // scale back to 10**18
isPut
? ProtocolAdapterTypes.OptionType.Put
: ProtocolAdapterTypes.OptionType.Call, // isPut
address(0)
);
uint256 shortBalance =
adapter.delegateCreateShort(optionTerms, shortAmount);
IERC20 optionToken = IERC20(newOption);
optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance);
emit OpenShort(newOption, shortAmount, msg.sender);
}
| 21,485
|
9
|
// Stores the total count of assets managed by this registry /
|
uint256 internal _count;
|
uint256 internal _count;
| 29,328
|
123
|
// Withdraw LP tokens from farm.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.acctkfPerShare).div(1e12).sub(user.rewardDebt);
safetkfTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.acctkfPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
pool.totalAmount = pool.totalAmount.sub(_amount);
emit Withdraw(msg.sender, _pid, _amount);
}
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.acctkfPerShare).div(1e12).sub(user.rewardDebt);
safetkfTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.acctkfPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
pool.totalAmount = pool.totalAmount.sub(_amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 57,308
|
25
|
// Sets the distributorSurfReward. Must be between 0 and 100
|
function setDistributorSurfReward(uint256 _distributorSurfReward) external onlyOwner {
require(_distributorSurfReward >= 0 && _distributorSurfReward <= 100e18, "Out of range");
distributorSurfReward = _distributorSurfReward;
}
|
function setDistributorSurfReward(uint256 _distributorSurfReward) external onlyOwner {
require(_distributorSurfReward >= 0 && _distributorSurfReward <= 100e18, "Out of range");
distributorSurfReward = _distributorSurfReward;
}
| 32,659
|
104
|
// If not burned.
|
if (packed & _BITMASK_BURNED == 0) {
|
if (packed & _BITMASK_BURNED == 0) {
| 41,810
|
17
|
// See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowanceis the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address.- `from` must have a balance of at least `value`.- the caller must have allowance for ``from``'s tokens of at least`value`. /
|
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
|
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
| 14,989
|
219
|
// Checks that _msgSender is the quest Manager /
|
modifier onlyQuestManager() {
require(_msgSender() == address(questManager), "Not verified");
_;
}
|
modifier onlyQuestManager() {
require(_msgSender() == address(questManager), "Not verified");
_;
}
| 23,777
|
5
|
// The registry ID of the exchange contract with permission to mint and burn this token. Unique per StableToken instance. solhint-disable-next-line state-visibility
|
bytes32 exchangeRegistryId;
|
bytes32 exchangeRegistryId;
| 25,827
|
5
|
// If the user doesn't have variable debt, no need to try to burn variable debt tokens
|
if (vars.userVariableDebt > 0) {
IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn(
user,
vars.userVariableDebt,
debtReserve.variableBorrowIndex
);
}
|
if (vars.userVariableDebt > 0) {
IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn(
user,
vars.userVariableDebt,
debtReserve.variableBorrowIndex
);
}
| 53,240
|
82
|
// See {transferCreativeLicense}. /
|
function _transferCreativeLicense(
address from,
address to,
uint256 tokenId
) internal virtual {
address creativeOwner = ERC1190.creativeOwnerOf(tokenId);
require(
creativeOwner == from,
"ERC1190: Cannot transfer the ownership license if it is not owned."
);
|
function _transferCreativeLicense(
address from,
address to,
uint256 tokenId
) internal virtual {
address creativeOwner = ERC1190.creativeOwnerOf(tokenId);
require(
creativeOwner == from,
"ERC1190: Cannot transfer the ownership license if it is not owned."
);
| 37,353
|
59
|
// Gets the API struct variables that are not mappings _requestId to look upreturn string of api to queryreturn string of symbol of api to queryreturn bytes32 hash of stringreturn bytes32 of the granularity(decimal places) requestedreturn uint of index in requestQ arrayreturn uint of current payout/tip for this requestId /
|
function getRequestVars(uint256 _requestId)
|
function getRequestVars(uint256 _requestId)
| 41,347
|
173
|
// return current block number
|
return block.number;
|
return block.number;
| 11,207
|
366
|
// Before token transfer hook to enforce that no token can be moved to another address until the pode sale has ended /
|
function _beforeTokenTransfer(address from, address, uint256) internal override {
if (from != address(0) && _getNow() <= podeLockTimestamp) {
revert("DigitalaxPodeNFT._beforeTokenTransfer: Transfers are currently locked at this time");
}
}
|
function _beforeTokenTransfer(address from, address, uint256) internal override {
if (from != address(0) && _getNow() <= podeLockTimestamp) {
revert("DigitalaxPodeNFT._beforeTokenTransfer: Transfers are currently locked at this time");
}
}
| 40,837
|
139
|
// CsaToken with Governance.
|
contract CsaToken is ERC20("CsaToken", "CSA"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
|
contract CsaToken is ERC20("CsaToken", "CSA"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
| 81,965
|
15
|
// Mapping from inscription Id to a hash of the nftAddress and tokenId
|
mapping (uint256 => bytes32) private _locationHashes;
|
mapping (uint256 => bytes32) private _locationHashes;
| 235
|
24
|
// 1. Harvest gains from positions
|
_tendGainsFromPositions();
uint256 stakedCvxCrv = cvxCrvRewardsPool.balanceOf(address(this));
if (stakedCvxCrv > 0) {
cvxCrvRewardsPool.withdraw(stakedCvxCrv, true);
}
|
_tendGainsFromPositions();
uint256 stakedCvxCrv = cvxCrvRewardsPool.balanceOf(address(this));
if (stakedCvxCrv > 0) {
cvxCrvRewardsPool.withdraw(stakedCvxCrv, true);
}
| 17,612
|
65
|
// oneWrite. /
|
contract oneWrite {
// Adds modifies that allow one function to be called only once
//Copyright (c) 2017 GenkiFS
bool written = false;
function oneWrite() {
/** @dev Constuctor, make sure written=false initally
*/
written = false;
}
modifier LockIfUnwritten() {
if (written){
_;
}
}
modifier writeOnce() {
if (!written){
written=true;
_;
}
}
}
|
contract oneWrite {
// Adds modifies that allow one function to be called only once
//Copyright (c) 2017 GenkiFS
bool written = false;
function oneWrite() {
/** @dev Constuctor, make sure written=false initally
*/
written = false;
}
modifier LockIfUnwritten() {
if (written){
_;
}
}
modifier writeOnce() {
if (!written){
written=true;
_;
}
}
}
| 35,185
|
125
|
// the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256). /
|
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex times
unchecked {
return _currentIndex - _burnCounter;
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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 override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, 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 TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
|
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex times
unchecked {
return _currentIndex - _burnCounter;
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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 override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, 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 TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
| 3,401
|
156
|
// contract dependencies
|
IExchangeWrapper public exchange;
IERC20 public perpToken;
IMinter public minter;
IInflationMonitor public inflationMonitor;
address private beneficiary;
|
IExchangeWrapper public exchange;
IERC20 public perpToken;
IMinter public minter;
IInflationMonitor public inflationMonitor;
address private beneficiary;
| 7,166
|
12
|
// Checks if a transfer can occur between the from/to addresses Both addresses must be whitelisted, unfrozen, and pass all compliance rule checks THROWS when the transfer should failinitiator The address initiating the transferfrom The address of the senderto The address of the receivertokens The number of tokens being transferred return If a transfer can occur between the from/to addresses /
|
function canTransfer(address initiator, address from, address to, uint256 tokens)
external
|
function canTransfer(address initiator, address from, address to, uint256 tokens)
external
| 20,960
|
28
|
// Configurable Configurable varriables of the contract /
|
contract Configurable {
uint256 public constant cap = 420000000000000000000000 *10**1;
uint256 public constant basePrice = 1000000000000000000000*10**1; // tokens per 1 ether
uint256 public tokensSold = 0;
uint256 public constant tokenReserve = 80000000000000000000000*10**1;
uint256 public remainingTokens = 0;
}
|
contract Configurable {
uint256 public constant cap = 420000000000000000000000 *10**1;
uint256 public constant basePrice = 1000000000000000000000*10**1; // tokens per 1 ether
uint256 public tokensSold = 0;
uint256 public constant tokenReserve = 80000000000000000000000*10**1;
uint256 public remainingTokens = 0;
}
| 10,086
|
12
|
// Listing identifier is keccak256 of Seller's partial transaction outpoint
|
bytes32 _listingID = keccak256(_partialTx.slice(7, 36));
|
bytes32 _listingID = keccak256(_partialTx.slice(7, 36));
| 30,214
|
87
|
// `maxBatchSize` refers to how much a minter can mint at a time.`collectionSize_` refers to how many tokens are in the collection. /
|
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
|
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
| 12,052
|
37
|
// mint using other mint functions
|
mintOnChainMfer(dna);
|
mintOnChainMfer(dna);
| 37,723
|
140
|
// Conic tokens created per second.
|
uint256 public conicPerSecond;
|
uint256 public conicPerSecond;
| 33,842
|
4
|
// v must be in the closed interval [0, 99] otherwise it outputs junk
|
y := numbx1(numbx1(x, div(v, 10)), mod(v, 10))
|
y := numbx1(numbx1(x, div(v, 10)), mod(v, 10))
| 20,258
|
119
|
// Our Token Contract
|
IERC20 public contractToken;
IERC20 public __usdtToken;
AggregatorV3Interface internal priceFeed;
using SafeMath for uint256;
using SafeCast for uint256;
using SafeERC20 for IERC20;
|
IERC20 public contractToken;
IERC20 public __usdtToken;
AggregatorV3Interface internal priceFeed;
using SafeMath for uint256;
using SafeCast for uint256;
using SafeERC20 for IERC20;
| 27,704
|
13
|
// Init StRSR
|
{
string memory stRSRSymbol = string(abi.encodePacked(StringLib.toLower(symbol), "RSR"));
string memory stRSRName = string(abi.encodePacked(stRSRSymbol, " Token"));
main.stRSR().init(
main,
stRSRName,
stRSRSymbol,
params.unstakingDelay,
params.rewardPeriod,
params.rewardRatio
|
{
string memory stRSRSymbol = string(abi.encodePacked(StringLib.toLower(symbol), "RSR"));
string memory stRSRName = string(abi.encodePacked(stRSRSymbol, " Token"));
main.stRSR().init(
main,
stRSRName,
stRSRSymbol,
params.unstakingDelay,
params.rewardPeriod,
params.rewardRatio
| 38,579
|
27
|
// Set up the member: status, name, `member since` & `inactive since`.
|
members_[_memberId] = Member(true, _memberName, "", uint64(now), 0);
|
members_[_memberId] = Member(true, _memberName, "", uint64(now), 0);
| 83,427
|
196
|
// Update the free memory pointer to allocate.
|
mstore(0x40, m)
|
mstore(0x40, m)
| 44,314
|
15
|
// usage: bytes32 h = Wallet(w).from(oneOwner).transact(to, value, data); Wallet(w).from(anotherOwner).confirm(h);
|
contract Wallet is multisig, multiowned, daylimit {
uint public version = 2;
// TYPES
// Transaction structure to remember details of transaction lest it need be saved for a later call.
struct Transaction {
address to;
uint value;
bytes data;
}
// METHODS
// constructor - just pass on the owner array to the multiowned and
// the limit to daylimit
function Wallet(address[] _owners, uint _required, uint _daylimit)
multiowned(_owners, _required) daylimit(_daylimit) {
}
// kills the contract sending everything to `_to`.
function kill(address _to) onlymanyowners(sha3(msg.data, block.number)) external {
suicide(_to);
}
// gets called when no other function matches
function() {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
// Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 _r) {
// first, take the opportunity to check that we're under the daily limit.
if (underLimit(_value)) {
SingleTransact(msg.sender, _value, _to, _data);
// yes - just execute the call.
_to.call.value(_value)(_data);
return 0;
}
// determine our operation hash.
_r = sha3(msg.data, block.number);
if (!confirm(_r) && m_txs[_r].to == 0) {
m_txs[_r].to = _to;
m_txs[_r].value = _value;
m_txs[_r].data = _data;
ConfirmationNeeded(_r, msg.sender, _value, _to, _data);
}
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
if (m_txs[_h].to != 0) {
m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data);
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data);
delete m_txs[_h];
return true;
}
}
// INTERNAL METHODS
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
delete m_txs[m_pendingIndex[i]];
super.clearPending();
}
// FIELDS
// pending transactions we have at present.
mapping (bytes32 => Transaction) m_txs;
}
|
contract Wallet is multisig, multiowned, daylimit {
uint public version = 2;
// TYPES
// Transaction structure to remember details of transaction lest it need be saved for a later call.
struct Transaction {
address to;
uint value;
bytes data;
}
// METHODS
// constructor - just pass on the owner array to the multiowned and
// the limit to daylimit
function Wallet(address[] _owners, uint _required, uint _daylimit)
multiowned(_owners, _required) daylimit(_daylimit) {
}
// kills the contract sending everything to `_to`.
function kill(address _to) onlymanyowners(sha3(msg.data, block.number)) external {
suicide(_to);
}
// gets called when no other function matches
function() {
// just being sent some cash?
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
// Outside-visible transact entry point. Executes transacion immediately if below daily spend limit.
// If not, goes into multisig process. We provide a hash on return to allow the sender to provide
// shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value
// and _data arguments). They still get the option of using them if they want, anyways.
function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 _r) {
// first, take the opportunity to check that we're under the daily limit.
if (underLimit(_value)) {
SingleTransact(msg.sender, _value, _to, _data);
// yes - just execute the call.
_to.call.value(_value)(_data);
return 0;
}
// determine our operation hash.
_r = sha3(msg.data, block.number);
if (!confirm(_r) && m_txs[_r].to == 0) {
m_txs[_r].to = _to;
m_txs[_r].value = _value;
m_txs[_r].data = _data;
ConfirmationNeeded(_r, msg.sender, _value, _to, _data);
}
}
// confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order
// to determine the body of the transaction from the hash provided.
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
if (m_txs[_h].to != 0) {
m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data);
MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data);
delete m_txs[_h];
return true;
}
}
// INTERNAL METHODS
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i)
delete m_txs[m_pendingIndex[i]];
super.clearPending();
}
// FIELDS
// pending transactions we have at present.
mapping (bytes32 => Transaction) m_txs;
}
| 35,918
|
4
|
// Returns the index of the Pool's main token in the Pool tokens array (as returned by IVault.getPoolTokens). /
|
function getMainIndex() external view returns (uint256);
|
function getMainIndex() external view returns (uint256);
| 22,022
|
22
|
// Conversion rate from IX15 to ETH
|
struct Price { uint256 numerator; uint256 denominator; }
Price public currentPrice;
// The amount of time that the secondary wallet must wait between price updates
uint256 public priceUpdateInterval = 1 hours;
mapping (uint256 => Price) public priceHistory;
uint256 public currentPriceHistoryIndex = 0;
// time for each withdrawal is set to the currentPriceHistoryIndex
struct WithdrawalRequest { uint256 nummberOfTokens; uint256 time; }
mapping (address => WithdrawalRequest) withdrawalRequests;
mapping(uint8 => string) restrictionMap;
constructor (address newSecondaryWallet, uint256 newPriceNumerator) public {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
require(newPriceNumerator > 0, "newPriceNumerator > 0");
name = "Isonex";
symbol = "IX15";
decimals = 18;
primaryWallet = msg.sender;
secondaryWallet = newSecondaryWallet;
whitelist[primaryWallet] = true;
whitelist[secondaryWallet] = true;
currentPrice = Price(newPriceNumerator, 1000);
currentPriceHistoryIndex = now;
restrictionMap[1] = "Sender is not whitelisted";
restrictionMap[2] = "Receiver is not whitelisted";
restrictionMap[3] = "Trading is not enabled";
}
|
struct Price { uint256 numerator; uint256 denominator; }
Price public currentPrice;
// The amount of time that the secondary wallet must wait between price updates
uint256 public priceUpdateInterval = 1 hours;
mapping (uint256 => Price) public priceHistory;
uint256 public currentPriceHistoryIndex = 0;
// time for each withdrawal is set to the currentPriceHistoryIndex
struct WithdrawalRequest { uint256 nummberOfTokens; uint256 time; }
mapping (address => WithdrawalRequest) withdrawalRequests;
mapping(uint8 => string) restrictionMap;
constructor (address newSecondaryWallet, uint256 newPriceNumerator) public {
require(newSecondaryWallet != address(0), "newSecondaryWallet != address(0)");
require(newPriceNumerator > 0, "newPriceNumerator > 0");
name = "Isonex";
symbol = "IX15";
decimals = 18;
primaryWallet = msg.sender;
secondaryWallet = newSecondaryWallet;
whitelist[primaryWallet] = true;
whitelist[secondaryWallet] = true;
currentPrice = Price(newPriceNumerator, 1000);
currentPriceHistoryIndex = now;
restrictionMap[1] = "Sender is not whitelisted";
restrictionMap[2] = "Receiver is not whitelisted";
restrictionMap[3] = "Trading is not enabled";
}
| 37,996
|
190
|
// now add to yearn
|
yvToken.deposit();
lastInvest = block.timestamp;
|
yvToken.deposit();
lastInvest = block.timestamp;
| 46,213
|
99
|
// transfer token last, to follow CEI pattern
|
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
|
stakeToken.safeTransferFrom(msg.sender, address(this), amount);
| 12,798
|
14
|
// Add accounts to the minter role. Restricted to admins.accounts The members to add as a member./
|
function addMinters(address[] memory accounts)
public
virtual
onlyOwner
|
function addMinters(address[] memory accounts)
public
virtual
onlyOwner
| 38,988
|
1
|
// even if not all parameters are currently used in this implementation they help future proofing it
|
function onReward(
uint256 _pid,
address _user,
address _to,
uint256 _pending,
uint256 _stakedAmount,
uint256 _lpSupply
) external;
|
function onReward(
uint256 _pid,
address _user,
address _to,
uint256 _pending,
uint256 _stakedAmount,
uint256 _lpSupply
) external;
| 31,986
|
13
|
// Will burn sender account rendering it unusable
|
function burn() public {
require(BurntLedger[msg.sender] == false);
BurntLedger[msg.sender] = true;
}
|
function burn() public {
require(BurntLedger[msg.sender] == false);
BurntLedger[msg.sender] = true;
}
| 3,483
|
310
|
// Checks if sorbetto is initialized
|
bool public finalized;
|
bool public finalized;
| 10,685
|
44
|
// CAPITAL (CALL) Token Token representing CALL. /
|
contract CALLToken is MintableToken {
string public name = "CAPITAL";
string public symbol = "CALL";
uint8 public decimals = 18;
}
|
contract CALLToken is MintableToken {
string public name = "CAPITAL";
string public symbol = "CALL";
uint8 public decimals = 18;
}
| 50,552
|
75
|
// Generates `_amount` tokens that are assigned to `_owner`/_owner The address that will be assigned the new tokens/_amount The quantity of tokens generated/ return True if the tokens are generated correctly
|
function generateTokens(address _owner, uint256 _amount
|
function generateTokens(address _owner, uint256 _amount
| 24,482
|
140
|
// BeeBToken with Governance.
|
contract BeeBToken is BEP20('PancakeSwap Token', 'Cake') {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce");
require(now <= expiry, "CAKE::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAKEs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
contract BeeBToken is BEP20('PancakeSwap Token', 'Cake') {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce");
require(now <= expiry, "CAKE::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAKEs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 23,290
|
125
|
// _loans[nftID].accuredInterestWei = outstanding(nftID) - _loans[nftID].borrowedWei;
|
_loans[nftID].returnedWei = _loans[nftID].borrowedWei;
|
_loans[nftID].returnedWei = _loans[nftID].borrowedWei;
| 57,740
|
138
|
// CozyTimeAuction /
|
contract CozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
|
contract CozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
| 58,038
|
5
|
// get delegation weight
|
(, , uint256 deactivatedEpoch, , uint256 amount, ,) = sfc.delegations(from, toStakerID);
if (deactivatedEpoch != 0) {
return 0;
}
|
(, , uint256 deactivatedEpoch, , uint256 amount, ,) = sfc.delegations(from, toStakerID);
if (deactivatedEpoch != 0) {
return 0;
}
| 4,139
|
0
|
// Usings // Enums // Status of the message state machine. /
|
enum MessageStatus {
Undeclared,
Declared,
Progressed,
DeclaredRevocation,
Revoked
}
|
enum MessageStatus {
Undeclared,
Declared,
Progressed,
DeclaredRevocation,
Revoked
}
| 34,967
|
4
|
// Returns the DAO's membership token URI /
|
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
|
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
| 43,749
|
107
|
// Same as a standards-compliant ERC20.approve() that never reverts (returns false).Note that this makes an external call to the token./
|
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
|
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
| 5,515
|
72
|
// Get token price
|
(uint256 systemCoinPrice, bool validSysCoinPrice) = systemCoinOrcl.getResultWithValidity();
require(both(systemCoinPrice > 0, validSysCoinPrice), "DebtAuctionInitialParameterSetter/invalid-price");
|
(uint256 systemCoinPrice, bool validSysCoinPrice) = systemCoinOrcl.getResultWithValidity();
require(both(systemCoinPrice > 0, validSysCoinPrice), "DebtAuctionInitialParameterSetter/invalid-price");
| 7,384
|
225
|
// Converts masset amount into credits based on exchange ratem = creditsexchangeRate /
|
function _creditToUnderlying(uint256 _credits)
internal
view
returns (uint256 underlyingAmount)
|
function _creditToUnderlying(uint256 _credits)
internal
view
returns (uint256 underlyingAmount)
| 5,401
|
66
|
// get isLocked attribute of the smart contract/
|
function getIsLocked() public view returns (bool) {
return isLocked;
}
|
function getIsLocked() public view returns (bool) {
return isLocked;
}
| 10,830
|
380
|
// Liquidity Protection Store interface /
|
interface ILiquidityProtectionStore is IOwned {
function withdrawTokens(
IReserveToken token,
address recipient,
uint256 amount
) external;
function protectedLiquidity(uint256 id)
external
view
returns (
address,
IDSToken,
IReserveToken,
uint256,
uint256,
uint256,
uint256,
uint256
);
function addProtectedLiquidity(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
uint256 reserveRateN,
uint256 reserveRateD,
uint256 timestamp
) external returns (uint256);
function updateProtectedLiquidityAmounts(
uint256 id,
uint256 poolNewAmount,
uint256 reserveNewAmount
) external;
function removeProtectedLiquidity(uint256 id) external;
function lockedBalance(address provider, uint256 index) external view returns (uint256, uint256);
function lockedBalanceRange(
address provider,
uint256 startIndex,
uint256 endIndex
) external view returns (uint256[] memory, uint256[] memory);
function addLockedBalance(
address provider,
uint256 reserveAmount,
uint256 expirationTime
) external returns (uint256);
function removeLockedBalance(address provider, uint256 index) external;
function systemBalance(IReserveToken poolToken) external view returns (uint256);
function incSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
function decSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
}
|
interface ILiquidityProtectionStore is IOwned {
function withdrawTokens(
IReserveToken token,
address recipient,
uint256 amount
) external;
function protectedLiquidity(uint256 id)
external
view
returns (
address,
IDSToken,
IReserveToken,
uint256,
uint256,
uint256,
uint256,
uint256
);
function addProtectedLiquidity(
address provider,
IDSToken poolToken,
IReserveToken reserveToken,
uint256 poolAmount,
uint256 reserveAmount,
uint256 reserveRateN,
uint256 reserveRateD,
uint256 timestamp
) external returns (uint256);
function updateProtectedLiquidityAmounts(
uint256 id,
uint256 poolNewAmount,
uint256 reserveNewAmount
) external;
function removeProtectedLiquidity(uint256 id) external;
function lockedBalance(address provider, uint256 index) external view returns (uint256, uint256);
function lockedBalanceRange(
address provider,
uint256 startIndex,
uint256 endIndex
) external view returns (uint256[] memory, uint256[] memory);
function addLockedBalance(
address provider,
uint256 reserveAmount,
uint256 expirationTime
) external returns (uint256);
function removeLockedBalance(address provider, uint256 index) external;
function systemBalance(IReserveToken poolToken) external view returns (uint256);
function incSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
function decSystemBalance(IReserveToken poolToken, uint256 poolAmount) external;
}
| 23,692
|
60
|
// Get the current balance of the tokens /
|
function balanceToMaintain() external view returns(uint256) {
uint256 currentBalance = IERC20(stakeToken).balanceOf(address(this));
uint256 totalUnClaimed = totalUnClaimedTokens();
if(totalUnClaimed > currentBalance) {
return totalUnClaimed.sub(currentBalance);
} else {
return 0;
}
}
|
function balanceToMaintain() external view returns(uint256) {
uint256 currentBalance = IERC20(stakeToken).balanceOf(address(this));
uint256 totalUnClaimed = totalUnClaimedTokens();
if(totalUnClaimed > currentBalance) {
return totalUnClaimed.sub(currentBalance);
} else {
return 0;
}
}
| 27,210
|
20
|
// Gets the current votes balance for `account` account The address to get votes balancereturn The number of current votes for `account` /
|
function getCurrentVotes(address account)
external
view
returns (uint256)
|
function getCurrentVotes(address account)
external
view
returns (uint256)
| 1,031
|
68
|
// save in returned value the amount of weth receive to use off-chain
|
_balances[i] = _res[_res.length - 1];
|
_balances[i] = _res[_res.length - 1];
| 67,315
|
26
|
// scope to avoid stack too deep errors
|
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = BeagleLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
|
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = BeagleLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
| 25,240
|
15
|
// Operations are ordered from most likely usage to least likely usage.
|
for {} 1 {
|
for {} 1 {
| 20,556
|
2
|
// Check if adddress bought before
|
if (addressSale[msg.sender] != 0) revert AddressAlreadyBought();
|
if (addressSale[msg.sender] != 0) revert AddressAlreadyBought();
| 30,023
|
2
|
// Params that could be changed by Strategy or Protocol Governance./tokenLimitPerAddress Max LP token limit per address/tokenLimit Max LP token for the vault
|
struct StrategyParams {
uint256 tokenLimitPerAddress;
uint256 tokenLimit;
}
|
struct StrategyParams {
uint256 tokenLimitPerAddress;
uint256 tokenLimit;
}
| 42,022
|
1
|
// Request a reassignment of the grantee address./ Can only be called by the grantee./_newGrantee The requested new grantee.
|
function requestGranteeReassignment(address _newGrantee)
public
onlyGrantee
noRequestedReassignment
|
function requestGranteeReassignment(address _newGrantee)
public
onlyGrantee
noRequestedReassignment
| 17,900
|
6
|
// Refund user
|
if(_sourceAddress == address(ETH)){
msg.sender.transfer(_amount);
} else if(_needToRefund) {
|
if(_sourceAddress == address(ETH)){
msg.sender.transfer(_amount);
} else if(_needToRefund) {
| 23,241
|
17
|
// Lets a contract admin set the recipient for all primary sales.
|
function setSaleRecipientForToken(uint256 _tokenId, address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
saleRecipient[_tokenId] = _saleRecipient;
}
|
function setSaleRecipientForToken(uint256 _tokenId, address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
saleRecipient[_tokenId] = _saleRecipient;
}
| 6,259
|
305
|
// Stores the details of an order.//_prefix The miscellaneous details of the order required for/calculating the order id./_settlementID The settlement identifier./_tokens The encoding of the token pair (buy token is encoded as/the first 32 bytes and sell token is encoded as the last 32/bytes)./_price The price of the order. Interpreted as the cost for 1/standard unit of the non-priority token, in 1e12 (i.e./PRICE_OFFSET) units of the priority token)./_volume The volume of the order. Interpreted as the maximum/number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority/token that can be traded by this order./_minimumVolume The minimum volume the trader is willing to/accept. Encoded
|
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
|
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
| 32,871
|
25
|
// Adjusted tokens
|
uint256 adjustedTokens = (((((_tokens * PRECISION) / fromAppliedTokenCirculation) * info.totalSupply)) / PRECISION);
info.users[_from].balance -= adjustedTokens;
_transferred = adjustedTokens;
info.users[_to].balance += _transferred;
|
uint256 adjustedTokens = (((((_tokens * PRECISION) / fromAppliedTokenCirculation) * info.totalSupply)) / PRECISION);
info.users[_from].balance -= adjustedTokens;
_transferred = adjustedTokens;
info.users[_to].balance += _transferred;
| 38,595
|
125
|
// Community Multisig
|
rewardDistribution[0xF49440C1F012d041802b25A73e5B0B9166a75c02] = true;
for(uint256 i = 0; i < _rewardDistributions.length; i++) {
rewardDistribution[_rewardDistributions[i]] = true;
}
|
rewardDistribution[0xF49440C1F012d041802b25A73e5B0B9166a75c02] = true;
for(uint256 i = 0; i < _rewardDistributions.length; i++) {
rewardDistribution[_rewardDistributions[i]] = true;
}
| 24,939
|
241
|
// Three different options for minting Creatures (basic, premium, and gold). /
|
uint256 NUM_OPTIONS = 3;
uint256 SINGLE_CREATURE_OPTION = 0;
uint256 MULTIPLE_CREATURE_OPTION = 1;
uint256 NUM_CREATURES_IN_MULTIPLE_CREATURE_OPTION = 4;
|
uint256 NUM_OPTIONS = 3;
uint256 SINGLE_CREATURE_OPTION = 0;
uint256 MULTIPLE_CREATURE_OPTION = 1;
uint256 NUM_CREATURES_IN_MULTIPLE_CREATURE_OPTION = 4;
| 37,620
|
9
|
// Indicates if surplus funds have been redistributed for each sustainer address
|
mapping(address => bool) redistributed;
|
mapping(address => bool) redistributed;
| 22,819
|
85
|
// Mapping from NFT ID to its index in the seller tokens list. /
|
mapping(uint256 => uint256) public tokenToSellerIndex;
|
mapping(uint256 => uint256) public tokenToSellerIndex;
| 22,175
|
839
|
// Accrue ALK to the market by updating the borrow index market The market whose borrow index to update isVerified Verified / Public protocol /
|
function updateAlkBorrowIndex(address market, bool isVerified) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalBorrows = getMarketTotalBorrows(
market,
isVerified
);
uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalBorrows > 0
? fraction(borrowAlkAccrued, marketTotalBorrows)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: borrowState.index}),
ratio
);
alkBorrowState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
|
function updateAlkBorrowIndex(address market, bool isVerified) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalBorrows = getMarketTotalBorrows(
market,
isVerified
);
uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalBorrows > 0
? fraction(borrowAlkAccrued, marketTotalBorrows)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: borrowState.index}),
ratio
);
alkBorrowState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
| 17,641
|
3
|
// Declares the contract as willing to be an implementer of`interfaceHash` for `account`.
|
* See {IERC1820Registry-setInterfaceImplementer} and
* {IERC1820Registry-interfaceHash}.
*/
function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual {
_supportedInterfaces[interfaceHash][account] = true;
}
|
* See {IERC1820Registry-setInterfaceImplementer} and
* {IERC1820Registry-interfaceHash}.
*/
function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual {
_supportedInterfaces[interfaceHash][account] = true;
}
| 30,867
|
909
|
// emit in deposit or burn
|
event Sent(address sender, address srcNft, uint256 id, uint64 dstChid, address receiver, address dstNft);
|
event Sent(address sender, address srcNft, uint256 id, uint64 dstChid, address receiver, address dstNft);
| 5,421
|
85
|
// Convert x to the 192.64-bit fixed-point format.
|
uint256 x192x64 = (x << 64) / SCALE;
|
uint256 x192x64 = (x << 64) / SCALE;
| 32,416
|
0
|
// Withdraws token from Franklin to root chain in case of exodus mode. User must provide proof that he owns funds/_accountId Id of the account in the tree/_proof Proof/_tokenId Verified token id/_amount Amount for owner (must be total amount, not part of it)
|
function exit(uint32 _accountId, uint16 _tokenId, uint128 _amount, uint256[] calldata _proof) external nonReentrant {
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, _tokenId);
require(exodusMode, "fet11"); // must be in exodus mode
require(!exited[_accountId][_tokenId], "fet12"); // already exited
require(verifierExit.verifyExitProof(blocks[totalBlocksVerified].stateRoot, _accountId, msg.sender, _tokenId, _amount, _proof), "fet13"); // verification failed
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.add(_amount);
exited[_accountId][_tokenId] = true;
}
|
function exit(uint32 _accountId, uint16 _tokenId, uint128 _amount, uint256[] calldata _proof) external nonReentrant {
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, _tokenId);
require(exodusMode, "fet11"); // must be in exodus mode
require(!exited[_accountId][_tokenId], "fet12"); // already exited
require(verifierExit.verifyExitProof(blocks[totalBlocksVerified].stateRoot, _accountId, msg.sender, _tokenId, _amount, _proof), "fet13"); // verification failed
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.add(_amount);
exited[_accountId][_tokenId] = true;
}
| 21,060
|
4
|
// Used to notify listeners that a child's asset has been unequipped from one of its parent assets. tokenId ID of the token that had an asset unequipped assetId ID of the asset associated with the token we are unequipping out of slotPartId ID of the slot we are unequipping from childId ID of the token being unequipped childAddress Address of the collection that a token that is being unequipped belongs to childAssetId ID of the asset associated with the token we are unequipping /
|
event ChildAssetUnequipped(
|
event ChildAssetUnequipped(
| 13,072
|
11
|
// versions: - ArbitrumValidator 0.1.0: initial release- ArbitrumValidator 0.2.0: critical Arbitrum network update- xDomain `msg.sender` backwards incompatible change (now an alias address)- new `withdrawFundsFromL2` fn that withdraws from L2 xDomain alias address- approximation of `maxSubmissionCost` using a L1 gas price feed- ArbitrumValidator 1.0.0: change target of L2 sequencer status update- now calls `updateStatus` on an L2 ArbitrumSequencerUptimeFeed contract instead ofdirectly calling the Flags contract @inheritdoc TypeAndVersionInterface /
|
function typeAndVersion() external pure virtual override returns (string memory) {
return "ArbitrumValidator 1.0.0";
}
|
function typeAndVersion() external pure virtual override returns (string memory) {
return "ArbitrumValidator 1.0.0";
}
| 42,872
|
149
|
// Steal part of the tokens and the arbitration fee of a juror who failed to vote. Note that a juror who voted but without all his weight can't be penalized. It is possible to not penalize with the maximum weight. But note that it can lead to arbitration fees being kept by the contract and never distributed._jurorAddress Address of the juror to steal tokens from._disputeID The ID of the dispute the juror was drawn._draws The list of draws the juror was drawn. Numbering starts at 1 and the numbers should be increasing. /
|
function penalizeInactiveJuror(address _jurorAddress, uint _disputeID, uint[] _draws) public {
Dispute storage dispute = disputes[_disputeID];
Juror storage inactiveJuror = jurors[_jurorAddress];
require(period > Period.Vote);
require(dispute.lastSessionVote[_jurorAddress] != session); // Verify the juror hasn't voted.
dispute.lastSessionVote[_jurorAddress] = session; // Update last session to avoid penalizing multiple times.
require(validDraws(_jurorAddress, _disputeID, _draws));
uint penality = _draws.length * minActivatedToken * 2 * alpha / ALPHA_DIVISOR;
penality = (penality < inactiveJuror.balance) ? penality : inactiveJuror.balance; // Make sure the penality is not higher than the balance.
inactiveJuror.balance -= penality;
TokenShift(_jurorAddress, _disputeID, -int(penality));
jurors[msg.sender].balance += penality / 2; // Give half of the penalty to the caller.
TokenShift(msg.sender, _disputeID, int(penality / 2));
jurors[governor].balance += penality / 2; // The other half to the governor.
TokenShift(governor, _disputeID, int(penality / 2));
msg.sender.transfer(_draws.length*dispute.arbitrationFeePerJuror); // Give the arbitration fees to the caller.
}
|
function penalizeInactiveJuror(address _jurorAddress, uint _disputeID, uint[] _draws) public {
Dispute storage dispute = disputes[_disputeID];
Juror storage inactiveJuror = jurors[_jurorAddress];
require(period > Period.Vote);
require(dispute.lastSessionVote[_jurorAddress] != session); // Verify the juror hasn't voted.
dispute.lastSessionVote[_jurorAddress] = session; // Update last session to avoid penalizing multiple times.
require(validDraws(_jurorAddress, _disputeID, _draws));
uint penality = _draws.length * minActivatedToken * 2 * alpha / ALPHA_DIVISOR;
penality = (penality < inactiveJuror.balance) ? penality : inactiveJuror.balance; // Make sure the penality is not higher than the balance.
inactiveJuror.balance -= penality;
TokenShift(_jurorAddress, _disputeID, -int(penality));
jurors[msg.sender].balance += penality / 2; // Give half of the penalty to the caller.
TokenShift(msg.sender, _disputeID, int(penality / 2));
jurors[governor].balance += penality / 2; // The other half to the governor.
TokenShift(governor, _disputeID, int(penality / 2));
msg.sender.transfer(_draws.length*dispute.arbitrationFeePerJuror); // Give the arbitration fees to the caller.
}
| 62,535
|
16
|
// Payable fallback function called by 0x Exchange v3 to refund unspent protocol fee. /
|
function () external payable {
require(msg.sender == 0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef, "msg.sender is not 0x Exchange v3.");
}
|
function () external payable {
require(msg.sender == 0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef, "msg.sender is not 0x Exchange v3.");
}
| 6,425
|
17
|
// Verify freemint requirements
|
require(freeMintSale, 'The freeMint is paused!');
bytes32 leaf = keccak256(abi.encodePacked(_msgSender()));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), 'Invalid proof!');
|
require(freeMintSale, 'The freeMint is paused!');
bytes32 leaf = keccak256(abi.encodePacked(_msgSender()));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), 'Invalid proof!');
| 2,705
|
8
|
// Loading the contract contract addressreturn contract interaction object /
|
function loadCurrentContract(string memory self) internal pure returns (string memory) {
string memory ret = self;
uint retptr;
assembly { retptr := add(ret, 32) }
return ret;
}
|
function loadCurrentContract(string memory self) internal pure returns (string memory) {
string memory ret = self;
uint retptr;
assembly { retptr := add(ret, 32) }
return ret;
}
| 4,869
|
279
|
// If address is set to zero address, mint is not prohibited
|
minterRole = _newMinter;
|
minterRole = _newMinter;
| 75,926
|
86
|
// Calculate one-time deltas if storage variables have not yet been updated.
|
uint256 newFee = lastFeePaid == uint256(0) ? loan.feePaid() : uint256(0); // `loan.feePaid` updated in `loan.drawdown()`
uint256 newExcess = lastExcessReturned == uint256(0) ? loan.excessReturned() : uint256(0); // `loan.excessReturned` updated in `loan.unwind()` OR `loan.drawdown()` if `amt < fundingLockerBal`
uint256 newAmountRecovered = lastAmountRecovered == uint256(0) ? loan.amountRecovered() : uint256(0); // `loan.amountRecovered` updated in `loan.triggerDefault()`
|
uint256 newFee = lastFeePaid == uint256(0) ? loan.feePaid() : uint256(0); // `loan.feePaid` updated in `loan.drawdown()`
uint256 newExcess = lastExcessReturned == uint256(0) ? loan.excessReturned() : uint256(0); // `loan.excessReturned` updated in `loan.unwind()` OR `loan.drawdown()` if `amt < fundingLockerBal`
uint256 newAmountRecovered = lastAmountRecovered == uint256(0) ? loan.amountRecovered() : uint256(0); // `loan.amountRecovered` updated in `loan.triggerDefault()`
| 3,774
|
3,862
|
// 1932
|
entry "miened" : ENG_ADJECTIVE
|
entry "miened" : ENG_ADJECTIVE
| 18,544
|
70
|
// Transfer tokens to a specified address. to The address to transfer to. value The amount to be transferred.return True on success, false otherwise. /
|
function transfer(address to, uint256 value)
public
validRecipient(to)
returns (bool)
|
function transfer(address to, uint256 value)
public
validRecipient(to)
returns (bool)
| 21,407
|
4
|
// players.push(Player(firstName, lastName));
|
players[msg.sender] = Player(msg.sender, Level.Novice, firstName, lastName);
playerCount += 1;
|
players[msg.sender] = Player(msg.sender, Level.Novice, firstName, lastName);
playerCount += 1;
| 52,953
|
12
|
// Modifier to make a function callable only when the contract is locked. /
|
modifier whenLocked() {
require(locked);
_;
}
|
modifier whenLocked() {
require(locked);
_;
}
| 31,363
|
171
|
// bond was issued at timestamp
|
uint256 issuedAt;
|
uint256 issuedAt;
| 24,273
|
498
|
// prefix point must be linked and able to spawn
|
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
|
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
| 37,128
|
444
|
// mint zero coupon bonds to `msg.sender`
|
zeroCouponBondsAmount = fractionalDeposit.totalSupply();
_mint(msg.sender, zeroCouponBondsAmount);
emit Mint(
msg.sender,
address(fractionalDeposit),
zeroCouponBondsAmount
);
|
zeroCouponBondsAmount = fractionalDeposit.totalSupply();
_mint(msg.sender, zeroCouponBondsAmount);
emit Mint(
msg.sender,
address(fractionalDeposit),
zeroCouponBondsAmount
);
| 21,196
|
8
|
// Define an internal function '_removeAirline' to remove this role, called by 'removeAirline'
|
function _removeAirline(address account) internal {
airlines.remove(account);
emit AirlineRemoved(account);
}
|
function _removeAirline(address account) internal {
airlines.remove(account);
emit AirlineRemoved(account);
}
| 14,635
|
45
|
// GoldVein contract - standard ERC20 token with Short Hand Attack and approve() race condition mitigation. /
|
contract GoldVein is ERC223Token{
/**
* @dev The function can be called only by agent.
*/
modifier onlyAgent() {
bool flag = false;
for(uint i = 0; i < addrCotracts.length; i++) {
if(msg.sender == addrCotracts[i]) flag = true;
}
assert(flag);
_;
}
/** Name and symbol were updated. */
event UpdatedTokenInformation(string newName, string newSymbol);
/**
* @param _name Token name
* @param _symbol Token symbol - should be all caps
* @param _decimals Number of decimal places
*/
function GoldVein(string _name, string _symbol, uint256 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function tokenFallback(address _from, uint _value, bytes _data) public onlyAgent returns (bool success){
balances[this] = safeSub(balanceOf(this), _value);
balances[_from] = safeAdd(balanceOf(_from), _value);
emit Transfer(this, _from, _value, _data);
return true;
}
/**
* Owner can update token information here.
*
* It is often useful to conceal the actual token association, until
* the token operations, like central issuance or reissuance have been completed.
*
* This function allows the token owner to rename the token after the operations
* have been completed and then point the audience to use the token contract.
*/
function setTokenInformation(string _name, string _symbol) public onlyOwner {
name = _name;
symbol = _symbol;
emit UpdatedTokenInformation(name, symbol);
}
function setAddr (address _addr) public onlyOwner {
addrCotracts.push(_addr);
}
function transferForICO(address _to, uint _value) public onlyCrowdsaleAgent returns (bool success) {
return this.transfer(_to, _value);
}
function delAddr (uint number) public onlyOwner {
require(number < addrCotracts.length);
for(uint i = number; i < addrCotracts.length-1; i++) {
addrCotracts[i] = addrCotracts[i+1];
}
addrCotracts.length = addrCotracts.length-1;
}
}
|
contract GoldVein is ERC223Token{
/**
* @dev The function can be called only by agent.
*/
modifier onlyAgent() {
bool flag = false;
for(uint i = 0; i < addrCotracts.length; i++) {
if(msg.sender == addrCotracts[i]) flag = true;
}
assert(flag);
_;
}
/** Name and symbol were updated. */
event UpdatedTokenInformation(string newName, string newSymbol);
/**
* @param _name Token name
* @param _symbol Token symbol - should be all caps
* @param _decimals Number of decimal places
*/
function GoldVein(string _name, string _symbol, uint256 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function tokenFallback(address _from, uint _value, bytes _data) public onlyAgent returns (bool success){
balances[this] = safeSub(balanceOf(this), _value);
balances[_from] = safeAdd(balanceOf(_from), _value);
emit Transfer(this, _from, _value, _data);
return true;
}
/**
* Owner can update token information here.
*
* It is often useful to conceal the actual token association, until
* the token operations, like central issuance or reissuance have been completed.
*
* This function allows the token owner to rename the token after the operations
* have been completed and then point the audience to use the token contract.
*/
function setTokenInformation(string _name, string _symbol) public onlyOwner {
name = _name;
symbol = _symbol;
emit UpdatedTokenInformation(name, symbol);
}
function setAddr (address _addr) public onlyOwner {
addrCotracts.push(_addr);
}
function transferForICO(address _to, uint _value) public onlyCrowdsaleAgent returns (bool success) {
return this.transfer(_to, _value);
}
function delAddr (uint number) public onlyOwner {
require(number < addrCotracts.length);
for(uint i = number; i < addrCotracts.length-1; i++) {
addrCotracts[i] = addrCotracts[i+1];
}
addrCotracts.length = addrCotracts.length-1;
}
}
| 4,620
|
10
|
// t2 to t1
|
ICurveFiCurve(csdp.pool2).exchange_underlying(
csdp.ij2 % 10,
csdp.ij2 / 10,
dy - 1,
options / 10 > 0 ? csdp.dx + 2 : 0
);
|
ICurveFiCurve(csdp.pool2).exchange_underlying(
csdp.ij2 % 10,
csdp.ij2 / 10,
dy - 1,
options / 10 > 0 ? csdp.dx + 2 : 0
);
| 27,907
|
218
|
// Return Keeper address from the Nexus. This account is used for operational transactions that don't need multiple signatures.returnAddress of the Keeper externally owned account. /
|
function _keeper() internal view returns (address) {
return nexus.getModule(KEY_KEEPER);
}
|
function _keeper() internal view returns (address) {
return nexus.getModule(KEY_KEEPER);
}
| 28,588
|
13
|
// onlyOwner functions
|
function addSeason(
uint256 _seasonNum,
uint256 _price,
uint256 _count,
uint256 _walletLimit,
string memory _provenance,
string memory _baseURI
|
function addSeason(
uint256 _seasonNum,
uint256 _price,
uint256 _count,
uint256 _walletLimit,
string memory _provenance,
string memory _baseURI
| 27,870
|
16
|
// buy & sell
|
P3Dcontract_.buy.value(_bal)(address(0));
P3Dcontract_.sell(P3Dcontract_.balanceOf(address(this)));
|
P3Dcontract_.buy.value(_bal)(address(0));
P3Dcontract_.sell(P3Dcontract_.balanceOf(address(this)));
| 70,108
|
26
|
// Full users list
|
address[] public usersList;
mapping(address => bool) isUserInList;
|
address[] public usersList;
mapping(address => bool) isUserInList;
| 13,400
|
146
|
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
|
uint256 _witnetResultReward = 0.0001 ether;
|
uint256 _witnetResultReward = 0.0001 ether;
| 32,174
|
48
|
// This function allows the controller to assign a new controller/Emits Controller_Changed event/new_controller Address of the new controller
|
function change_controller(address new_controller) public {
require(msg.sender == controller, "only controller");
controller = new_controller;
emit Controller_Changed(new_controller);
}
|
function change_controller(address new_controller) public {
require(msg.sender == controller, "only controller");
controller = new_controller;
emit Controller_Changed(new_controller);
}
| 33,391
|
15
|
// return result of equation from balancer whitepaper Trading Formulas eq.15:
|
function tradeOutGivenIn(uint8 _indexIn, uint8 _indexOut, uint256 _amountIn) public view returns(uint256){
Coin _coinIn = Coin(payable(address(uint160(tokenData[_indexIn]))));
Coin _coinOut = Coin(payable(address(uint160(tokenData[_indexOut]))));
int128 balanceIn = convertTo64x64(_coinIn.balanceOf(address(this)));
int128 weightIn = Math.divu(uint256(tokenData[_indexIn]>>160), uint256(1000));
int128 balanceOut = convertTo64x64(_coinOut.balanceOf(address(this)));
int128 weightOut = Math.divu(uint256(tokenData[_indexOut]>>160), uint256(1000));
//balancer (eq.15): Out-Given-In
int128 compareBalance = Math.div(balanceIn, Math.add(balanceIn, convertTo64x64(_amountIn)));
int128 multiplier = Math.sub(Math.fromUInt(uint256(1)), ifractPow(compareBalance, Math.div(weightIn, weightOut)));
int128 result = Math.mul(balanceOut, multiplier);
return convertFrom64x64(result);
}
|
function tradeOutGivenIn(uint8 _indexIn, uint8 _indexOut, uint256 _amountIn) public view returns(uint256){
Coin _coinIn = Coin(payable(address(uint160(tokenData[_indexIn]))));
Coin _coinOut = Coin(payable(address(uint160(tokenData[_indexOut]))));
int128 balanceIn = convertTo64x64(_coinIn.balanceOf(address(this)));
int128 weightIn = Math.divu(uint256(tokenData[_indexIn]>>160), uint256(1000));
int128 balanceOut = convertTo64x64(_coinOut.balanceOf(address(this)));
int128 weightOut = Math.divu(uint256(tokenData[_indexOut]>>160), uint256(1000));
//balancer (eq.15): Out-Given-In
int128 compareBalance = Math.div(balanceIn, Math.add(balanceIn, convertTo64x64(_amountIn)));
int128 multiplier = Math.sub(Math.fromUInt(uint256(1)), ifractPow(compareBalance, Math.div(weightIn, weightOut)));
int128 result = Math.mul(balanceOut, multiplier);
return convertFrom64x64(result);
}
| 26,820
|
43
|
// Increase the maximum number of price and liquidity observations that this pool will store/This method is no-op if the pool already has an observationCardinalityNext greater than or equal to/ the input observationCardinalityNext./observationCardinalityNext The desired minimum number of observations for the pool to store
|
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
|
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
| 20,809
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.