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 |
|---|---|---|---|---|
19 | // extend the auction for the ticker if someone is outbidding near the end | if (isNearEndOfBidding) {
auction.biddingEnd = auction.biddingEnd + BID_EXTENSION_IN_BLOCKS;
emit AuctionForTickerExtended(lowerBrandTicker, auction.biddingEnd);
}
| if (isNearEndOfBidding) {
auction.biddingEnd = auction.biddingEnd + BID_EXTENSION_IN_BLOCKS;
emit AuctionForTickerExtended(lowerBrandTicker, auction.biddingEnd);
}
| 11,630 |
35 | // Used for cash settlement excerise for an active option _optionId Option id / | function exercise(uint256 _optionId) external override {
Option storage option = options[_optionId];
require(option.expiration >= block.timestamp, "Option has expired");
require(option.holder == msg.sender, "Invalid Caller");
require(option.state == State.Active, "Invalid state");
option.state = State.Exercised;
(uint256 profit, uint256 settlementFee) = _getProfit(_optionId);
pool.send(_optionId, option.holder, profit);
emit Exercise(_optionId, profit, settlementFee, ExcerciseType.Cash);
}
| function exercise(uint256 _optionId) external override {
Option storage option = options[_optionId];
require(option.expiration >= block.timestamp, "Option has expired");
require(option.holder == msg.sender, "Invalid Caller");
require(option.state == State.Active, "Invalid state");
option.state = State.Exercised;
(uint256 profit, uint256 settlementFee) = _getProfit(_optionId);
pool.send(_optionId, option.holder, profit);
emit Exercise(_optionId, profit, settlementFee, ExcerciseType.Cash);
}
| 4,182 |
163 | // Accrue interest | uint128 extraAmount = uint128((uint256(_totalBorrow.elastic) * cloneInfo.interestPerSecond * elapsedTime) / 1e18);
_totalBorrow.elastic = _totalBorrow.elastic + extraAmount;
_accrueInfo.feesEarned = _accrueInfo.feesEarned + extraAmount;
totalBorrow = _totalBorrow;
accrueInfo = _accrueInfo;
emit LogAccrue(extraAmount);
| uint128 extraAmount = uint128((uint256(_totalBorrow.elastic) * cloneInfo.interestPerSecond * elapsedTime) / 1e18);
_totalBorrow.elastic = _totalBorrow.elastic + extraAmount;
_accrueInfo.feesEarned = _accrueInfo.feesEarned + extraAmount;
totalBorrow = _totalBorrow;
accrueInfo = _accrueInfo;
emit LogAccrue(extraAmount);
| 32,877 |
87 | // A mapping of each investor address to a specific amount | mapping(address => uint256) public userTotalAmount;
| mapping(address => uint256) public userTotalAmount;
| 33,270 |
45 | // Has balance and is NOT broken | if (isBrokenToken[tokens[i]] == false && amounts[tokens[i]] > 0 ) {length++;}
| if (isBrokenToken[tokens[i]] == false && amounts[tokens[i]] > 0 ) {length++;}
| 36,586 |
47 | // Emits an {InvestorListUpdated} event indicating the update. Requirements: - `sender` must be admin. / |
function updateInvestorStatus(address _investorAddress,bool updateType) public onlyOwner {
if(usersList[_investorAddress].userAddress == address(0)){
usersList[_investorAddress] = User(_investorAddress,0,true);
}
|
function updateInvestorStatus(address _investorAddress,bool updateType) public onlyOwner {
if(usersList[_investorAddress].userAddress == address(0)){
usersList[_investorAddress] = User(_investorAddress,0,true);
}
| 27,362 |
19 | // Set base URI for computing {tokenURI}. _baseUri The new baseUri. / | function setBaseUri(
string memory _baseUri
)
external
onlyOwner
{
super._setBaseUri(_baseUri);
}
| function setBaseUri(
string memory _baseUri
)
external
onlyOwner
{
super._setBaseUri(_baseUri);
}
| 8,688 |
196 | // Minting with metadata received from L2 i.e. emitted by event `TransferWithMetadata` during burning | bytes memory logData = logRLPList[2].toBytes();
bytes memory metaData = abi.decode(logData, (bytes));
token.mint(withdrawer, tokenId, metaData);
| bytes memory logData = logRLPList[2].toBytes();
bytes memory metaData = abi.decode(logData, (bytes));
token.mint(withdrawer, tokenId, metaData);
| 56,890 |
27 | // Returns whether the given spender can transfer a given token ID to holder _spender address of the spender to query _to uint256 ID of the holder to receive the token ID _toOrigin address of the holder's origin _tokenId uint256 ID of the token to be transferredreturn bool whether the msg.sender is approved for the given token ID, is an operator of the owner, or is the owner of the token / | function isHolderApprovedFor(address _spender, uint256 _to, address _toOrigin, uint256 _tokenId)
internal
view
returns (bool)
| function isHolderApprovedFor(address _spender, uint256 _to, address _toOrigin, uint256 _tokenId)
internal
view
returns (bool)
| 49,284 |
74 | // Transfer a token between 2 addresses letting the receiver knows of the transfer from The sender of the token to The recipient of the token id The id of the token data Additional data / | function safeTransferFrom(address from, address to, uint256 id, bytes memory data) public {
bool metaTx = _checkTransfer(from, to, id);
_transferFrom(from, to, id);
if (to.isContract()) {
require(
_checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, data),
"ERC721: transfer rejected by to"
);
}
}
| function safeTransferFrom(address from, address to, uint256 id, bytes memory data) public {
bool metaTx = _checkTransfer(from, to, id);
_transferFrom(from, to, id);
if (to.isContract()) {
require(
_checkOnERC721Received(metaTx ? from : msg.sender, from, to, id, data),
"ERC721: transfer rejected by to"
);
}
}
| 16,586 |
141 | // An event emitted when a proposal has been queued in the Timelock | event ProposalQueued(uint256 id, uint256 eta);
| event ProposalQueued(uint256 id, uint256 eta);
| 7,534 |
22 | // Set the current user's favorite album information | function setUsersFavoriteAlbum(string memory _artist, string memory _albumTitle, uint _tracks) public {
userAlbums[msg.sender].artist = _artist;
userAlbums[msg.sender].albumTitle = _albumTitle;
userAlbums[msg.sender].tracks = _tracks;
// Raise the albumEvent to let any event subscribers know the current album information has changed.
emit albumEvent("You have updated your personal favorite album information", _artist, _albumTitle, _tracks);
} // setUsersFavoriteAlbum
| function setUsersFavoriteAlbum(string memory _artist, string memory _albumTitle, uint _tracks) public {
userAlbums[msg.sender].artist = _artist;
userAlbums[msg.sender].albumTitle = _albumTitle;
userAlbums[msg.sender].tracks = _tracks;
// Raise the albumEvent to let any event subscribers know the current album information has changed.
emit albumEvent("You have updated your personal favorite album information", _artist, _albumTitle, _tracks);
} // setUsersFavoriteAlbum
| 20,676 |
8 | // ipfs id for this file | string ipfshash;
FileState state;
| string ipfshash;
FileState state;
| 63,601 |
3 | // Public Functions / |
function resolveContract(
string memory _name
)
public
view
returns (address)
|
function resolveContract(
string memory _name
)
public
view
returns (address)
| 3,751 |
100 | // Modifies a slot at an index for a given branch. _branch Branch node to modify. _index Slot index to modify. _value Value to insert into the slot.return _updatedNode Modified branch node. / | function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
| function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
| 37,960 |
51 | // The value is stored at length-1, but we add 1 to all indexes and use 0 as a sentinel value | set._indexes[value] = set._values.length;
return true;
| set._indexes[value] = set._values.length;
return true;
| 4,190 |
21 | // _executor Address of the executor (e.g. a Safe)/_oracle Address of the oracle (e.g. Realitio)/timeout Timeout in seconds that should be required for the oracle/cooldown Cooldown in seconds that should be required after a oracle provided answer/expiration Duration that a positive answer of the oracle is valid in seconds (or 0 if valid forever)/bond Minimum bond that is required for an answer to be accepted/templateId ID of the template that should be used for proposal questions (see https:github.com/realitio/realitio-dappstructuring-and-fetching-information)/There need to be at least 60 seconds between end of cooldown and expiration | constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) {
require(timeout > 0, "Timeout has to be greater 0");
require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration");
executor = _executor;
oracle = _oracle;
answerExpiration = expiration;
questionTimeout = timeout;
questionCooldown = cooldown;
questionArbitrator = address(_executor);
minimumBond = bond;
template = templateId;
}
| constructor(Executor _executor, Realitio _oracle, uint32 timeout, uint32 cooldown, uint32 expiration, uint256 bond, uint256 templateId) {
require(timeout > 0, "Timeout has to be greater 0");
require(expiration == 0 || expiration - cooldown >= 60 , "There need to be at least 60s between end of cooldown and expiration");
executor = _executor;
oracle = _oracle;
answerExpiration = expiration;
questionTimeout = timeout;
questionCooldown = cooldown;
questionArbitrator = address(_executor);
minimumBond = bond;
template = templateId;
}
| 9,683 |
53 | // Loop through and initialize isModule, isFactory, and isResource mapping | for (uint256 i = 0; i < _factories.length; i++) {
require(_factories[i] != address(0), "Zero address submitted.");
isFactory[_factories[i]] = true;
}
| for (uint256 i = 0; i < _factories.length; i++) {
require(_factories[i] != address(0), "Zero address submitted.");
isFactory[_factories[i]] = true;
}
| 46,688 |
6 | // If no bids were made, so the status never transitioned from OPT_OUT to AUCTIONS_OPEN, then bestBid.bidder is 0, which will trigger a require later | require(settlePeriodStart <= now && now < settlePeriodEnd, "Error: not within rebalancing period");
status = Status.OPEN;
| require(settlePeriodStart <= now && now < settlePeriodEnd, "Error: not within rebalancing period");
status = Status.OPEN;
| 44,718 |
5 | // callback from oraclize with the result, let the storage contract know | function __callback(bytes32 myid, string result, bytes proof) {
if (msg.sender != oraclize_cbAddress()) throw;
// this is basically a bytes32 to hexstring piece
string memory expected = iudexIdToString(expectedId[myid]);
bool asExpected = indexOf(result, expected) > -1;
Storage(lookup.addrStorage()).updateAccount(lookup.accountProvider_GITHUB(), expectedId[myid], asExpected, myid);
delete expectedId[myid];
}
| function __callback(bytes32 myid, string result, bytes proof) {
if (msg.sender != oraclize_cbAddress()) throw;
// this is basically a bytes32 to hexstring piece
string memory expected = iudexIdToString(expectedId[myid]);
bool asExpected = indexOf(result, expected) > -1;
Storage(lookup.addrStorage()).updateAccount(lookup.accountProvider_GITHUB(), expectedId[myid], asExpected, myid);
delete expectedId[myid];
}
| 35,882 |
70 | // Picks out the ID for a node. Node ID is referred to as the"hash" within the specification, but nodes < 32 bytes are not actuallyhashed. _node Node to pull an ID for.return _nodeID ID for the node, depending on the size of its contents. / | function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
| function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
| 37,944 |
38 | // 36 = 4-byte selector 0x4e487b71 + 32 bytes integer | else if (data.length == 36 && data[0] == "\x4e" && data[1] == "\x48" && data[2] == "\x7b" && data[3] == "\x71") {
uint256 code;
| else if (data.length == 36 && data[0] == "\x4e" && data[1] == "\x48" && data[2] == "\x7b" && data[3] == "\x71") {
uint256 code;
| 10,324 |
13 | // Convert to 18 decimals | premium = premium.mul(assetOracleMultiplier);
| premium = premium.mul(assetOracleMultiplier);
| 63,115 |
27 | // Oracle Settings | {
IFraxlendWhitelist _fraxlendWhitelist = IFraxlendWhitelist(FRAXLEND_WHITELIST_ADDRESS);
| {
IFraxlendWhitelist _fraxlendWhitelist = IFraxlendWhitelist(FRAXLEND_WHITELIST_ADDRESS);
| 24,464 |
2 | // Returns the amount of tokens owned by `account`. / | function balanceOf(address tokenOwner) virtual public view returns (uint balance);
| function balanceOf(address tokenOwner) virtual public view returns (uint balance);
| 6,297 |
21 | // Returns true if `operator` is approved to transfer ``account``'s tokens. See {setApprovalForAll}. / | function isApprovedForAll(address account, address operator) external view returns (bool);
| function isApprovedForAll(address account, address operator) external view returns (bool);
| 6,880 |
19 | // ...in which case `anotherSandwich` will simply be a copy of thedata in memory, and... | anotherSandwich.status = "Eaten!";
| anotherSandwich.status = "Eaten!";
| 3,720 |
17 | // onlyRole(DEPOSITOR_ROLE) | {
ChildERC20GaslessUpgradeable._mint(account, amount);
}
| {
ChildERC20GaslessUpgradeable._mint(account, amount);
}
| 24,768 |
11 | // Donates DUST Costs more to claim dust than it's worth /IERC20(frax).safeTransfer(Send performance fee to strategist | uint256 _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
uint256 performanceFee = _want.mul(keepFXS).div(keepFXSmax);
IERC20(want).safeTransfer(
strategist,
performanceFee
);
}
| uint256 _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
uint256 performanceFee = _want.mul(keepFXS).div(keepFXSmax);
IERC20(want).safeTransfer(
strategist,
performanceFee
);
}
| 68,141 |
36 | // set a mintFeeRecipient for a specific address/address_ The address of the account/mintFeeRecipient_ The address of the mint fee recipient | function setMintFeeRecipientForAddress(address address_, address mintFeeRecipient_) external onlyOwner {
mintFeeRecipientList[address_] = mintFeeRecipient_;
}
| function setMintFeeRecipientForAddress(address address_, address mintFeeRecipient_) external onlyOwner {
mintFeeRecipientList[address_] = mintFeeRecipient_;
}
| 9,518 |
87 | // Send ether to the fund collection wallet | function forwardFunds() internal {
MULTISIG_ETH.transfer(address(this).balance);
}
| function forwardFunds() internal {
MULTISIG_ETH.transfer(address(this).balance);
}
| 8,976 |
29 | // Add the same to the recipient | balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
| balanceOf[_to] = (balanceOf[_to] + _value);
allowed[_from][msg.sender] = (allowed[_from][msg.sender] - _value);
Transfer(_from, _to, _value);
return true;
| 22,074 |
8 | // Implementations The set of implementation contracts to be used for proxies in the Deployer / | struct Implementations {
IMain main;
Components components;
ITrade trade;
}
| struct Implementations {
IMain main;
Components components;
ITrade trade;
}
| 38,621 |
627 | // Deposits tokens into the vault.//_amount the amount of tokens to deposit into the vault. | function deposit(uint256 _amount) external override {
vault.deposit(_amount);
}
| function deposit(uint256 _amount) external override {
vault.deposit(_amount);
}
| 15,681 |
84 | // Withdraw indexer tokens once the thawing period has passed. / | function withdraw() external override notPaused {
_withdraw(msg.sender);
}
| function withdraw() external override notPaused {
_withdraw(msg.sender);
}
| 12,518 |
29 | // ---------------------------------------------------------------------------- WUMI ERC20 Token---------------------------------------------------------------------------- | contract WUMI is ERC20Interface, Owned {
using SafeMath for uint;
bool public running = true;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Contract init. Set symbol, name, decimals and initial fixed supply
// ------------------------------------------------------------------------
constructor() public {
symbol = "WUMI";
name = "WUMI";
decimals = 18;
_totalSupply = 1175000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Start-stop contract functions:
// transfer, approve, transferFrom, approveAndCall
// ------------------------------------------------------------------------
modifier isRunning {
require(running);
_;
}
function startStop () public onlyOwner returns (bool success) {
if (running) { running = false; } else { running = true; }
return true;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public isRunning returns (bool success) {
require(tokens <= balances[msg.sender]);
require(to != address(0));
_transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Internal transfer function
// ------------------------------------------------------------------------
function _transfer(address from, address to, uint256 tokens) internal {
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Increase the amount of tokens that an owner allowed to a spender.
// ------------------------------------------------------------------------
function increaseAllowance(address spender, uint addedTokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, allowed[msg.sender][spender].add(addedTokens));
return true;
}
// ------------------------------------------------------------------------
// Decrease the amount of tokens that an owner allowed to a spender.
// ------------------------------------------------------------------------
function decreaseAllowance(address spender, uint subtractedTokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedTokens));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public isRunning returns (bool success) {
_approve(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Approve an address to spend another addresses' tokens.
// ------------------------------------------------------------------------
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0));
require(spender != address(0));
allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public isRunning returns (bool success) {
require(to != address(0));
_approve(from, msg.sender, allowed[from][msg.sender].sub(tokens));
_transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Tokens burn
// ------------------------------------------------------------------------
function burnTokens(uint tokens) public returns (bool success) {
require(tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
_totalSupply = _totalSupply.sub(tokens);
emit Transfer(msg.sender, address(0), tokens);
return true;
}
// ------------------------------------------------------------------------
// Tokens multisend from owner only by owner
// ------------------------------------------------------------------------
function multisend(address[] memory to, uint[] memory values) public onlyOwner returns (uint) {
require(to.length == values.length);
require(to.length < 100);
uint sum;
for (uint j; j < values.length; j++) {
sum += values[j];
}
balances[owner] = balances[owner].sub(sum);
for (uint i; i < to.length; i++) {
balances[to[i]] = balances[to[i]].add(values[i]);
emit Transfer(owner, to[i], values[i]);
}
return(to.length);
}
} | contract WUMI is ERC20Interface, Owned {
using SafeMath for uint;
bool public running = true;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Contract init. Set symbol, name, decimals and initial fixed supply
// ------------------------------------------------------------------------
constructor() public {
symbol = "WUMI";
name = "WUMI";
decimals = 18;
_totalSupply = 1175000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Start-stop contract functions:
// transfer, approve, transferFrom, approveAndCall
// ------------------------------------------------------------------------
modifier isRunning {
require(running);
_;
}
function startStop () public onlyOwner returns (bool success) {
if (running) { running = false; } else { running = true; }
return true;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public isRunning returns (bool success) {
require(tokens <= balances[msg.sender]);
require(to != address(0));
_transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Internal transfer function
// ------------------------------------------------------------------------
function _transfer(address from, address to, uint256 tokens) internal {
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Increase the amount of tokens that an owner allowed to a spender.
// ------------------------------------------------------------------------
function increaseAllowance(address spender, uint addedTokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, allowed[msg.sender][spender].add(addedTokens));
return true;
}
// ------------------------------------------------------------------------
// Decrease the amount of tokens that an owner allowed to a spender.
// ------------------------------------------------------------------------
function decreaseAllowance(address spender, uint subtractedTokens) public isRunning returns (bool success) {
_approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedTokens));
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public isRunning returns (bool success) {
_approve(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
// ------------------------------------------------------------------------
// Approve an address to spend another addresses' tokens.
// ------------------------------------------------------------------------
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0));
require(spender != address(0));
allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public isRunning returns (bool success) {
require(to != address(0));
_approve(from, msg.sender, allowed[from][msg.sender].sub(tokens));
_transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Tokens burn
// ------------------------------------------------------------------------
function burnTokens(uint tokens) public returns (bool success) {
require(tokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
_totalSupply = _totalSupply.sub(tokens);
emit Transfer(msg.sender, address(0), tokens);
return true;
}
// ------------------------------------------------------------------------
// Tokens multisend from owner only by owner
// ------------------------------------------------------------------------
function multisend(address[] memory to, uint[] memory values) public onlyOwner returns (uint) {
require(to.length == values.length);
require(to.length < 100);
uint sum;
for (uint j; j < values.length; j++) {
sum += values[j];
}
balances[owner] = balances[owner].sub(sum);
for (uint i; i < to.length; i++) {
balances[to[i]] = balances[to[i]].add(values[i]);
emit Transfer(owner, to[i], values[i]);
}
return(to.length);
}
} | 24,676 |
3 | // The EGG TOKEN! | EggToken public egg;
| EggToken public egg;
| 14,093 |
22 | // Constructor function - init core params on deploy timestampts are uint64s to give us plenty of room for millennia flags are [_useEncryption, enableTesting] | function SVLightBallotBox(bytes32 _specHash, uint64[2] openPeriod, bool[2] flags) public {
owner = msg.sender;
// take the max of the start time provided and the blocks timestamp to avoid a DoS against recent token holders
// (which someone might be able to do if they could set the timestamp in the past)
startTime = max(openPeriod[0], uint64(block.timestamp));
endTime = openPeriod[1];
useEncryption = flags[F_USE_ENC];
specHash = _specHash;
creationBlock = uint64(block.number);
// add a rough prediction of what block is the starting block
startingBlockAround = uint64((startTime - block.timestamp) / 15 + block.number);
if (flags[F_TESTING]) {
testMode = true;
TestingEnabled();
}
CreatedBallot(msg.sender, [startTime, endTime], useEncryption, specHash);
}
| function SVLightBallotBox(bytes32 _specHash, uint64[2] openPeriod, bool[2] flags) public {
owner = msg.sender;
// take the max of the start time provided and the blocks timestamp to avoid a DoS against recent token holders
// (which someone might be able to do if they could set the timestamp in the past)
startTime = max(openPeriod[0], uint64(block.timestamp));
endTime = openPeriod[1];
useEncryption = flags[F_USE_ENC];
specHash = _specHash;
creationBlock = uint64(block.number);
// add a rough prediction of what block is the starting block
startingBlockAround = uint64((startTime - block.timestamp) / 15 + block.number);
if (flags[F_TESTING]) {
testMode = true;
TestingEnabled();
}
CreatedBallot(msg.sender, [startTime, endTime], useEncryption, specHash);
}
| 80,914 |
17 | // 1. desireY(rg.sqrtRate_96 - 2^96)< 2^1282^96= 2 ^ 224 < 2 ^ 256 2. desireY < maxY = rg.liquidity(rg.sqrtPriceR_96 - rg.sqrtPriceL_96) / (rg.sqrtRate_96 - 2^96) here, '/' means div of int desireY < rg.liquidity(rg.sqrtPriceR_96 - rg.sqrtPriceL_96) / (rg.sqrtRate_96 - 2^96) => desireY(rg.sqrtRate_96 - TwoPower.Pow96) / rg.liquidity < rg.sqrtPriceR_96 - rg.sqrtPriceL_96 => rg.sqrtPriceR_96 - desireY(rg.sqrtRate_96 - TwoPower.Pow96) / rg.liquidity > rg.sqrtPriceL_96 | uint160 cl = uint160(uint256(rg.sqrtPriceR_96) - uint256(desireY) * (rg.sqrtRate_96 - TwoPower.Pow96) / rg.liquidity);
ret.locPt = LogPowMath.getLogSqrtPriceFloor(cl) + 1;
ret.locPt = MaxMinMath.min(ret.locPt, rg.rightPt);
ret.locPt = MaxMinMath.max(ret.locPt, rg.leftPt + 1);
ret.completeLiquidity = false;
if (ret.locPt == rg.rightPt) {
ret.costX = 0;
| uint160 cl = uint160(uint256(rg.sqrtPriceR_96) - uint256(desireY) * (rg.sqrtRate_96 - TwoPower.Pow96) / rg.liquidity);
ret.locPt = LogPowMath.getLogSqrtPriceFloor(cl) + 1;
ret.locPt = MaxMinMath.min(ret.locPt, rg.rightPt);
ret.locPt = MaxMinMath.max(ret.locPt, rg.leftPt + 1);
ret.completeLiquidity = false;
if (ret.locPt == rg.rightPt) {
ret.costX = 0;
| 30,603 |
0 | // roles | address public immutable owner;
address payable public immutable beneficiary;
| address public immutable owner;
address payable public immutable beneficiary;
| 18,285 |
521 | // The ChainlinkClient contract Contract writers can inherit this contract in order to create requests for theChainlink network / | contract ChainlinkClient {
using Chainlink for Chainlink.Request;
using SafeMath_Chainlink for uint256;
uint256 constant internal LINK = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = address(0);
uint256 constant private ARGS_VERSION = 1;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
LinkTokenInterface private link;
ChainlinkRequestInterface private oracle;
uint256 private requestCount = 1;
mapping(bytes32 => address) private pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param _specId The Job Specification ID that the request will be created for
* @param _callbackAddress The callback address that the response will be sent to
* @param _callbackFunctionSignature The callback function signature to use for the callback address
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 _specId,
address _callbackAddress,
bytes4 _callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32)
{
return sendChainlinkRequestTo(address(oracle), _req, _payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param _oracle The address of the oracle for the request
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requestCount));
_req.nonce = requestCount;
pendingRequests[requestId] = _oracle;
emit ChainlinkRequested(requestId);
require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle");
requestCount += 1;
return requestId;
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param _requestId The request ID
* @param _payment The amount of LINK sent for the request
* @param _callbackFunc The callback function specified for the request
* @param _expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
)
internal
{
ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]);
delete pendingRequests[_requestId];
emit ChainlinkCancelled(_requestId);
requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/**
* @notice Sets the stored oracle address
* @param _oracle The address of the oracle contract
*/
function setChainlinkOracle(address _oracle) internal {
oracle = ChainlinkRequestInterface(_oracle);
}
/**
* @notice Sets the LINK token address
* @param _link The address of the LINK token contract
*/
function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress()
internal
view
returns (address)
{
return address(link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param _oracle The address of the oracle contract that will fulfill the request
* @param _requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address _oracle, bytes32 _requestId)
internal
notPendingRequest(_requestId)
{
pendingRequests[_requestId] = _oracle;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param _ens The address of the ENS contract
* @param _node The ENS node hash
*/
function useChainlinkWithENS(address _ens, bytes32 _node)
internal
{
ens = ENSInterface(_ens);
ensNode = _node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS()
internal
{
bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Chainlink Request
* @return The bytes payload for the `transferAndCall` method
*/
function encodeRequest(Chainlink.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
_req.id,
_req.callbackAddress,
_req.callbackFunctionId,
_req.nonce,
ARGS_VERSION,
_req.buf.buf);
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param _requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 _requestId)
internal
recordChainlinkFulfillment(_requestId)
// solhint-disable-next-line no-empty-blocks
{}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param _requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId],
"Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit ChainlinkFulfilled(_requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param _requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 _requestId) {
require(pendingRequests[_requestId] == address(0), "Request is already pending");
_;
}
}
| contract ChainlinkClient {
using Chainlink for Chainlink.Request;
using SafeMath_Chainlink for uint256;
uint256 constant internal LINK = 10**18;
uint256 constant private AMOUNT_OVERRIDE = 0;
address constant private SENDER_OVERRIDE = address(0);
uint256 constant private ARGS_VERSION = 1;
bytes32 constant private ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 constant private ENS_ORACLE_SUBNAME = keccak256("oracle");
address constant private LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private ens;
bytes32 private ensNode;
LinkTokenInterface private link;
ChainlinkRequestInterface private oracle;
uint256 private requestCount = 1;
mapping(bytes32 => address) private pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param _specId The Job Specification ID that the request will be created for
* @param _callbackAddress The callback address that the response will be sent to
* @param _callbackFunctionSignature The callback function signature to use for the callback address
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 _specId,
address _callbackAddress,
bytes4 _callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(_specId, _callbackAddress, _callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32)
{
return sendChainlinkRequestTo(address(oracle), _req, _payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param _oracle The address of the oracle for the request
* @param _req The initialized Chainlink Request
* @param _payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requestCount));
_req.nonce = requestCount;
pendingRequests[requestId] = _oracle;
emit ChainlinkRequested(requestId);
require(link.transferAndCall(_oracle, _payment, encodeRequest(_req)), "unable to transferAndCall to oracle");
requestCount += 1;
return requestId;
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param _requestId The request ID
* @param _payment The amount of LINK sent for the request
* @param _callbackFunc The callback function specified for the request
* @param _expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
)
internal
{
ChainlinkRequestInterface requested = ChainlinkRequestInterface(pendingRequests[_requestId]);
delete pendingRequests[_requestId];
emit ChainlinkCancelled(_requestId);
requested.cancelOracleRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/**
* @notice Sets the stored oracle address
* @param _oracle The address of the oracle contract
*/
function setChainlinkOracle(address _oracle) internal {
oracle = ChainlinkRequestInterface(_oracle);
}
/**
* @notice Sets the LINK token address
* @param _link The address of the LINK token contract
*/
function setChainlinkToken(address _link) internal {
link = LinkTokenInterface(_link);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress()
internal
view
returns (address)
{
return address(link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress()
internal
view
returns (address)
{
return address(oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param _oracle The address of the oracle contract that will fulfill the request
* @param _requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address _oracle, bytes32 _requestId)
internal
notPendingRequest(_requestId)
{
pendingRequests[_requestId] = _oracle;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param _ens The address of the ENS contract
* @param _node The ENS node hash
*/
function useChainlinkWithENS(address _ens, bytes32 _node)
internal
{
ens = ENSInterface(_ens);
ensNode = _node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS()
internal
{
bytes32 oracleSubnode = keccak256(abi.encodePacked(ensNode, ENS_ORACLE_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Chainlink Request
* @return The bytes payload for the `transferAndCall` method
*/
function encodeRequest(Chainlink.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
_req.id,
_req.callbackAddress,
_req.callbackFunctionId,
_req.nonce,
ARGS_VERSION,
_req.buf.buf);
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param _requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 _requestId)
internal
recordChainlinkFulfillment(_requestId)
// solhint-disable-next-line no-empty-blocks
{}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param _requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 _requestId) {
require(msg.sender == pendingRequests[_requestId],
"Source must be the oracle of the request");
delete pendingRequests[_requestId];
emit ChainlinkFulfilled(_requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param _requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 _requestId) {
require(pendingRequests[_requestId] == address(0), "Request is already pending");
_;
}
}
| 16,215 |
245 | // Converts a uint256 to its ASCII string decimal representation. / | function _toString(uint256 value) internal pure virtual returns (string memory str) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
let m := add(mload(0x40), 0xa0)
// Update the free memory pointer to allocate.
mstore(0x40, m)
// Assign the 'str' to the end.
str := sub(m, 0x20)
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// prettier-ignore
for { let temp := value } 1 {} {
str := sub(str, 1)
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing 'temp' until zero.
temp := div(temp, 10)
// prettier-ignore
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
| function _toString(uint256 value) internal pure virtual returns (string memory str) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
let m := add(mload(0x40), 0xa0)
// Update the free memory pointer to allocate.
mstore(0x40, m)
// Assign the 'str' to the end.
str := sub(m, 0x20)
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// prettier-ignore
for { let temp := value } 1 {} {
str := sub(str, 1)
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing 'temp' until zero.
temp := div(temp, 10)
// prettier-ignore
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
| 31,493 |
131 | // transfer toTokens to sender | if (toTokenAddress == address(0)) {
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
tokensRec,
affiliate,
true
);
payable(msg.sender).transfer(tokensRec - totalGoodwillPortion);
} else {
| if (toTokenAddress == address(0)) {
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
tokensRec,
affiliate,
true
);
payable(msg.sender).transfer(tokensRec - totalGoodwillPortion);
} else {
| 16,271 |
17 | // Mints the assets accrued through the reserve factor to the treasury in the form of aTokens assets The list of reserves for which the minting needs to be executed // Rescue and transfer tokens locked in this contract token The address of the token to The address of the recipient amount The amount of token to transfer / | function rescueTokens(
| function rescueTokens(
| 20,355 |
237 | // uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; | uint256 _fee = ((round_[_rID].pot) / 50).add(((round_[_rID].pot).mul(potSplit_[round_[_rID].team].p3d)) / 100);
uint256 _res = ((((round_[_rID].pot).sub(_win)).sub(_fee)).sub(_gen));
| uint256 _fee = ((round_[_rID].pot) / 50).add(((round_[_rID].pot).mul(potSplit_[round_[_rID].team].p3d)) / 100);
uint256 _res = ((((round_[_rID].pot).sub(_win)).sub(_fee)).sub(_gen));
| 24,224 |
11 | // creating new array campaign using new keyword; we can also create new address ( new address() ) [{}, {}, {}] | Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for (uint i = 0; i < allCampaigns.length; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
| Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for (uint i = 0; i < allCampaigns.length; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
| 27,523 |
72 | // Multiplier on the marginRatio for this market | Decimal.D256 marginPremium;
| Decimal.D256 marginPremium;
| 7,886 |
4 | // Check if the address has minted | require(!_hasMinted[msg.sender], "This address already minted an Anky");
| require(!_hasMinted[msg.sender], "This address already minted an Anky");
| 6,564 |
17 | // 通过Unix时间戳获取年份 | function getYear(uint timestamp) public pure returns (uint16) {
uint secondsAccountedFor = 0; // 用于累计已解析的秒数
uint16 year; // 年份变量
uint numLeapYears; // 闰年个数
// 年份
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); // 计算年份
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); // 计算起始年份到解析年份之间的闰年个数
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; // 累计闰年的秒数
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); // 累计非闰年的秒数
// 对年份进行修正
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; // 修正闰年的秒数
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS; // 修正非闰年的秒数
}
year -= 1; // 年份递减
}
return year;
}
| function getYear(uint timestamp) public pure returns (uint16) {
uint secondsAccountedFor = 0; // 用于累计已解析的秒数
uint16 year; // 年份变量
uint numLeapYears; // 闰年个数
// 年份
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); // 计算年份
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); // 计算起始年份到解析年份之间的闰年个数
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; // 累计闰年的秒数
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); // 累计非闰年的秒数
// 对年份进行修正
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; // 修正闰年的秒数
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS; // 修正非闰年的秒数
}
year -= 1; // 年份递减
}
return year;
}
| 15,283 |
107 | // risk group: 17 - APR: 7.81% | file("riskGroup", 17, ONE, 85*10**25, uint(1000000002477168949771689497), 99.79*10**25);
| file("riskGroup", 17, ONE, 85*10**25, uint(1000000002477168949771689497), 99.79*10**25);
| 40,288 |
26 | // distribute profit between all users | function _callbackFinRes(uint16 index, uint256 ltAmount, uint256 receivedAmountB, bool isProfit, uint256 finResB) internal override {
//apply operation fin res to totalcap and calculate commissions
if(isProfit){
uint256 externalCommission = finResB.mul(externalCommissionPercentNom).div(externalCommissionPercentDenom);
externalCommissionBalance = externalCommissionBalance.add(externalCommission);
uint256 userCommissionProfit = finResB.sub(externalCommission);
totalCap = totalCap.add(userCommissionProfit);
}else{
//decrease totalCap by operation loss result
//set totalCap to 1wei in case things went so bad...
totalCap = (totalCap > finResB)?totalCap.sub(finResB):1;
}
}
| function _callbackFinRes(uint16 index, uint256 ltAmount, uint256 receivedAmountB, bool isProfit, uint256 finResB) internal override {
//apply operation fin res to totalcap and calculate commissions
if(isProfit){
uint256 externalCommission = finResB.mul(externalCommissionPercentNom).div(externalCommissionPercentDenom);
externalCommissionBalance = externalCommissionBalance.add(externalCommission);
uint256 userCommissionProfit = finResB.sub(externalCommission);
totalCap = totalCap.add(userCommissionProfit);
}else{
//decrease totalCap by operation loss result
//set totalCap to 1wei in case things went so bad...
totalCap = (totalCap > finResB)?totalCap.sub(finResB):1;
}
}
| 28,701 |
211 | // bytes4(keccak256('name()')) == 0x06fdde03bytes4(keccak256('symbol()')) == 0x95d89b41bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f / | bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
| bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
| 706 |
422 | // solhint-disable-next-line not-rely-on-time |
return (getCurrentTime(), now);
|
return (getCurrentTime(), now);
| 1,731 |
5 | // : logic overview 1) Coupons just purchased will fail at 1 epoch check. 2) Valid coupons redeemed during contraction will suffer 5% penalty fee plus forgo rewarded amount 3) Valid coupons without sufficient redeemable will fail at redeemToAccount. | function redeemCoupons(uint256 couponEpoch, uint256 amount) external {
require(epoch().sub(couponEpoch) >= 1, "Market: Too early to redeem");
require(amount != 0, "Market: Amount too low");
// early redemption penalty. Coupon premium stays
if (eraStatus() != Era.Status.EXPANSION) {
uint256 penalty = amount.mul(Constants.getCouponRedemptionPenalty()).div(100);
amount = amount.sub(penalty);
decrementBalanceOfCouponUnderlying(
msg.sender,
couponEpoch,
amount,
"Market: Insufficient coupon underlying balance"
);
redeemToAccountNoBalanceCheck(msg.sender, amount);
emit EarlyCouponRedemption(msg.sender, couponEpoch, amount);
return;
}
uint256 underlyingAmount = balanceOfCouponUnderlying(msg.sender, couponEpoch);
uint256 couponAmount =
balanceOfCoupons(msg.sender, couponEpoch).mul(amount).div(underlyingAmount, "Market: No underlying");
uint256 redeemableAmount = computeRedeemable(couponEpoch, couponAmount);
decrementBalanceOfCouponUnderlying(
msg.sender,
couponEpoch,
amount,
"Market: Insufficient coupon underlying balance"
);
if (couponAmount != 0)
decrementBalanceOfCoupons(msg.sender, couponEpoch, couponAmount, "Market: Insufficient coupon balance");
redeemToAccount(msg.sender, amount, redeemableAmount);
emit CouponRedemption(msg.sender, couponEpoch, amount, couponAmount);
}
| function redeemCoupons(uint256 couponEpoch, uint256 amount) external {
require(epoch().sub(couponEpoch) >= 1, "Market: Too early to redeem");
require(amount != 0, "Market: Amount too low");
// early redemption penalty. Coupon premium stays
if (eraStatus() != Era.Status.EXPANSION) {
uint256 penalty = amount.mul(Constants.getCouponRedemptionPenalty()).div(100);
amount = amount.sub(penalty);
decrementBalanceOfCouponUnderlying(
msg.sender,
couponEpoch,
amount,
"Market: Insufficient coupon underlying balance"
);
redeemToAccountNoBalanceCheck(msg.sender, amount);
emit EarlyCouponRedemption(msg.sender, couponEpoch, amount);
return;
}
uint256 underlyingAmount = balanceOfCouponUnderlying(msg.sender, couponEpoch);
uint256 couponAmount =
balanceOfCoupons(msg.sender, couponEpoch).mul(amount).div(underlyingAmount, "Market: No underlying");
uint256 redeemableAmount = computeRedeemable(couponEpoch, couponAmount);
decrementBalanceOfCouponUnderlying(
msg.sender,
couponEpoch,
amount,
"Market: Insufficient coupon underlying balance"
);
if (couponAmount != 0)
decrementBalanceOfCoupons(msg.sender, couponEpoch, couponAmount, "Market: Insufficient coupon balance");
redeemToAccount(msg.sender, amount, redeemableAmount);
emit CouponRedemption(msg.sender, couponEpoch, amount, couponAmount);
}
| 16,104 |
230 | // transfer tokens to this contract | IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
if (!_skipRebalance) {
| IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
if (!_skipRebalance) {
| 10,468 |
297 | // orderEpoch is initialized to 0, so to cancelUpTo we need salt + 1 | uint256 newOrderEpoch = targetOrderEpoch + 1;
uint256 oldOrderEpoch = orderEpoch[makerAddress][orderSenderAddress];
| uint256 newOrderEpoch = targetOrderEpoch + 1;
uint256 oldOrderEpoch = orderEpoch[makerAddress][orderSenderAddress];
| 14,366 |
120 | // Add funds to the allocation | alloc.collectedFees = alloc.collectedFees.add(queryFees);
| alloc.collectedFees = alloc.collectedFees.add(queryFees);
| 20,640 |
32 | // Performs a Solidity function call using a low level `call`. A plain`call` is an unsafe replacement for a function call: use this function instead. If `target` reverts with a revert reason, it is bubbled up by this function (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract. - calling `target` with `data` must not revert. _Available since v3.1._/ | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| 3,341 |
11 | // uint32 id; | int64 lowerBidId; // if this outbids an older bid, otherwise -1
address payable addr;
uint amount;
string request;
| int64 lowerBidId; // if this outbids an older bid, otherwise -1
address payable addr;
uint amount;
string request;
| 9,384 |
16 | // Multi reject_addresses agreements addresses array/ | function batchRejectAgreements(address[] calldata _addresses) external onlyAdmin() {
require(_addresses.length <= 256, "FRF3");
for (uint256 i = 0; i < _addresses.length; i++) {
if (IAgreement(_addresses[i]).isBeforeStatus(IAgreement.Statuses.Active)) {
IAgreement(_addresses[i]).rejectAgreement();
removeAgreement(_addresses[i]);
}
}
}
| function batchRejectAgreements(address[] calldata _addresses) external onlyAdmin() {
require(_addresses.length <= 256, "FRF3");
for (uint256 i = 0; i < _addresses.length; i++) {
if (IAgreement(_addresses[i]).isBeforeStatus(IAgreement.Statuses.Active)) {
IAgreement(_addresses[i]).rejectAgreement();
removeAgreement(_addresses[i]);
}
}
}
| 4,890 |
86 | // Claim AAVE rewards from the Safety Module & stake them to receive stkAAVE/ | function _getStkAaveRewards() internal {
IStakedAave _stkAave = IStakedAave(STK_AAVE);
// Get pending rewards amount
uint256 pendingRewards = _stkAave.getTotalRewardsBalance(address(this));
if (pendingRewards > 0) {
// Claim the AAVE tokens
_stkAave.claimRewards(address(this), pendingRewards);
// Set a part of the claimed amount as the Reserve (protocol fees)
reserveAmount += (pendingRewards * reserveRatio) / MAX_BPS;
}
IERC20 _aave = IERC20(AAVE);
uint256 currentBalance = _aave.balanceOf(address(this));
if(currentBalance > 0) {
// Increase allowance for the Safety Module & stake AAVE into stkAAVE
_aave.safeIncreaseAllowance(STK_AAVE, currentBalance);
_stkAave.stake(address(this), currentBalance);
}
}
| function _getStkAaveRewards() internal {
IStakedAave _stkAave = IStakedAave(STK_AAVE);
// Get pending rewards amount
uint256 pendingRewards = _stkAave.getTotalRewardsBalance(address(this));
if (pendingRewards > 0) {
// Claim the AAVE tokens
_stkAave.claimRewards(address(this), pendingRewards);
// Set a part of the claimed amount as the Reserve (protocol fees)
reserveAmount += (pendingRewards * reserveRatio) / MAX_BPS;
}
IERC20 _aave = IERC20(AAVE);
uint256 currentBalance = _aave.balanceOf(address(this));
if(currentBalance > 0) {
// Increase allowance for the Safety Module & stake AAVE into stkAAVE
_aave.safeIncreaseAllowance(STK_AAVE, currentBalance);
_stkAave.stake(address(this), currentBalance);
}
}
| 38,082 |
28 | // We assume that all the tradings can be done on Sushiswap | function _liquidateReward() internal {
if (!sell()) {
// Profits can be disabled for possible simplified and rapoolId exit
emit ProfitsNotCollected(sell(), false);
return;
}
for(uint256 i = 0; i < rewardTokens.length; i++){
address token = rewardTokens[i];
uint256 rewardBalance = IERC20(token).balanceOf(address(this));
if (rewardBalance == 0 || reward2WETH[token].length < 2) {
continue;
}
if (token == cvx) {
uint256 toHodl = rewardBalance.mul(hodlRatio()).div(hodlRatioBase);
if (toHodl > 0) {
IERC20(cvx).safeTransfer(hodlVault(), toHodl);
rewardBalance = rewardBalance.sub(toHodl);
if (rewardBalance == 0) {
continue;
}
}
}
address routerV2;
if(useUni[token]) {
routerV2 = uniswapRouterV2;
} else {
routerV2 = sushiswapRouterV2;
}
IERC20(token).safeApprove(routerV2, 0);
IERC20(token).safeApprove(routerV2, rewardBalance);
// we can accept 1 as the minimum because this will be called only by a trusted worker
IUniswapV2Router02(routerV2).swapExactTokensForTokens(
rewardBalance, 1, reward2WETH[token], address(this), block.timestamp
);
}
uint256 rewardBalance = IERC20(weth).balanceOf(address(this));
notifyProfitInRewardToken(rewardBalance);
uint256 remainingRewardBalance = IERC20(rewardToken()).balanceOf(address(this));
if (remainingRewardBalance == 0) {
return;
}
address routerV2;
if(useUni[depositToken()]) {
routerV2 = uniswapRouterV2;
} else {
routerV2 = sushiswapRouterV2;
}
// allow Uniswap to sell our reward
IERC20(rewardToken()).safeApprove(routerV2, 0);
IERC20(rewardToken()).safeApprove(routerV2, remainingRewardBalance);
// we can accept 1 as minimum because this is called only by a trusted role
uint256 amountOutMin = 1;
IUniswapV2Router02(routerV2).swapExactTokensForTokens(
remainingRewardBalance,
amountOutMin,
WETH2deposit,
address(this),
block.timestamp
);
uint256 tokenBalance = IERC20(depositToken()).balanceOf(address(this));
if (tokenBalance > 0) {
depositCurve();
}
}
| function _liquidateReward() internal {
if (!sell()) {
// Profits can be disabled for possible simplified and rapoolId exit
emit ProfitsNotCollected(sell(), false);
return;
}
for(uint256 i = 0; i < rewardTokens.length; i++){
address token = rewardTokens[i];
uint256 rewardBalance = IERC20(token).balanceOf(address(this));
if (rewardBalance == 0 || reward2WETH[token].length < 2) {
continue;
}
if (token == cvx) {
uint256 toHodl = rewardBalance.mul(hodlRatio()).div(hodlRatioBase);
if (toHodl > 0) {
IERC20(cvx).safeTransfer(hodlVault(), toHodl);
rewardBalance = rewardBalance.sub(toHodl);
if (rewardBalance == 0) {
continue;
}
}
}
address routerV2;
if(useUni[token]) {
routerV2 = uniswapRouterV2;
} else {
routerV2 = sushiswapRouterV2;
}
IERC20(token).safeApprove(routerV2, 0);
IERC20(token).safeApprove(routerV2, rewardBalance);
// we can accept 1 as the minimum because this will be called only by a trusted worker
IUniswapV2Router02(routerV2).swapExactTokensForTokens(
rewardBalance, 1, reward2WETH[token], address(this), block.timestamp
);
}
uint256 rewardBalance = IERC20(weth).balanceOf(address(this));
notifyProfitInRewardToken(rewardBalance);
uint256 remainingRewardBalance = IERC20(rewardToken()).balanceOf(address(this));
if (remainingRewardBalance == 0) {
return;
}
address routerV2;
if(useUni[depositToken()]) {
routerV2 = uniswapRouterV2;
} else {
routerV2 = sushiswapRouterV2;
}
// allow Uniswap to sell our reward
IERC20(rewardToken()).safeApprove(routerV2, 0);
IERC20(rewardToken()).safeApprove(routerV2, remainingRewardBalance);
// we can accept 1 as minimum because this is called only by a trusted role
uint256 amountOutMin = 1;
IUniswapV2Router02(routerV2).swapExactTokensForTokens(
remainingRewardBalance,
amountOutMin,
WETH2deposit,
address(this),
block.timestamp
);
uint256 tokenBalance = IERC20(depositToken()).balanceOf(address(this));
if (tokenBalance > 0) {
depositCurve();
}
}
| 28,418 |
181 | // An event emitted when vesting contract address changed. | event VestingChanged(address newVesting);
| event VestingChanged(address newVesting);
| 50,498 |
13 | // Hack to get things to work automatically on OpenSea.Use transferFrom so the frontend doesn't have to worry about different method names. / | function transferFrom(
address,
address _to,
uint256 _tokenId
| function transferFrom(
address,
address _to,
uint256 _tokenId
| 5,521 |
4 | // Get balance/ return The balance of the user A SPECIAL KEYWORD prevents function from editing state variables; allows function to run locally/off blockchain | function getBalance() public view returns (uint) {
/* Get the balance of the sender of this transaction */
return balances[msg.sender];
}
| function getBalance() public view returns (uint) {
/* Get the balance of the sender of this transaction */
return balances[msg.sender];
}
| 20,396 |
52 | // calculate for votes ratio | forRatio = forRatio.mul(PPM_RESOLUTION).div(totalProposalVotes);
| forRatio = forRatio.mul(PPM_RESOLUTION).div(totalProposalVotes);
| 25,654 |
49 | // The bit position of `numberMinted` in packed address data. | uint256 private constant _BITPOS_NUMBER_MINTED = 64;
| uint256 private constant _BITPOS_NUMBER_MINTED = 64;
| 8,964 |
217 | // Migrate existing strategy to new strategy. Migrating strategy aka old and new strategy should be of same type. _old Address of strategy being migrated _new Address of new strategy / | function migrateStrategy(address _old, address _new) external onlyGovernor {
require(
IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this),
Errors.INVALID_STRATEGY
);
IPoolAccountant(poolAccountant).migrateStrategy(_old, _new);
IStrategy(_old).migrate(_new);
}
| function migrateStrategy(address _old, address _new) external onlyGovernor {
require(
IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this),
Errors.INVALID_STRATEGY
);
IPoolAccountant(poolAccountant).migrateStrategy(_old, _new);
IStrategy(_old).migrate(_new);
}
| 31,600 |
235 | // maximum number of tokens that can be early minted in a single transaction | uint256 public constant MAX_EARLY_TOKENS_PER_PURCHASE = 25;
| uint256 public constant MAX_EARLY_TOKENS_PER_PURCHASE = 25;
| 55,447 |
17 | // Skip the O(length) loop when source == dest. | if (source == dest) {
return;
}
| if (source == dest) {
return;
}
| 32,803 |
5 | // Debug Transaction Guard - A guard that will emit events with extended information./This guard is only meant as a development tool and example/Richard Meissner - <richard@gnosis.pm> | contract DebugTransactionGuard is BaseGuard {
// solhint-disable-next-line payable-fallback
fallback() external {
// We don't revert on fallback to avoid issues in case of a Safe upgrade
// E.g. The expected check method might change and then the Safe would be locked.
}
event TransactionDetails(
address indexed safe,
bytes32 indexed txHash,
address to,
uint256 value,
bytes data,
Enum.Operation operation,
uint256 safeTxGas,
bool usesRefund,
uint256 nonce
);
event GasUsage(address indexed safe, bytes32 indexed txHash, uint256 indexed nonce, bool success);
mapping(bytes32 => uint256) public txNonces;
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
// solhint-disable-next-line no-unused-vars
address payable refundReceiver,
bytes memory,
address
) external override {
uint256 nonce;
bytes32 txHash;
{
GnosisSafe safe = GnosisSafe(payable(msg.sender));
nonce = safe.nonce() - 1;
txHash = safe.getTransactionHash(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, nonce);
}
emit TransactionDetails(msg.sender, txHash, to, value, data, operation, safeTxGas, gasPrice > 0, nonce);
txNonces[txHash] = nonce;
}
function checkAfterExecution(bytes32 txHash, bool success) external override {
uint256 nonce = txNonces[txHash];
require(nonce != 0, "Could not get nonce");
txNonces[txHash] = 0;
emit GasUsage(msg.sender, txHash, nonce, success);
}
}
| contract DebugTransactionGuard is BaseGuard {
// solhint-disable-next-line payable-fallback
fallback() external {
// We don't revert on fallback to avoid issues in case of a Safe upgrade
// E.g. The expected check method might change and then the Safe would be locked.
}
event TransactionDetails(
address indexed safe,
bytes32 indexed txHash,
address to,
uint256 value,
bytes data,
Enum.Operation operation,
uint256 safeTxGas,
bool usesRefund,
uint256 nonce
);
event GasUsage(address indexed safe, bytes32 indexed txHash, uint256 indexed nonce, bool success);
mapping(bytes32 => uint256) public txNonces;
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
// solhint-disable-next-line no-unused-vars
address payable refundReceiver,
bytes memory,
address
) external override {
uint256 nonce;
bytes32 txHash;
{
GnosisSafe safe = GnosisSafe(payable(msg.sender));
nonce = safe.nonce() - 1;
txHash = safe.getTransactionHash(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, nonce);
}
emit TransactionDetails(msg.sender, txHash, to, value, data, operation, safeTxGas, gasPrice > 0, nonce);
txNonces[txHash] = nonce;
}
function checkAfterExecution(bytes32 txHash, bool success) external override {
uint256 nonce = txNonces[txHash];
require(nonce != 0, "Could not get nonce");
txNonces[txHash] = 0;
emit GasUsage(msg.sender, txHash, nonce, success);
}
}
| 16,805 |
0 | // Tabella in cui viene associato il biglietto con la propria transazione | mapping(address=>uint) tickets;
| mapping(address=>uint) tickets;
| 40,823 |
58 | // Approves another address to transfer the given token IDThe zero address indicates there is no approved address.There can only be one approved address per token at a given time.Can only be called by the token owner or an approved operator. to address to be approved for the given token ID tokenId uint256 ID of the token to be approved / | function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
| function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
| 49,815 |
241 | // if the reserve has not been initialized yet | _self.lastLiquidityCumulativeIndex = WadRayMath.ray();
| _self.lastLiquidityCumulativeIndex = WadRayMath.ray();
| 17,405 |
58 | // returns current rewards for an address / | function rewardOf(address addr) external view returns (uint256);
| function rewardOf(address addr) external view returns (uint256);
| 8,347 |
109 | // It is set right after deployment. / | function setNFTAddress(address nftAddress) public {
require(_nftAddress == address(0), "Already set");
_nftAddress = nftAddress;
}
| function setNFTAddress(address nftAddress) public {
require(_nftAddress == address(0), "Already set");
_nftAddress = nftAddress;
}
| 76,160 |
148 | // Accepts ownership transfer to the nextOwner address making it the new owner.The signer should seek approval from the current owner before calling this method. / | function acceptNextOwner() external {
require(msg.sender == nextOwner, "nextOwner does not match transaction signer.");
owner = nextOwner;
}
| function acceptNextOwner() external {
require(msg.sender == nextOwner, "nextOwner does not match transaction signer.");
owner = nextOwner;
}
| 17,971 |
17 | // 기준 brs를 set 합ㄴ디ㅏ. | function setBaseBrs(uint256 number) public onlyOwner {
require(number >= 0, "Must be greater than 0.");
_baseBrs = number;
}
| function setBaseBrs(uint256 number) public onlyOwner {
require(number >= 0, "Must be greater than 0.");
_baseBrs = number;
}
| 9,639 |
103 | // Called by owner to withdraw all funds from the lock and send them to the `beneficiary`. _amount specifies the max amount to withdraw, which may be reduced whenconsidering the available balance. Set to 0 or MAX_UINT to withdraw everything. TODO: consider allowing anybody to trigger this as long as it goes to owner anyway? -- however be wary of draining funds as it breaks the `cancelAndRefund` use case. / | function withdraw(
uint _amount
) external
onlyOwnerOrBeneficiary
| function withdraw(
uint _amount
) external
onlyOwnerOrBeneficiary
| 45,432 |
32 | // AzbitAirdrop Airdrop Smart Contract of Azbit project / | contract AzbitAirdrop is Ownable {
// ** PUBLIC STATE VARIABLES **
// Azbit token
AzbitTokenInterface public azbitToken;
// ** CONSTRUCTOR **
/**
* @dev Constructor of AzbitAirdrop Contract
* @param tokenAddress address of AzbitToken
*/
constructor(
address tokenAddress
)
public
{
_setToken(tokenAddress);
}
// ** ONLY OWNER FUNCTIONS **
/**
* @dev Send tokens to beneficiary by owner
* @param beneficiary The address for tokens withdrawal
* @param amount The token amount
*/
function sendTokens(
address beneficiary,
uint256 amount
)
external
onlyOwner
{
_sendTokens(beneficiary, amount);
}
/**
* @dev Send tokens to the array of beneficiaries by owner
* @param beneficiaries The array of addresses for tokens withdrawal
* @param amounts The array of tokens amount
*/
function sendTokensArray(
address[] beneficiaries,
uint256[] amounts
)
external
onlyOwner
{
require(beneficiaries.length == amounts.length, "array lengths have to be equal");
require(beneficiaries.length > 0, "array lengths have to be greater than zero");
for (uint256 i = 0; i < beneficiaries.length; i++) {
_sendTokens(beneficiaries[i], amounts[i]);
}
}
// ** PUBLIC VIEW FUNCTIONS **
/**
* @return total tokens of this contract.
*/
function contractTokenBalance()
public
view
returns(uint256)
{
return azbitToken.balanceOf(this);
}
// ** PRIVATE HELPER FUNCTIONS **
// Helper: Set the address of Azbit Token
function _setToken(address tokenAddress)
internal
{
azbitToken = AzbitTokenInterface(tokenAddress);
require(contractTokenBalance() >= 0, "The token being added is not ERC20 token");
}
// Helper: send tokens to beneficiary
function _sendTokens(
address beneficiary,
uint256 amount
)
internal
{
require(beneficiary != address(0), "Address cannot be 0x0");
require(amount > 0, "Amount cannot be zero");
require(amount <= contractTokenBalance(), "not enough tokens on this contract");
// transfer tokens
require(azbitToken.transfer(beneficiary, amount), "tokens are not transferred");
}
} | contract AzbitAirdrop is Ownable {
// ** PUBLIC STATE VARIABLES **
// Azbit token
AzbitTokenInterface public azbitToken;
// ** CONSTRUCTOR **
/**
* @dev Constructor of AzbitAirdrop Contract
* @param tokenAddress address of AzbitToken
*/
constructor(
address tokenAddress
)
public
{
_setToken(tokenAddress);
}
// ** ONLY OWNER FUNCTIONS **
/**
* @dev Send tokens to beneficiary by owner
* @param beneficiary The address for tokens withdrawal
* @param amount The token amount
*/
function sendTokens(
address beneficiary,
uint256 amount
)
external
onlyOwner
{
_sendTokens(beneficiary, amount);
}
/**
* @dev Send tokens to the array of beneficiaries by owner
* @param beneficiaries The array of addresses for tokens withdrawal
* @param amounts The array of tokens amount
*/
function sendTokensArray(
address[] beneficiaries,
uint256[] amounts
)
external
onlyOwner
{
require(beneficiaries.length == amounts.length, "array lengths have to be equal");
require(beneficiaries.length > 0, "array lengths have to be greater than zero");
for (uint256 i = 0; i < beneficiaries.length; i++) {
_sendTokens(beneficiaries[i], amounts[i]);
}
}
// ** PUBLIC VIEW FUNCTIONS **
/**
* @return total tokens of this contract.
*/
function contractTokenBalance()
public
view
returns(uint256)
{
return azbitToken.balanceOf(this);
}
// ** PRIVATE HELPER FUNCTIONS **
// Helper: Set the address of Azbit Token
function _setToken(address tokenAddress)
internal
{
azbitToken = AzbitTokenInterface(tokenAddress);
require(contractTokenBalance() >= 0, "The token being added is not ERC20 token");
}
// Helper: send tokens to beneficiary
function _sendTokens(
address beneficiary,
uint256 amount
)
internal
{
require(beneficiary != address(0), "Address cannot be 0x0");
require(amount > 0, "Amount cannot be zero");
require(amount <= contractTokenBalance(), "not enough tokens on this contract");
// transfer tokens
require(azbitToken.transfer(beneficiary, amount), "tokens are not transferred");
}
} | 42,950 |
20 | // Return all influencer contract addresses / | function getInfluencerContracts() external view returns(InfluencerAgreement[] memory) {
return influencerAgreements;
}
| function getInfluencerContracts() external view returns(InfluencerAgreement[] memory) {
return influencerAgreements;
}
| 31,526 |
17 | // then, add user data into the contract (tie NFT to value): - set the ID of the Capsule NFT at counter to map to the passed in tokenAddress - set the ID of the Capsule NFT at counter to map to the passed in tokenAmount | singleERC20Capsule[_capsule][id].tokenAddress = _token;
singleERC20Capsule[_capsule][id].tokenAmount = _actualAmount;
| singleERC20Capsule[_capsule][id].tokenAddress = _token;
singleERC20Capsule[_capsule][id].tokenAmount = _actualAmount;
| 14,253 |
0 | // SubContract/ | interface SubContract {
/** @dev Defines interface for reporting argument json.
@notice Defines interface for reporting argument json.
@return JSON string representing arguments.
*/
function arguments() external view returns (string memory);
/** @dev Defines interface for Kosu Order validation.
@notice Defines interface for Kosu Order validation.
@param data Kosu Order serialized based on arguments.
@return boolean representing validity of order
*/
function isValid(bytes calldata data) external view returns (bool);
/** @dev Defines interface for determining remaining amount available in Kosu order
@notice Defines interface for determining remaining amount available in Kosu order
@param data Kosu Order serialized based on arguments.
@return Number of asset available to be taken
*/
function amountRemaining(bytes calldata data) external view returns (uint);
/** @dev Defines interface to settlement of Kosu order
@notice Defines interface to settlement of Kosu order
@param data Kosu Order serialized based on arguments.
@return Number of asset successfully taken
*/
function participate(bytes calldata data) external returns (bool);
}
| interface SubContract {
/** @dev Defines interface for reporting argument json.
@notice Defines interface for reporting argument json.
@return JSON string representing arguments.
*/
function arguments() external view returns (string memory);
/** @dev Defines interface for Kosu Order validation.
@notice Defines interface for Kosu Order validation.
@param data Kosu Order serialized based on arguments.
@return boolean representing validity of order
*/
function isValid(bytes calldata data) external view returns (bool);
/** @dev Defines interface for determining remaining amount available in Kosu order
@notice Defines interface for determining remaining amount available in Kosu order
@param data Kosu Order serialized based on arguments.
@return Number of asset available to be taken
*/
function amountRemaining(bytes calldata data) external view returns (uint);
/** @dev Defines interface to settlement of Kosu order
@notice Defines interface to settlement of Kosu order
@param data Kosu Order serialized based on arguments.
@return Number of asset successfully taken
*/
function participate(bytes calldata data) external returns (bool);
}
| 27,355 |
228 | // single check is sufficient | require(getStake[msg.sender][_stakingTokenAddress] == address(0), "StakeFactory: FARM_EXISTS");
bytes memory creationCode = type(StakingRewards).creationCode;
bytes memory bytecode = abi.encodePacked(
creationCode,
abi.encode(
_stakingTokenAddress,
_rewardTokenAddresses,
_rewardsDuration,
_depositFeeBps,
_withdrawalFeesBps,
| require(getStake[msg.sender][_stakingTokenAddress] == address(0), "StakeFactory: FARM_EXISTS");
bytes memory creationCode = type(StakingRewards).creationCode;
bytes memory bytecode = abi.encodePacked(
creationCode,
abi.encode(
_stakingTokenAddress,
_rewardTokenAddresses,
_rewardsDuration,
_depositFeeBps,
_withdrawalFeesBps,
| 24,802 |
1 | // address of ERC20 and ERC721 contracts | address public tokenAddress;
address public nftAddress;
| address public tokenAddress;
address public nftAddress;
| 11,444 |
44 | // Provide an accurate expected value for the return this strategywould provide to the Vault the next time `report()` is called(since the last time it was called) / | function expectedReturn() public virtual view returns (uint256);
| function expectedReturn() public virtual view returns (uint256);
| 34,596 |
30 | // Mainnet | wrappedTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
| wrappedTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
| 32,967 |
42 | // Transfer a token from a token to another token/_fromContract The address of the owning contract/_fromTokenId The owning token/_toContract The ERC721 contract of the receiving token/_toTokenId The receiving token/_id ID of the token/_value The amount tokens to transfer | function transferAsChild(
address _fromContract,
uint256 _fromTokenId,
address _toContract,
uint256 _toTokenId,
uint256 _id,
uint256 _value
| function transferAsChild(
address _fromContract,
uint256 _fromTokenId,
address _toContract,
uint256 _toTokenId,
uint256 _id,
uint256 _value
| 10,600 |
4 | // unit (wei) | uint256 public preOrderMinAmount;
| uint256 public preOrderMinAmount;
| 47,206 |
1 | // Star struct / | struct Star {
string name;
string story;
Coordinates coordinates;
}
| struct Star {
string name;
string story;
Coordinates coordinates;
}
| 8,769 |
69 | // Used to determine if user has a valid pending withdraw request of specific tokenuser address of usertoken address of ERC20 token return true if `user` has valid withdraw request for `token`, otherwise false/ | function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
| function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
| 6,705 |
79 | // A version of `invoke()` that has one explicit signature which is used to derive the authorized/address. Uses `msg.sender` as the cosigner./v the v value for the signature; see https:github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md/r the r value for the signature/s the s value for the signature/nonce the nonce value for the signature/authorizedAddress the address of the authorization key; this is used here so that cosigner signatures are interchangeable/between this function and `invoke2()`/data The data containing the transactions to be invoked; see internalInvoke for details. | function invoke1CosignerSends(uint8 v, bytes32 r, bytes32 s, uint256 nonce, address authorizedAddress, bytes data) external {
// check signature version
require(v == 27 || v == 28, "Invalid signature version.");
// calculate hash
bytes32 operationHash = keccak256(
abi.encodePacked(
EIP191_PREFIX,
EIP191_VERSION_DATA,
this,
nonce,
authorizedAddress,
data));
// recover signer
address signer = ecrecover(operationHash, v, r, s);
// check for valid signature
require(signer != address(0), "Invalid signature.");
// check nonce
require(nonce == nonces[signer], "must use correct nonce");
// check signer
require(signer == authorizedAddress, "authorized addresses must be equal");
// Get cosigner
address requiredCosigner = address(authorizations[authVersion + uint256(signer)]);
// The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
// if the actual cosigner matches the required cosigner.
require(requiredCosigner == signer || requiredCosigner == msg.sender, "Invalid authorization.");
// increment nonce to prevent replay attacks
nonces[signer] = nonce + 1;
// call internal function
internalInvoke(operationHash, data);
}
| function invoke1CosignerSends(uint8 v, bytes32 r, bytes32 s, uint256 nonce, address authorizedAddress, bytes data) external {
// check signature version
require(v == 27 || v == 28, "Invalid signature version.");
// calculate hash
bytes32 operationHash = keccak256(
abi.encodePacked(
EIP191_PREFIX,
EIP191_VERSION_DATA,
this,
nonce,
authorizedAddress,
data));
// recover signer
address signer = ecrecover(operationHash, v, r, s);
// check for valid signature
require(signer != address(0), "Invalid signature.");
// check nonce
require(nonce == nonces[signer], "must use correct nonce");
// check signer
require(signer == authorizedAddress, "authorized addresses must be equal");
// Get cosigner
address requiredCosigner = address(authorizations[authVersion + uint256(signer)]);
// The operation should be approved if the signer address has no cosigner (i.e. signer == cosigner) or
// if the actual cosigner matches the required cosigner.
require(requiredCosigner == signer || requiredCosigner == msg.sender, "Invalid authorization.");
// increment nonce to prevent replay attacks
nonces[signer] = nonce + 1;
// call internal function
internalInvoke(operationHash, data);
}
| 6,086 |
81 | // prevent anything more than maxContributionWei per contributor address | uint256 _weiContributionAllowed = maxContributionWei > 0 ? maxContributionWei.sub(contributions[msg.sender]) : msg.value;
if (maxContributionWei > 0) {
require(_weiContributionAllowed > 0);
}
| uint256 _weiContributionAllowed = maxContributionWei > 0 ? maxContributionWei.sub(contributions[msg.sender]) : msg.value;
if (maxContributionWei > 0) {
require(_weiContributionAllowed > 0);
}
| 11,640 |
14 | // 使用并扩展ERC20接口 | contract ERC20Interface {
function totalSupply() public view returns(uint);
function balanceOf(address tokenOwner) public view returns(uint balance);
function allowance(address tokenOwner, address spender) public view returns(uint remaining);
function transfer(address to, uint tokens) public returns(bool success);
function approve(address spender, uint tokens) public returns(bool success);
function transferFrom(address from, address to, uint tokens) public returns(bool success);
uint public basisPointsRate = 0;
uint public maximumFee = 0;
uint public MAX_UINT = 2**256 - 1;
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed owner, address indexed spender, uint value);
}
| contract ERC20Interface {
function totalSupply() public view returns(uint);
function balanceOf(address tokenOwner) public view returns(uint balance);
function allowance(address tokenOwner, address spender) public view returns(uint remaining);
function transfer(address to, uint tokens) public returns(bool success);
function approve(address spender, uint tokens) public returns(bool success);
function transferFrom(address from, address to, uint tokens) public returns(bool success);
uint public basisPointsRate = 0;
uint public maximumFee = 0;
uint public MAX_UINT = 2**256 - 1;
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed owner, address indexed spender, uint value);
}
| 15,687 |
119 | // calculate claimable tad based on current state | function claimableTad(address _address) public view returns(uint){
uint stakerIndex = stakerIndexes[_address];
// if it's the first stake for user and the first stake for entire mining program, set stakerIndex as stakeInitialIndex
if (stakerIndex == 0 && totalStaked == 0) {
stakerIndex = stakeInitialIndex;
}
//else if it's the first stake for user, set stakerIndex as current miningStateIndex
if(stakerIndex == 0){
stakerIndex = miningStateIndex;
}
uint deltaIndex = miningStateIndex.sub(stakerIndex);
uint tadDelta = deltaIndex.mul(stakerPower[_address]).div(1e18);
return tadDelta;
}
| function claimableTad(address _address) public view returns(uint){
uint stakerIndex = stakerIndexes[_address];
// if it's the first stake for user and the first stake for entire mining program, set stakerIndex as stakeInitialIndex
if (stakerIndex == 0 && totalStaked == 0) {
stakerIndex = stakeInitialIndex;
}
//else if it's the first stake for user, set stakerIndex as current miningStateIndex
if(stakerIndex == 0){
stakerIndex = miningStateIndex;
}
uint deltaIndex = miningStateIndex.sub(stakerIndex);
uint tadDelta = deltaIndex.mul(stakerPower[_address]).div(1e18);
return tadDelta;
}
| 6,371 |
34 | // function to withdraw tokens, dividend and referralBalance. / | function withdraw(address contractAddress) public
| function withdraw(address contractAddress) public
| 6,355 |
0 | // An event thats emitted when the minter address is changed | event MinterChanged(address minter, address newMinter);
| event MinterChanged(address minter, address newMinter);
| 30,744 |
21 | // any other data that needs to be passed in for arbitrary function calls | bytes data;
| bytes data;
| 8,493 |
22 | // The market's last updated compBorrowIndex or compSupplyIndex | uint224 index;
| uint224 index;
| 12,312 |
59 | // You can send zero ETH to the contract address to use the faucet (added for convenience) Contract address: 0xA389d50A9D8163cbFa4145FD41f8865715A64929 | receive() external payable {
if (msg.value > 0) {
// Return ETH to sender
(bool success, ) = _msgSender().call{value: msg.value}("");
require(success, "ETH transfer failed");
}
useFaucet();
}
| receive() external payable {
if (msg.value > 0) {
// Return ETH to sender
(bool success, ) = _msgSender().call{value: msg.value}("");
require(success, "ETH transfer failed");
}
useFaucet();
}
| 62,520 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.