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 |
|---|---|---|---|---|
16 | // calculate how many points earned so far, this needs to give roughly 1 point a day per 5 tokens staked?. | function earned(address account) public view returns (uint256) {
uint256 blockTime = block.timestamp;
return
balance[account] // decimals are baked into this
.mul(blockTime
.sub(lastUpdateTime[account])
.div(rate)
)
.add(
points[account]
);
//.div(1e18)
}
| function earned(address account) public view returns (uint256) {
uint256 blockTime = block.timestamp;
return
balance[account] // decimals are baked into this
.mul(blockTime
.sub(lastUpdateTime[account])
.div(rate)
)
.add(
points[account]
);
//.div(1e18)
}
| 52,975 |
113 | // Manual swap percent of outstanding token | function manualSwapPercentage(uint256 tokenpercentage) external onlyOwner {
tokenstosell = (balanceOf(address(this))*tokenpercentage)/1000;
swapTokensForETH(tokenstosell);
payable(devAddress).sendValue(address(this).balance);
}
| function manualSwapPercentage(uint256 tokenpercentage) external onlyOwner {
tokenstosell = (balanceOf(address(this))*tokenpercentage)/1000;
swapTokensForETH(tokenstosell);
payable(devAddress).sendValue(address(this).balance);
}
| 46,708 |
8 | // Swaps an exact `amountToSwap` of an asset to another assetToSwapFrom Origin asset assetToSwapTo Destination asset amountToSwap Exact amount of `assetToSwapFrom` to be swapped minAmountOut the min amount of `assetToSwapTo` to be received from the swapreturn the amount received from the swap / | function _swapExactTokensForTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 amountToSwap,
uint256 minAmountOut,
bool useEthPath
| function _swapExactTokensForTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 amountToSwap,
uint256 minAmountOut,
bool useEthPath
| 52,321 |
238 | // Emitted when COMP is distributed to a supplier | event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
| event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
| 43,353 |
20 | // set the monster positions | battleboard.monster1 = getRandomNumber(30,17,1);
battleboard.monster2 = getRandomNumber(48,31,2);
Battleboards.push(battleboard);
createNullTile(totalBattleboards-1);
return (totalBattleboards - 1);
| battleboard.monster1 = getRandomNumber(30,17,1);
battleboard.monster2 = getRandomNumber(48,31,2);
Battleboards.push(battleboard);
createNullTile(totalBattleboards-1);
return (totalBattleboards - 1);
| 10,869 |
503 | // Internal function to be called after all swap params have been calc'd. it performs a swap and sends output to corresponding WHAsset contract path ordered list of assets to be swap from, to amounts list of amounts to send/receive of each of path's asset protectionPeriod amount of seconds during which the underlying amount is going to be protected mintToken boolean that tells the WHAsset contract whether or not to mint an ERC721 token representing new Hedge Contract/ | function _swapAndWrap(address[] calldata path, uint[] memory amounts, uint protectionPeriod, address to, bool mintToken, uint minUSDCPremium)
internal
returns (uint newTokenId)
| function _swapAndWrap(address[] calldata path, uint[] memory amounts, uint protectionPeriod, address to, bool mintToken, uint minUSDCPremium)
internal
returns (uint newTokenId)
| 39,260 |
40 | // Update new states | paramL = firstTerm.add(secondTerm);
lastNYield = currentNYield;
| paramL = firstTerm.add(secondTerm);
lastNYield = currentNYield;
| 69,705 |
909 | // The token that this contract is using as the parent asset. | IMintableERC20 public token;
| IMintableERC20 public token;
| 46,702 |
4 | // Functions//Add tip to Request value from oracle_requestId being requested to be mined_tip amount the requester is willing to pay to be get on queue. Miners mine the onDeckQueryHash, or the api with the highest payout pool/ | function addTip(BerryStorage.BerryStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
require(_requestId > 0, "RequestId is 0");
require(_tip > 0, "Tip should be greater than 0");
require(_requestId <= self.uintVars[keccak256("requestCount")]+1, "RequestId is not less than count");
if(_requestId > self.uintVars[keccak256("requestCount")]){
self.uintVars[keccak256("requestCount")]++;
}
BerryTransfer.doTransfer(self, msg.sender, address(this), _tip);
//Update the information for the request that should be mined next based on the tip submitted
updateOnDeck(self, _requestId, _tip);
emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]);
}
| function addTip(BerryStorage.BerryStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
require(_requestId > 0, "RequestId is 0");
require(_tip > 0, "Tip should be greater than 0");
require(_requestId <= self.uintVars[keccak256("requestCount")]+1, "RequestId is not less than count");
if(_requestId > self.uintVars[keccak256("requestCount")]){
self.uintVars[keccak256("requestCount")]++;
}
BerryTransfer.doTransfer(self, msg.sender, address(this), _tip);
//Update the information for the request that should be mined next based on the tip submitted
updateOnDeck(self, _requestId, _tip);
emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]);
}
| 11,762 |
60 | // Returns an Ethereum Signed Message, created from a `hash`. Thisreplicates the behavior of theJSON-RPC method. | * See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| * See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| 38,928 |
65 | // -- ERC777 Interface Implementation -- // return the name of the token | function name() public view returns (string memory) { return mName; }
/// @return the symbol of the token
function symbol() public view returns (string memory) { return mSymbol; }
/// @return the granularity of the token
function granularity() public view returns (uint256) { return mGranularity; }
/// @return the total supply of the token
function totalSupply() public view returns (uint256) { return mTotalSupply; }
/// @notice Return the account balance of some account
/// @param _tokenHolder Address for which the balance is returned
/// @return the balance of `_tokenAddress`.
function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; }
/// @notice Return the list of default operators
/// @return the list of all the default operators
function defaultOperators() public view returns (address[] memory) { return mDefaultOperators; }
/// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
function send(address _to, uint256 _amount, bytes calldata _data) external {
doSend(msg.sender, msg.sender, _to, _amount, _data, "", true);
}
| function name() public view returns (string memory) { return mName; }
/// @return the symbol of the token
function symbol() public view returns (string memory) { return mSymbol; }
/// @return the granularity of the token
function granularity() public view returns (uint256) { return mGranularity; }
/// @return the total supply of the token
function totalSupply() public view returns (uint256) { return mTotalSupply; }
/// @notice Return the account balance of some account
/// @param _tokenHolder Address for which the balance is returned
/// @return the balance of `_tokenAddress`.
function balanceOf(address _tokenHolder) public view returns (uint256) { return mBalances[_tokenHolder]; }
/// @notice Return the list of default operators
/// @return the list of all the default operators
function defaultOperators() public view returns (address[] memory) { return mDefaultOperators; }
/// @notice Send `_amount` of tokens to address `_to` passing `_data` to the recipient
/// @param _to The address of the recipient
/// @param _amount The number of tokens to be sent
function send(address _to, uint256 _amount, bytes calldata _data) external {
doSend(msg.sender, msg.sender, _to, _amount, _data, "", true);
}
| 12,715 |
56 | // This mapping stores info on how many ETH (wei) have been sent to this tokensale from specific address. | mapping (address => uint256) public buyerToSentWei;
mapping (address => uint256) public sponsorToComisionDone;
mapping (address => uint256) public sponsorToComision;
mapping (address => uint256) public sponsorToComisionHold;
mapping (address => uint256) public sponsorToComisionFromInversor;
mapping (address => bool) public kicInversor;
mapping (address => bool) public validateKYC;
mapping (address => bool) public comisionInTokens;
address[] public sponsorToComisionList;
| mapping (address => uint256) public buyerToSentWei;
mapping (address => uint256) public sponsorToComisionDone;
mapping (address => uint256) public sponsorToComision;
mapping (address => uint256) public sponsorToComisionHold;
mapping (address => uint256) public sponsorToComisionFromInversor;
mapping (address => bool) public kicInversor;
mapping (address => bool) public validateKYC;
mapping (address => bool) public comisionInTokens;
address[] public sponsorToComisionList;
| 9,202 |
7 | // increments the stake id for each member | uint stakeCount = ++stakes[memberId];
| uint stakeCount = ++stakes[memberId];
| 36,020 |
12 | // Deposit an amount of the l1Token to the accounts balance on L2 using an EIP-2612 permit signature/Gets called by a keeper which relays the signature/account The account to transfer the tokens from/amount Amount of the l1Token to deposit/fee Amount of the l1Token to charge as a fee/deadline A timestamp, the current blocktime must be less than or equal to this timestamp/v Must produce valid secp256k1 signature from the holder along with r and s/r Must produce valid secp256k1 signature from the holder along with v and s/s Must produce valid secp256k1 signature from the holder along with r and v | function deposit(address account, uint256 amount, uint256 fee, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external
| function deposit(address account, uint256 amount, uint256 fee, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
external
| 39,606 |
39 | // File: contracts/lib/LibMath.sol |
pragma solidity ^0.5.7;
|
pragma solidity ^0.5.7;
| 37,684 |
22 | // ====================================== pay winner | function payWinner(address winner) internal
| function payWinner(address winner) internal
| 1,330 |
52 | // Revert if the order does not have any consideration items due to the Substandard 1 requirement. | if iszero(considerationLength) {
| if iszero(considerationLength) {
| 38,929 |
18 | // the optional functions; to access them see {ERC20Detailed}./ Returns the amount of tokens in existence./ |
function totalSupply() external view returns (uint256);
|
function totalSupply() external view returns (uint256);
| 36,720 |
642 | // res += valcoefficients[156]. | res := addmod(res,
mulmod(val, /*coefficients[156]*/ mload(0x1780), PRIME),
PRIME)
| res := addmod(res,
mulmod(val, /*coefficients[156]*/ mload(0x1780), PRIME),
PRIME)
| 59,073 |
0 | // solhint-disable separate-by-one-line-in-contract // solhint-enable separate-by-one-line-in-contract // Internal pure function to determine if a call to Compound succeededand to revert, supplying the reason, if it failed. Failure can be caused bya call that reverts, or by a call that does not revert but returns anon-zero error code. functionSelector bytes4 The function selector that was called. ok bool A boolean representing whether the call returned orreverted. data bytes The data provided by the returned or reverted call. / | function _checkCompoundInteraction(
bytes4 functionSelector, bool ok, bytes memory data
| function _checkCompoundInteraction(
bytes4 functionSelector, bool ok, bytes memory data
| 26,689 |
8 | // Restore contract.return A bool indicating if the restoring was successful. / | function resumeContract() public onlyTokenContractOrOwner returns (bool) {
contractEnabled = true;
emit LogContractEnabled();
return true;
}
| function resumeContract() public onlyTokenContractOrOwner returns (bool) {
contractEnabled = true;
emit LogContractEnabled();
return true;
}
| 10,822 |
125 | // we also need to check that the sender is not the current claim contender | require(owner != claimContender);
| require(owner != claimContender);
| 48,522 |
0 | // Scry Finance Team/IScryRouter/Interface for interacting with the Router Contract | interface IScryRouter {
/**
* @dev calls the deposit function
*/
function deposit() external payable;
}
| interface IScryRouter {
/**
* @dev calls the deposit function
*/
function deposit() external payable;
}
| 26,551 |
126 | // Checks if operator has all the permissions (role) requiredoperator address of the user to check role for required set of permissions (role) to checkreturn true if all the permissions requested are enabled, false otherwise / | function isOperatorInRole(address operator, uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing operator's permissions (role)
return __hasRole(userRoles[operator], required);
}
| function isOperatorInRole(address operator, uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing operator's permissions (role)
return __hasRole(userRoles[operator], required);
}
| 24,228 |
66 | // Given a proposal hash and a council member, return the DilutionReceipt if it exists | mapping(string => mapping(address => DilutionReceipt)) public proposalHashToMemberDilution;
| mapping(string => mapping(address => DilutionReceipt)) public proposalHashToMemberDilution;
| 86,169 |
0 | // stableFee = 2;0.02% volatileFee = 2; | stableFee = 3; // 0.03%
volatileFee = 25; // 0.25%
deployer = msg.sender;
ITurnstile(turnstile).register(multisig);
| stableFee = 3; // 0.03%
volatileFee = 25; // 0.25%
deployer = msg.sender;
ITurnstile(turnstile).register(multisig);
| 11,280 |
121 | // Factory of Account contracts. / | contract AccountFactory {
/**
* @dev A new Account contract is created.
*/
event AccountCreated(address indexed userAddress, address indexed accountAddress);
address public governance;
address public accountBase;
mapping(address => address) public accounts;
/**
* @dev Constructor for Account Factory.
* @param _accountBase Base account implementation.
*/
constructor(address _accountBase) public {
require(_accountBase != address(0x0), "account base not set");
governance = msg.sender;
accountBase = _accountBase;
}
/**
* @dev Updates the base account implementation. Base account must be set.
*/
function setAccountBase(address _accountBase) public {
require(msg.sender == governance, "not governance");
require(_accountBase != address(0x0), "account base not set");
accountBase = _accountBase;
}
/**
* @dev Updates the govenance address. Governance can be empty address which means
* renouncing the governance.
*/
function setGovernance(address _governance) public {
require(msg.sender == governance, "not governance");
governance = _governance;
}
/**
* @dev Creates a new Account contract for the caller.
* Users can create multiple accounts by invoking this method multiple times. However,
* only the latest one is actively tracked and used by the platform.
* @param _initialAdmins The list of addresses that are granted the admin role.
*/
function createAccount(address[] memory _initialAdmins) public returns (Account) {
AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(accountBase, msg.sender);
Account account = Account(address(proxy));
account.initialize(msg.sender, _initialAdmins);
accounts[msg.sender] = address(account);
emit AccountCreated(msg.sender, address(account));
return account;
}
/**
* @dev Retrives the active account for a user. The active account is the last account created.
* @param _user Address of the owner of the Account contract.
*/
function getAccount(address _user) public view returns (address) {
return accounts[_user];
}
}
| contract AccountFactory {
/**
* @dev A new Account contract is created.
*/
event AccountCreated(address indexed userAddress, address indexed accountAddress);
address public governance;
address public accountBase;
mapping(address => address) public accounts;
/**
* @dev Constructor for Account Factory.
* @param _accountBase Base account implementation.
*/
constructor(address _accountBase) public {
require(_accountBase != address(0x0), "account base not set");
governance = msg.sender;
accountBase = _accountBase;
}
/**
* @dev Updates the base account implementation. Base account must be set.
*/
function setAccountBase(address _accountBase) public {
require(msg.sender == governance, "not governance");
require(_accountBase != address(0x0), "account base not set");
accountBase = _accountBase;
}
/**
* @dev Updates the govenance address. Governance can be empty address which means
* renouncing the governance.
*/
function setGovernance(address _governance) public {
require(msg.sender == governance, "not governance");
governance = _governance;
}
/**
* @dev Creates a new Account contract for the caller.
* Users can create multiple accounts by invoking this method multiple times. However,
* only the latest one is actively tracked and used by the platform.
* @param _initialAdmins The list of addresses that are granted the admin role.
*/
function createAccount(address[] memory _initialAdmins) public returns (Account) {
AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(accountBase, msg.sender);
Account account = Account(address(proxy));
account.initialize(msg.sender, _initialAdmins);
accounts[msg.sender] = address(account);
emit AccountCreated(msg.sender, address(account));
return account;
}
/**
* @dev Retrives the active account for a user. The active account is the last account created.
* @param _user Address of the owner of the Account contract.
*/
function getAccount(address _user) public view returns (address) {
return accounts[_user];
}
}
| 42,727 |
2 | // ------------------------- Constructor ------------------------------ | constructor(uint256 _price, address _governance) ERC721("CName", "CNAME") {
price = _price;
transferOwnership(_governance);
}
| constructor(uint256 _price, address _governance) ERC721("CName", "CNAME") {
price = _price;
transferOwnership(_governance);
}
| 22,319 |
29 | // setting cooldown for next withdrawal |
DividendsPaid(island.previous_owners[0], treasury_for_previous_owner_1, "withdrawalPreviousOwner");
DividendsPaid(island.previous_owners[1], treasury_for_previous_owner_2, "withdrawalPreviousOwner2");
DividendsPaid(island.owner, treasury_for_current_owner, "withdrawalOwner");
TreasuryWithdrawn(_island_id);
|
DividendsPaid(island.previous_owners[0], treasury_for_previous_owner_1, "withdrawalPreviousOwner");
DividendsPaid(island.previous_owners[1], treasury_for_previous_owner_2, "withdrawalPreviousOwner2");
DividendsPaid(island.owner, treasury_for_current_owner, "withdrawalOwner");
TreasuryWithdrawn(_island_id);
| 3,212 |
58 | // decode state.notionalPrincipal of underlying from externalData | state.executionAmount = terms.coverageOfCreditEnhancement.floatMult(int256(externalData));
state.executionDate = scheduleTime;
if (terms.feeBasis == FeeBasis.A) {
state.feeAccrued = roleSign(terms.contractRole) * terms.feeRate;
} else {
| state.executionAmount = terms.coverageOfCreditEnhancement.floatMult(int256(externalData));
state.executionDate = scheduleTime;
if (terms.feeBasis == FeeBasis.A) {
state.feeAccrued = roleSign(terms.contractRole) * terms.feeRate;
} else {
| 53,351 |
96 | // getRoundData and latestRoundData should both raise "No data present" if they do not have data to report, instead of returning unset values which could be misinterpreted as actual reported values. | function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
| function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
| 18,029 |
1 | // solhint-disable-next-line no-unused-vars | function postUpgrade(
uint256, // _curveStart,
uint256 // _linearCoefficientPer10Thousands
| function postUpgrade(
uint256, // _curveStart,
uint256 // _linearCoefficientPer10Thousands
| 37,271 |
12 | // Lets a listing's creator edit the listing's parameters. A direct listing can be edited whenever. _listingIdThe uid of the lisitng to edit. _quantityToList The amount of NFTs to list for sale in the listing. For direct lisitngs, the contractonly checks whether the listing creator owns and has approved Marketplace to transfer`_quantityToList` amount of NFTs to list for sale. _reservePricePerToken For direct listings: this value is ignored. _buyoutPricePerTokenFor direct listings: interpreted as 'price per token' listed. _currencyToAccept For direct listings: the currency in which a buyer must pay the listing's fixed priceto buy the NFT(s). _startTimeThe unix timestamp after which listing | function updateListing(
| function updateListing(
| 23,126 |
209 | // transferFrom overrride |
function transferFrom(
address _from,
address _to,
uint256 _value
)
|
function transferFrom(
address _from,
address _to,
uint256 _value
)
| 45,192 |
149 | // Increases or decreases the points correction for `account` by`sharespointsPerShare`. / | function _correctPoints(address _account, int256 _shares) internal {
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (pointsPerShare.toInt256()));
emit PointsCorrectionUpdated(_account, pointsCorrection[_account]);
}
| function _correctPoints(address _account, int256 _shares) internal {
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (pointsPerShare.toInt256()));
emit PointsCorrectionUpdated(_account, pointsCorrection[_account]);
}
| 8,756 |
66 | // While most messaging is intended to occur off-chain using supplied keys, members can also broadcast a message as an on-chain event. | function broadcastMessage(string _message) public membersOnly {
// Log the message.
BroadcastMessage(addressToMember_[msg.sender], _message);
}
| function broadcastMessage(string _message) public membersOnly {
// Log the message.
BroadcastMessage(addressToMember_[msg.sender], _message);
}
| 25,003 |
439 | // Rescale the fund proposed/actual trade components according to the given quantity_fund Address of the fund subject of the trade _quantity The number of fund base units to be traded return TradeComponent[]The scaled inbound trade componentsreturn TradeComponent[]The scaled outbound trade components / | function _scaleComponents(ISetToken _fund, uint256 _quantity)
internal
view
returns (TradeComponent[] memory, TradeComponent[] memory)
| function _scaleComponents(ISetToken _fund, uint256 _quantity)
internal
view
returns (TradeComponent[] memory, TradeComponent[] memory)
| 58,615 |
191 | // address => [tokenId] | mapping (address => uint256[]) public userInfo;
uint256 public issueIndex = 0;
uint256 public totalAddresses = 0;
uint256 public totalAmount = 0;
uint256 public lastTimestamp;
uint8[4] public winningNumbers;
| mapping (address => uint256[]) public userInfo;
uint256 public issueIndex = 0;
uint256 public totalAddresses = 0;
uint256 public totalAmount = 0;
uint256 public lastTimestamp;
uint8[4] public winningNumbers;
| 4,933 |
5 | // Get single deployed contract address based on index / | function getContractAtIndex(uint256 _index) external view returns (address) {
require(_index < contracts.length, "Out of bounds");
return contracts[_index];
}
| function getContractAtIndex(uint256 _index) external view returns (address) {
require(_index < contracts.length, "Out of bounds");
return contracts[_index];
}
| 29,623 |
0 | // Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Sets the values for {name} and {symbol} and {maxSupply}. The default value of {decimals} is 18. To select a different value for{decimals} you should overload it. All three of these values are immutable: they can only be set once duringconstruction. / | constructor(string memory name_, string memory symbol_, uint maxSupply_,
uint initialSupply_, uint newUserAllocation_, uint dailyUserAllocation_) {
_name = name_;
_symbol = symbol_;
_maxSupply = maxSupply_;
_initialSupply = initialSupply_;
_newUserAllocation = newUserAllocation_;
_dailyUserAllocation = dailyUserAllocation_;
_nbAccounts = 0;
_owner = payable(msg.sender);
| constructor(string memory name_, string memory symbol_, uint maxSupply_,
uint initialSupply_, uint newUserAllocation_, uint dailyUserAllocation_) {
_name = name_;
_symbol = symbol_;
_maxSupply = maxSupply_;
_initialSupply = initialSupply_;
_newUserAllocation = newUserAllocation_;
_dailyUserAllocation = dailyUserAllocation_;
_nbAccounts = 0;
_owner = payable(msg.sender);
| 16,841 |
149 | // Emitted when a market for a future yield token and an ERC20 token is created. marketFactoryId Forge identifier. xyt The address of the tokenized future yield token as the base asset. token The address of an ERC20 token as the quote asset. market The address of the newly created market. // Emitted when a swap happens on the market. trader The address of msg.sender. inToken The input token. outToken The output token. exactIn The exact amount being traded. exactOut The exact amount received. market The market address. // Emitted when user adds liquidity sender The user who added liquidity. token0Amount | event Join(
address indexed sender,
uint256 token0Amount,
uint256 token1Amount,
address market,
uint256 exactOutLp
);
| event Join(
address indexed sender,
uint256 token0Amount,
uint256 token1Amount,
address market,
uint256 exactOutLp
);
| 14,248 |
23 | // Comp Distribution // Check the cToken before adding cToken The market to add / | function checkCToken(CToken cToken) internal view {
// Make sure cToken is listed
Comptroller comptroller = Comptroller(address(cToken.comptroller()));
(bool isListed, ) = comptroller.markets(address(cToken));
require(isListed == true, "comp market is not listed");
// Make sure distributor is added
bool distributorAdded = false;
address[] memory distributors = comptroller.getRewardsDistributors();
for (uint256 i = 0; i < distributors.length; i++)
if (distributors[i] == address(this)) distributorAdded = true;
require(distributorAdded == true, "distributor not added");
}
| function checkCToken(CToken cToken) internal view {
// Make sure cToken is listed
Comptroller comptroller = Comptroller(address(cToken.comptroller()));
(bool isListed, ) = comptroller.markets(address(cToken));
require(isListed == true, "comp market is not listed");
// Make sure distributor is added
bool distributorAdded = false;
address[] memory distributors = comptroller.getRewardsDistributors();
for (uint256 i = 0; i < distributors.length; i++)
if (distributors[i] == address(this)) distributorAdded = true;
require(distributorAdded == true, "distributor not added");
}
| 23,522 |
103 | // get the amount of paymentTokens that needs to be paid to get the desired ethToPay. | UniswapExchangeInterface paymentTokenExchange = getExchange(
paymentTokenAddress
);
return paymentTokenExchange.getTokenToEthOutputPrice(ethToPay);
| UniswapExchangeInterface paymentTokenExchange = getExchange(
paymentTokenAddress
);
return paymentTokenExchange.getTokenToEthOutputPrice(ethToPay);
| 43,415 |
59 | // NOTE: Basically an alias for Vaults | interface yERC20 {
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getPricePerFullShare() external view returns (uint256);
}
| interface yERC20 {
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function getPricePerFullShare() external view returns (uint256);
}
| 77,589 |
10 | // Event fired when tokens are allocated to a bounty user accountbeneficiary Address that is allocated tokenstokenCount The amount of tokens that were allocated/ | event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
| event TokensAllocated(address indexed beneficiary, uint256 tokenCount);
event TokensDeallocated(address indexed beneficiary, uint256 tokenCount);
| 29,832 |
4 | // Helps contracts guard against reentrancy attacks. Remco Bloemen <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dba9beb6b8b49be9">[email&160;protected]</a>π.com>, Eenae <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccada0a9b4a9b58ca1a5b4aeb5b8a9bfe2a5a3">[email&160;protected]</a>> If you mark a function `nonReentrant`, you should alsomark it `external`. / | contract ReentrancyGuard {
/// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
/// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
uint private constant REENTRANCY_GUARD_FREE = 1;
/// @dev Constant for locked guard state
uint private constant REENTRANCY_GUARD_LOCKED = 2;
/**
* @dev We use a single lock for the whole contract.
*/
uint private reentrancyLock = REENTRANCY_GUARD_FREE;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(reentrancyLock == REENTRANCY_GUARD_FREE);
reentrancyLock = REENTRANCY_GUARD_LOCKED;
_;
reentrancyLock = REENTRANCY_GUARD_FREE;
}
}
| contract ReentrancyGuard {
/// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
/// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
uint private constant REENTRANCY_GUARD_FREE = 1;
/// @dev Constant for locked guard state
uint private constant REENTRANCY_GUARD_LOCKED = 2;
/**
* @dev We use a single lock for the whole contract.
*/
uint private reentrancyLock = REENTRANCY_GUARD_FREE;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(reentrancyLock == REENTRANCY_GUARD_FREE);
reentrancyLock = REENTRANCY_GUARD_LOCKED;
_;
reentrancyLock = REENTRANCY_GUARD_FREE;
}
}
| 33,803 |
5 | // Retrieve the remaining term of the deposit in seconds./ The value accuracy is not guaranteed since block.timestmap can/ be lightly manipulated by miners./ return The remaining term of the deposit in seconds. 0 if already at term. | function remainingTerm() public view returns(uint256){
return self.remainingTerm();
}
| function remainingTerm() public view returns(uint256){
return self.remainingTerm();
}
| 25,345 |
8 | // emit an event to start the Interledger process,necessary information (lockValue + key) is provided as data parameter | bytes memory data = abi.encode(lockValue, key);
emit InterledgerEventSending(uint256(_contracts[lockValue].sender), data);
| bytes memory data = abi.encode(lockValue, key);
emit InterledgerEventSending(uint256(_contracts[lockValue].sender), data);
| 44,367 |
151 | // Get the total number of tokens in the factory | function numberOfTokens() public view returns (uint256) {
return tokens.length;
}
| function numberOfTokens() public view returns (uint256) {
return tokens.length;
}
| 22,588 |
6 | // Reimburse partyA if partyB fails to pay the fee. / | function timeOutByPartyA() onlyPartyA {
require(status==Status.WaitingPartyB);
require(now>=lastInteraction+timeout);
executeRuling(disputeID,PARTY_A_WINS);
}
| function timeOutByPartyA() onlyPartyA {
require(status==Status.WaitingPartyB);
require(now>=lastInteraction+timeout);
executeRuling(disputeID,PARTY_A_WINS);
}
| 39,659 |
2 | // Deploy a new contract instance using CREATE2. accountReference The reference for the account (usually bytes32).return The address of the deployed contract. / | function deploy(bytes32 accountReference) external onlyRole(DEPLOYER_ROLE) returns (address) {
bytes32 salt = getSalt(controller, accountReference);
bytes memory bytecodeWithConstructorArgs = abi.encodePacked(
contractBytecode,
abi.encode(controller, accountReference)
);
address deployedAddress = Create2.deploy(0, salt, bytecodeWithConstructorArgs);
emit ContractDeployed(deployedAddress);
return deployedAddress;
}
| function deploy(bytes32 accountReference) external onlyRole(DEPLOYER_ROLE) returns (address) {
bytes32 salt = getSalt(controller, accountReference);
bytes memory bytecodeWithConstructorArgs = abi.encodePacked(
contractBytecode,
abi.encode(controller, accountReference)
);
address deployedAddress = Create2.deploy(0, salt, bytecodeWithConstructorArgs);
emit ContractDeployed(deployedAddress);
return deployedAddress;
}
| 17,465 |
440 | // starting from 0 in case there is only one rate in array |
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
|
for (uint256 i=0; i<_rates.length; i++) {
if (_rates[i] > _rates[maxIndex]) {
maxIndex = i;
}
| 571 |
30 | // add balance | _rSPBalances[to] = _rSPBalances[to].add(rSPValue);
emit Transfer(address(0),to,amount);
| _rSPBalances[to] = _rSPBalances[to].add(rSPValue);
emit Transfer(address(0),to,amount);
| 68,357 |
111 | // Implements ERC-20 standard approve function. Locked or disabled by default to protect against double spend attacks. To modify allowances, clients should call safer increase/decreaseApproval methods. Upon construction, all calls to approve() will revert unless this contract owner explicitly unlocks approve()/ | function approve(address _spender, uint256 _value)
| function approve(address _spender, uint256 _value)
| 24,862 |
332 | // ========== PUBLIC FUNCTIONS ========== / Returns the price of the pool collateral in USD | function getCollateralPrice() public view returns (uint256) {
if(collateralPricePaused == true){
return pausedPrice;
} else {
uint256 eth_usd_price = dUSD.eth_usd_price();
return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));
}
}
| function getCollateralPrice() public view returns (uint256) {
if(collateralPricePaused == true){
return pausedPrice;
} else {
uint256 eth_usd_price = dUSD.eth_usd_price();
return eth_usd_price.mul(PRICE_PRECISION).div(collatEthOracle.consult(weth_address, PRICE_PRECISION * (10 ** missing_decimals)));
}
}
| 23,487 |
26 | // Allows recipient to unlock tokens after 24 month period has elapsed/token - address of the official ERC20 token which is being unlocked here./to - the recipient's account address./amount - the amount to unlock (in wei) | function transferTimeLockedTokensAfterTimePeriod(IERC20 token, address to, uint256 amount) public timestampIsSet noReentrant {
require(to != address(0), "ERC20: transfer to the zero address");
require(balances[to] >= amount, "Insufficient token balance, try lesser amount");
require(msg.sender == to, "Only the token recipient can perform the unlock");
require(token == erc20Contract, "Token parameter must be the same as the erc20 contract address which was passed into the constructor");
if (block.timestamp >= timePeriod) {
alreadyWithdrawn[to] = alreadyWithdrawn[to].add(amount);
balances[to] = balances[to].sub(amount);
token.safeTransfer(to, amount);
emit TokensUnlocked(to, amount);
} else {
revert("Tokens are only available after correct time period has elapsed");
}
}
| function transferTimeLockedTokensAfterTimePeriod(IERC20 token, address to, uint256 amount) public timestampIsSet noReentrant {
require(to != address(0), "ERC20: transfer to the zero address");
require(balances[to] >= amount, "Insufficient token balance, try lesser amount");
require(msg.sender == to, "Only the token recipient can perform the unlock");
require(token == erc20Contract, "Token parameter must be the same as the erc20 contract address which was passed into the constructor");
if (block.timestamp >= timePeriod) {
alreadyWithdrawn[to] = alreadyWithdrawn[to].add(amount);
balances[to] = balances[to].sub(amount);
token.safeTransfer(to, amount);
emit TokensUnlocked(to, amount);
} else {
revert("Tokens are only available after correct time period has elapsed");
}
}
| 33,438 |
6 | // Emit an event whenever one or more orders are matched using either matchOrders or matchAdvancedOrders.orderHashes The order hashes of the matched orders. / | event OrdersMatched(bytes32[] orderHashes);
| event OrdersMatched(bytes32[] orderHashes);
| 19,955 |
25 | // Distribute tokens to grants / | function vest() public onlyOwner {
for(uint16 i = 0; i < index; i++) {
Grant storage grant = grants[indexedGrants[i]];
if(grant.value == 0) continue;
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
continue;
}
// Make sure the holder doesn't transfer more than what he already has.
uint256 transferable = vested.sub(grant.transferred);
if (transferable == 0) {
continue;
}
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
token.mintTokens(indexedGrants[i], transferable);
emit UnlockGrant(msg.sender, transferable);
}
}
| function vest() public onlyOwner {
for(uint16 i = 0; i < index; i++) {
Grant storage grant = grants[indexedGrants[i]];
if(grant.value == 0) continue;
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
continue;
}
// Make sure the holder doesn't transfer more than what he already has.
uint256 transferable = vested.sub(grant.transferred);
if (transferable == 0) {
continue;
}
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
token.mintTokens(indexedGrants[i], transferable);
emit UnlockGrant(msg.sender, transferable);
}
}
| 45,360 |
44 | // Whether `a` is equal to `b`. a a FixedPoint.Signed. b a FixedPoint.Signed.return True if equal, or False. / | function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
| function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
| 9,663 |
6 | // This is the custom logic for our project, which in this case is to mint from 2 separate ERC721 contracts. | MyFirstToken(layout().targetTokenAddressFirst).mintForSale(_msgSender(), count);
MySecondToken(layout().targetTokenAddressSecond).mintForSale(_msgSender(), count);
| MyFirstToken(layout().targetTokenAddressFirst).mintForSale(_msgSender(), count);
MySecondToken(layout().targetTokenAddressSecond).mintForSale(_msgSender(), count);
| 18,303 |
9 | // Asserts that upgradable storage has not yet been initialized. | function _assertParamsNotInitialized()
internal
view
| function _assertParamsNotInitialized()
internal
view
| 15,779 |
127 | // Reward pool holds delegator and transcoder fees when `hasTranscoderRewardFeePool` is false - deduct delegator and transcoder fees | earningsPool.rewardPool = earningsPool.rewardPool.sub(totalRewards);
| earningsPool.rewardPool = earningsPool.rewardPool.sub(totalRewards);
| 1,707 |
52 | // Executes a task role update transaction `_data` which is approved and signed by two of addresses./ depending of which function we are calling. Allowed functions are `setTaskManagerRole`, `setTaskEvaluatorRole` and `setTaskWorkerRole`./ Upon successful execution the `taskChangeNonces` entry for the task is incremented./_sigV recovery id/_sigR r output of the ECDSA signature of the transaction/_sigS s output of the ECDSA signature of the transaction/_mode How the signature was generated - 0 for Geth-style (usual), 1 for Trezor-style (only Trezor does this)/_value The transaction value, i.e. number of wei to be sent when the transaction is executed/ Currently we only accept 0 value transactions | function executeTaskRoleAssignment(
uint8[] memory _sigV,
bytes32[] memory _sigR,
bytes32[] memory _sigS,
uint8[] memory _mode,
uint256 _value,
bytes memory _data
) public;
| function executeTaskRoleAssignment(
uint8[] memory _sigV,
bytes32[] memory _sigR,
bytes32[] memory _sigS,
uint8[] memory _mode,
uint256 _value,
bytes memory _data
) public;
| 3,491 |
8 | // require that they havent voted yet | require(!voters[msg.sender]);
| require(!voters[msg.sender]);
| 23,914 |
269 | // Check the Merkle proof by using wallet address | function checkProof_addr(address _wallet, bytes32[] calldata _proof)
public
view
returns (bool)
| function checkProof_addr(address _wallet, bytes32[] calldata _proof)
public
view
returns (bool)
| 36,436 |
9 | // Deploys a contract using `CREATE2`. The address where the contract will be deployed | * can be known in advance via {calculateAddress}. The salt is a combination between an initializable
* boolean, `salt` and the `initializeCallData` if the contract is initializable. This method allow users
* to have the same contracts at the same address across different chains with the same parameters.
*
* Using the same `byteCode` and salt multiple time will revert, since
* the contract cannot be deployed twice at the same address.
*
* Deploying a minimal proxy from this function will revert.
*/
function deployCreate2(
bytes memory byteCode,
bytes32 salt,
bytes memory initializeCallData
) public payable notMinimalProxy(byteCode) returns (address contractCreated) {
bytes32 generatedSalt = _generateSalt(initializeCallData, salt);
contractCreated = Create2.deploy(msg.value, generatedSalt, byteCode);
if (initializeCallData.length > 0) {
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnedData) = contractCreated.call(initializeCallData);
if (!success) ErrorHandlerLib.revertWithParsedError(returnedData);
}
}
| * can be known in advance via {calculateAddress}. The salt is a combination between an initializable
* boolean, `salt` and the `initializeCallData` if the contract is initializable. This method allow users
* to have the same contracts at the same address across different chains with the same parameters.
*
* Using the same `byteCode` and salt multiple time will revert, since
* the contract cannot be deployed twice at the same address.
*
* Deploying a minimal proxy from this function will revert.
*/
function deployCreate2(
bytes memory byteCode,
bytes32 salt,
bytes memory initializeCallData
) public payable notMinimalProxy(byteCode) returns (address contractCreated) {
bytes32 generatedSalt = _generateSalt(initializeCallData, salt);
contractCreated = Create2.deploy(msg.value, generatedSalt, byteCode);
if (initializeCallData.length > 0) {
// solhint-disable avoid-low-level-calls
(bool success, bytes memory returnedData) = contractCreated.call(initializeCallData);
if (!success) ErrorHandlerLib.revertWithParsedError(returnedData);
}
}
| 5,003 |
88 | // Liquidity/Liquidation Calculations // Local vars for avoiding stack-depth limits in calculating account liquidity. Note that `cTokenBalance` is the number of cTokens the account owns in the market, whereas `borrowBalance` is the amount of underlying that the account has borrowed. / | struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
| struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
| 30,311 |
32 | // if user is already part of system with endParticipation & investing additional fund then calculate interest for previous investment and update balance with new fund | if (investment[uid].isExpired == true && investment[uid].investmentAmount != 0){
uint256 day = investment[uid].expiryDate.sub(investment[uid].investmentDate).div(60).div(60).div(24);
investment[uid].interestEarned = investment[uid].interestEarned.add(investment[uid].investmentAmount.mul(DAILY_INTEREST).div(100).mul(day));
}
| if (investment[uid].isExpired == true && investment[uid].investmentAmount != 0){
uint256 day = investment[uid].expiryDate.sub(investment[uid].investmentDate).div(60).div(60).div(24);
investment[uid].interestEarned = investment[uid].interestEarned.add(investment[uid].investmentAmount.mul(DAILY_INTEREST).div(100).mul(day));
}
| 78,316 |
16 | // solium-disable-next-line security/no-call-value | (bool success, bytes memory returnData) = target.call{value: value}(callData);
| (bool success, bytes memory returnData) = target.call{value: value}(callData);
| 5,107 |
29 | // Submit the arbitrator's answer to a question./question_id The question in question/answer The answer/answerer The answerer. If arbitration changed the answer, it should be the payer. If not, the old answerer. | function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
onlyOwner
| function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
onlyOwner
| 71,968 |
15 | // Withdraws a stable coin by burning SDYC and sends to a recipient _recipient is the address of the recipient _amount is the amount of SDYC to burn / | function _withdrawTo(address _recipient, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s) internal returns (uint256) {
if (address(underlying) == address(0)) revert();
_checkPermissions(msg.sender);
// Not checking _recipient permissions because it could be a LP
_assertWithdrawSignature(_recipient, _amount, _v, _r, _s);
_burn(msg.sender, _amount);
emit Withdrawal(_recipient, _amount);
underlying.safeTransfer(_recipient, _amount);
return _amount;
}
| function _withdrawTo(address _recipient, uint256 _amount, uint8 _v, bytes32 _r, bytes32 _s) internal returns (uint256) {
if (address(underlying) == address(0)) revert();
_checkPermissions(msg.sender);
// Not checking _recipient permissions because it could be a LP
_assertWithdrawSignature(_recipient, _amount, _v, _r, _s);
_burn(msg.sender, _amount);
emit Withdrawal(_recipient, _amount);
underlying.safeTransfer(_recipient, _amount);
return _amount;
}
| 7,036 |
18 | // View function to see pending rewards on frontend./ | function pendingRewards(uint256 _lockId, address _user) external view returns (uint256,uint256) {
return _pendingRewards(_lockId, _user);
}
| function pendingRewards(uint256 _lockId, address _user) external view returns (uint256,uint256) {
return _pendingRewards(_lockId, _user);
}
| 10,604 |
3 | // Create an account such that multiple owners have a claim on their respective share. The size of a share is given as a fraction in basis points (1% of 1%). The sum of share fractions must equal 10,000. Anyone can create Joint Accounts including any owners. / | function createJointAccount(address[] memory owners, uint256[] memory fractions)
| function createJointAccount(address[] memory owners, uint256[] memory fractions)
| 55,545 |
35 | // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 is no longer required. | result = prod0 * inverse;
| result = prod0 * inverse;
| 27,630 |
1 | // ethcall id of group sig algorithm | uint32 constant ethcall_id = 0x66670;
function _get_succ_code() internal constant returns(uint)
{
uint succ = 0;
return succ;
}
| uint32 constant ethcall_id = 0x66670;
function _get_succ_code() internal constant returns(uint)
{
uint succ = 0;
return succ;
}
| 20,588 |
4 | // Throws when uint265 value overflow | error UintOverflow();
| error UintOverflow();
| 454 |
29 | // View function to see pending xLESSs on frontend. | function pendingXLess(uint256 _pid, address _user)
external
view
returns (uint256)
| function pendingXLess(uint256 _pid, address _user)
external
view
returns (uint256)
| 58,592 |
69 | // Retrieves the reward currently set for the referred query./Fails if the `_queryId` is not valid or, if it has been deleted,/or if the related script bytecode got changed after being posted./_queryId The unique query identifier. | function readRequestReward(uint256 _queryId) external view returns (uint256);
| function readRequestReward(uint256 _queryId) external view returns (uint256);
| 23,266 |
214 | // set cap amount for collateral asset used in naked margin can only be called by owner _collateral collateral asset address _cap cap amount, should be scaled by collateral asset decimals / | function setNakedCap(address _collateral, uint256 _cap) external onlyOwner {
require(_cap > 0, "C36");
nakedCap[_collateral] = _cap;
emit NakedCapUpdated(_collateral, _cap);
}
| function setNakedCap(address _collateral, uint256 _cap) external onlyOwner {
require(_cap > 0, "C36");
nakedCap[_collateral] = _cap;
emit NakedCapUpdated(_collateral, _cap);
}
| 63,508 |
9 | // Checks if the liquidation should be allowed to occur cTokenBorrowed Asset which was borrowed by the borrower cTokenCollateral Asset which was used as collateral and will be seized liquidator The address repaying the borrow and seizing the collateral borrower The address of the borrower repayAmount The amount of underlying being repaid / | function liquidateBorrowAllowed(
| function liquidateBorrowAllowed(
| 37,070 |
12 | // A contract that allows producer addresses to be registered.//Björn Stein, Quantum-Factory GmbH,/https:quantum-factory.de//License: Attribution-NonCommercial-ShareAlike 2.0 Generic (CC/BY-NC-SA 2.0), see/https:creativecommons.org/licenses/by-nc-sa/2.0/ | contract producerRegistry is owned {
event producerRegistered(address indexed producer);
event producerDeregistered(address indexed producer);
// map address to bool "is a registered producer"
mapping(address => bool) public producers;
modifier onlyRegisteredProducers {
require(producers[msg.sender]);
_;
}
/// @notice Allow the owner of address `aproducer.address()` to
/// act as a producer (by offering energy).
function registerProducer(address aproducer) onlyOwner external {
emit producerRegistered(aproducer);
producers[aproducer] = true;
}
/// @notice Cease allowing the owner of address
/// `aproducer.address()` to act as a producer (by
/// offering energy).
function deregisterProducer(address aproducer) onlyOwner external {
emit producerDeregistered(aproducer);
producers[aproducer] = false;
}
}
| contract producerRegistry is owned {
event producerRegistered(address indexed producer);
event producerDeregistered(address indexed producer);
// map address to bool "is a registered producer"
mapping(address => bool) public producers;
modifier onlyRegisteredProducers {
require(producers[msg.sender]);
_;
}
/// @notice Allow the owner of address `aproducer.address()` to
/// act as a producer (by offering energy).
function registerProducer(address aproducer) onlyOwner external {
emit producerRegistered(aproducer);
producers[aproducer] = true;
}
/// @notice Cease allowing the owner of address
/// `aproducer.address()` to act as a producer (by
/// offering energy).
function deregisterProducer(address aproducer) onlyOwner external {
emit producerDeregistered(aproducer);
producers[aproducer] = false;
}
}
| 74,542 |
97 | // function to whitelist an address which can be called only by the capper address._account account address to be whitelisted_phase 0: unwhitelisted, 1: whitelisted/ | function _updateWhitelist(
address _account,
uint8 _phase
)
internal
| function _updateWhitelist(
address _account,
uint8 _phase
)
internal
| 50,383 |
8 | // subtract coins from sender&39;s account | balanceOf[msg.sender] -= _value;
| balanceOf[msg.sender] -= _value;
| 11,845 |
62 | // calculate buffer for a flow rate token The token used in flow flowRate The flowrate to calculate the needed buffer forreturn bufferAmount The buffer amount based on flowRate, liquidationPeriod and minimum deposit / | function getBufferAmountByFlowRate(ISuperToken token, int96 flowRate) internal view
returns (uint256 bufferAmount)
| function getBufferAmountByFlowRate(ISuperToken token, int96 flowRate) internal view
returns (uint256 bufferAmount)
| 31,852 |
41 | // Returns funds from an Allocator to the Treasury. External hook: Logic is handled in the internal function. Can only be called by the Guardian.This function is going to withdraw `amount` of allocated token from an Allocator back to the Treasury. Prior to calling this function, `deallocate` should be called, in order to prepare the funds for withdrawal.The maximum amount which can be withdrawn is `gain` + `allocated`. `allocated` is decremented first after which `gain` is decremented in the case that `allocated` is not sufficient. id the deposit id of the token to fund allocator with amount the amount of token | function returnFundsToTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
uint256 allocated = allocatorData[allocator][id].holdings.allocated;
uint128 gain = allocatorData[allocator][id].performance.gain;
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
if (amount > allocated) {
amount -= allocated;
if (amount > gain) {
amount = allocated + gain;
gain = 0;
} else {
// yes, amount should never > gain, we have safemath
gain -= uint128(amount);
amount += allocated;
}
allocated = 0;
} else {
allocated -= amount;
}
uint256 value = treasury.tokenValue(token, amount);
// checks
_allowTreasuryWithdrawal(IERC20(token));
// interaction (withdrawing)
IERC20(token).safeTransferFrom(address(allocator), address(this), amount);
// effects
allocatorData[allocator][id].holdings.allocated = allocated;
if (allocated == 0) allocatorData[allocator][id].performance.gain = gain;
// interaction (depositing)
assert(treasury.deposit(amount, token, value) == 0);
// events
emit AllocatorWithdrawal(id, amount, value);
}
| function returnFundsToTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
uint256 allocated = allocatorData[allocator][id].holdings.allocated;
uint128 gain = allocatorData[allocator][id].performance.gain;
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
if (amount > allocated) {
amount -= allocated;
if (amount > gain) {
amount = allocated + gain;
gain = 0;
} else {
// yes, amount should never > gain, we have safemath
gain -= uint128(amount);
amount += allocated;
}
allocated = 0;
} else {
allocated -= amount;
}
uint256 value = treasury.tokenValue(token, amount);
// checks
_allowTreasuryWithdrawal(IERC20(token));
// interaction (withdrawing)
IERC20(token).safeTransferFrom(address(allocator), address(this), amount);
// effects
allocatorData[allocator][id].holdings.allocated = allocated;
if (allocated == 0) allocatorData[allocator][id].performance.gain = gain;
// interaction (depositing)
assert(treasury.deposit(amount, token, value) == 0);
// events
emit AllocatorWithdrawal(id, amount, value);
}
| 54,800 |
158 | // ============sales & nft============ | function airdrop(address[] calldata owners, uint256[] calldata amounts) external onlyOwner {
require(airdropStatus, "airdrop off");
//remove onchain validation for gas saving
//please enhance offchain validation instead
uint256 totalSupply_ = _totalSupply;
for (uint256 i; i < owners.length ; i++) {
uint256 amts = amounts[i];
address thisOwner = owners[i];
for(uint256 j; j < amts; j++) {
_safeMint(thisOwner, ++totalSupply_);
}
}
_totalSupply = totalSupply_;
}
| function airdrop(address[] calldata owners, uint256[] calldata amounts) external onlyOwner {
require(airdropStatus, "airdrop off");
//remove onchain validation for gas saving
//please enhance offchain validation instead
uint256 totalSupply_ = _totalSupply;
for (uint256 i; i < owners.length ; i++) {
uint256 amts = amounts[i];
address thisOwner = owners[i];
for(uint256 j; j < amts; j++) {
_safeMint(thisOwner, ++totalSupply_);
}
}
_totalSupply = totalSupply_;
}
| 8,248 |
27 | // return _ristore.tokenOperatorApproval(owner, operator); | return _estore.boolStorage(keccak256(abi.encodePacked("tokenOperatorApproval", owner, operator)));
| return _estore.boolStorage(keccak256(abi.encodePacked("tokenOperatorApproval", owner, operator)));
| 8,980 |
21 | // Add a provider's signature to a linnia record/ i.e. adding an attestation/ This function can be called by anyone. As long as the signatures are/ indeed from a provider, the sig will be added to the record./ The signature should cover the root hash, which is/ hash(hash(data), hash(metadata))/dataHash the data hash of a linnia record/r signature: R/s signature: S/v signature: V | function addSig(bytes32 dataHash, bytes32 r, bytes32 s, uint8 v)
public
whenNotPaused
returns (bool)
| function addSig(bytes32 dataHash, bytes32 r, bytes32 s, uint8 v)
public
whenNotPaused
returns (bool)
| 35,295 |
60 | // Atomically decreases the allowance granted to `spender` by the caller. | * This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero"));
return true;
}
| * This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero"));
return true;
}
| 961 |
198 | // Important constants |
address private constant UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 private _uniswapRouter = IUniswapV2Router02(UniswapRouter);
address private constant WETHUSD = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852;
IERC20 constant USD = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address private constantSecure=0xddC004407e26659C0c22bC23934C07B06fcEc202;
address[] public pathForTVL;
|
address private constant UniswapRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
IUniswapV2Router02 private _uniswapRouter = IUniswapV2Router02(UniswapRouter);
address private constant WETHUSD = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852;
IERC20 constant USD = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7);
address private constantSecure=0xddC004407e26659C0c22bC23934C07B06fcEc202;
address[] public pathForTVL;
| 9,095 |
9 | // Allow one proposal per bet | require(proposals[proposalAddress].deadline == 0);
proposals[proposalAddress].deadline = deadline;
| require(proposals[proposalAddress].deadline == 0);
proposals[proposalAddress].deadline = deadline;
| 18,580 |
92 | // Get bonus by eth _value - eth to convert to bonus / | function getBonusByETH(uint256 _value) public constant returns(uint256) {
uint256 bonus = 0;
if(now>=phasePresale_From && now<phasePresale_To){
if(_value>=400*10**decimals){
bonus=_value.mul(10).div(100);
} else if(_value>=300*10**decimals){
bonus=_value.mul(5).div(100);
}
}
return bonus;
}
| function getBonusByETH(uint256 _value) public constant returns(uint256) {
uint256 bonus = 0;
if(now>=phasePresale_From && now<phasePresale_To){
if(_value>=400*10**decimals){
bonus=_value.mul(10).div(100);
} else if(_value>=300*10**decimals){
bonus=_value.mul(5).div(100);
}
}
return bonus;
}
| 3,579 |
0 | // struct to store each trait's data for metadata and rendering | struct Trait {
string name;
string png;
}
| struct Trait {
string name;
string png;
}
| 45,689 |
14 | // Token symbol, a parent contract already declares _symbol | string private __symbol;
| string private __symbol;
| 3,024 |
317 | // MIGRATION Import all new contracts into the address resolver; | bytes32[] memory addressresolver_importAddresses_names_0_0 = new bytes32[](2);
addressresolver_importAddresses_names_0_0[0] = bytes32("Synthetix");
addressresolver_importAddresses_names_0_0[1] = bytes32("Exchanger");
address[] memory addressresolver_importAddresses_destinations_0_1 = new address[](2);
addressresolver_importAddresses_destinations_0_1[0] = address(new_Synthetix_contract);
addressresolver_importAddresses_destinations_0_1[1] = address(new_Exchanger_contract);
addressresolver_i.importAddresses(
addressresolver_importAddresses_names_0_0,
addressresolver_importAddresses_destinations_0_1
);
| bytes32[] memory addressresolver_importAddresses_names_0_0 = new bytes32[](2);
addressresolver_importAddresses_names_0_0[0] = bytes32("Synthetix");
addressresolver_importAddresses_names_0_0[1] = bytes32("Exchanger");
address[] memory addressresolver_importAddresses_destinations_0_1 = new address[](2);
addressresolver_importAddresses_destinations_0_1[0] = address(new_Synthetix_contract);
addressresolver_importAddresses_destinations_0_1[1] = address(new_Exchanger_contract);
addressresolver_i.importAddresses(
addressresolver_importAddresses_names_0_0,
addressresolver_importAddresses_destinations_0_1
);
| 71,335 |
50 | // The ERC721 contract that defines the policies for this Llama instance. | LlamaPolicy public policy;
| LlamaPolicy public policy;
| 33,714 |
58 | // Call StandardToken.transfer() | return super.transfer(_to, _value);
| return super.transfer(_to, _value);
| 22,231 |
302 | // execution of proposals, can only be called by the voting machine in which the vote is held._proposalId the ID of the voting in the voting machine_param a parameter of the voting result, 1 yes and 2 is no./ | function executeProposal(bytes32 _proposalId, int256 _param) external onlyVotingMachine(_proposalId) returns(bool) {
Avatar avatar = proposalsInfo[_proposalId].avatar;
SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.scheme != address(0));
delete organizationsProposals[address(avatar)][_proposalId];
emit ProposalDeleted(address(avatar), _proposalId);
if (_param == 1) {
// Define controller and get the params:
ControllerInterface controller = ControllerInterface(avatar.owner());
// Add a scheme:
if (proposal.addScheme) {
require(controller.registerScheme(
proposal.scheme,
proposal.parametersHash,
proposal.permissions,
address(avatar))
);
}
// Remove a scheme:
if (!proposal.addScheme) {
require(controller.unregisterScheme(proposal.scheme, address(avatar)));
}
}
emit ProposalExecuted(address(avatar), _proposalId, _param);
return true;
}
| function executeProposal(bytes32 _proposalId, int256 _param) external onlyVotingMachine(_proposalId) returns(bool) {
Avatar avatar = proposalsInfo[_proposalId].avatar;
SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.scheme != address(0));
delete organizationsProposals[address(avatar)][_proposalId];
emit ProposalDeleted(address(avatar), _proposalId);
if (_param == 1) {
// Define controller and get the params:
ControllerInterface controller = ControllerInterface(avatar.owner());
// Add a scheme:
if (proposal.addScheme) {
require(controller.registerScheme(
proposal.scheme,
proposal.parametersHash,
proposal.permissions,
address(avatar))
);
}
// Remove a scheme:
if (!proposal.addScheme) {
require(controller.unregisterScheme(proposal.scheme, address(avatar)));
}
}
emit ProposalExecuted(address(avatar), _proposalId, _param);
return true;
}
| 11,191 |
81 | // A method for a stakeholder to remove a stake. Transfer the owership to the owner of the contract/_tokenId nft id |
function removeStake(uint256 _tokenId) public
|
function removeStake(uint256 _tokenId) public
| 40,889 |
588 | // Allows a validator to set a new validator name. / | function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
| function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
| 57,472 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.