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
|
---|---|---|---|---|
252 | // Update funds received for PoolFDTs. | updateFundsReceived();
_emitBalanceUpdatedEvent();
emit BalanceUpdated(stakeLocker, address(liquidityAsset), liquidityAsset.balanceOf(stakeLocker));
emit Claim(loan, interestClaim, principalClaim, claimInfo[3], stakeLockerPortion, poolDelegatePortion);
| updateFundsReceived();
_emitBalanceUpdatedEvent();
emit BalanceUpdated(stakeLocker, address(liquidityAsset), liquidityAsset.balanceOf(stakeLocker));
emit Claim(loan, interestClaim, principalClaim, claimInfo[3], stakeLockerPortion, poolDelegatePortion);
| 42,112 |
4 | // The owner address whose account will be modified | address owner;
| address owner;
| 30,150 |
12 | // Admin errors/Royalty percentage too high | error Setup_RoyaltyPercentageTooHigh(uint16 maxRoyaltyBPS);
| error Setup_RoyaltyPercentageTooHigh(uint16 maxRoyaltyBPS);
| 8,895 |
212 | // Set weth address | weth = uniswapRouter.WETH();
| weth = uniswapRouter.WETH();
| 49,171 |
194 | // How much of the staking tax should be allocated for marketing | function TeamChangeMarketingShare(uint8 newShare) public onlyTeam{
marketingShare=newShare;
}
| function TeamChangeMarketingShare(uint8 newShare) public onlyTeam{
marketingShare=newShare;
}
| 70,486 |
2 | // Enter the Compound market to provide liquidity | function _enterMarkets() internal {
address[] memory cTokens = new address[](1);
cTokens[0] = address(_cToken);
uint256[] memory errors = _comptroller.enterMarkets(cTokens);
if (errors[0] != 0) {
revert("Comptroller.enterMarkets Error");
}
}
| function _enterMarkets() internal {
address[] memory cTokens = new address[](1);
cTokens[0] = address(_cToken);
uint256[] memory errors = _comptroller.enterMarkets(cTokens);
if (errors[0] != 0) {
revert("Comptroller.enterMarkets Error");
}
}
| 47,807 |
334 | // Add mappings for any new markets that have been added to factorysince the last time this method was called / | function populateMarkets() external {
populateMarketsUntil(factory.numMarkets());
}
| function populateMarkets() external {
populateMarketsUntil(factory.numMarkets());
}
| 16,748 |
0 | // modify token name | string public constant NAME = "Token";
| string public constant NAME = "Token";
| 45,906 |
107 | // helper to set vBRIGHT contract address_onlyOwner available / | function setVBRIGHTAddress(address vBRIGHTAddress) public _onlyOwner {
_vBRIGHTAddress = vBRIGHTAddress;
_vBRIGHTToken = IERC20(_vBRIGHTAddress);
}
| function setVBRIGHTAddress(address vBRIGHTAddress) public _onlyOwner {
_vBRIGHTAddress = vBRIGHTAddress;
_vBRIGHTToken = IERC20(_vBRIGHTAddress);
}
| 6,161 |
157 | // Update state for remove_liquidity | tranche_interest_earned[epoch][uint256(Tranche.S)] = wind_down.tranche_S_interest;
tranche_interest_earned[epoch][uint256(Tranche.AA)] = 0;
tranche_interest_earned[epoch][uint256(Tranche.A)] = wind_down.tranche_A_interest;
| tranche_interest_earned[epoch][uint256(Tranche.S)] = wind_down.tranche_S_interest;
tranche_interest_earned[epoch][uint256(Tranche.AA)] = 0;
tranche_interest_earned[epoch][uint256(Tranche.A)] = wind_down.tranche_A_interest;
| 7,842 |
37 | // Only manufacturer | onlyVerifier()
| onlyVerifier()
| 19,914 |
18 | // Check if Deposit was correctly donepalPool address of PalPooldest address to send the minted palTokensamount amount of palTokens minted return bool : Verification Success/ | function depositVerify(address palPool, address dest, uint amount) external view override returns(bool){
require(isPalPool(msg.sender), "Call not allowed");
palPool;
dest;
amount;
//Check the amount sent isn't null
return amount > 0;
}
| function depositVerify(address palPool, address dest, uint amount) external view override returns(bool){
require(isPalPool(msg.sender), "Call not allowed");
palPool;
dest;
amount;
//Check the amount sent isn't null
return amount > 0;
}
| 14,784 |
15 | // bool changed; | uint16 executorApplication;
uint8 budgetCount;
uint16 applicationCount;
uint8 submissionCount;
| uint16 executorApplication;
uint8 budgetCount;
uint16 applicationCount;
uint8 submissionCount;
| 26,591 |
256 | // string memory strImages = string(abi.encodePacked('<svg xmlns="http:www.w3.org/2000/svg" width="', Base64.uint2str(size) ,'" height="', Base64.uint2str(size) ,'">')); | uint256[9] memory baseAtt = dd.getBaseAttributues(tokenId);
for(uint256 i = 0; i < dd.traitCount(); i++){
if(i < 9){
(string memory attributeName, string memory attributeValue, string memory attributeURI, string memory breedOverride, bool active) = dd.getUriValues(i, baseAtt[i], baseAtt[2]);
if(bytes(attributeValue).length > 0 && active == true){
| uint256[9] memory baseAtt = dd.getBaseAttributues(tokenId);
for(uint256 i = 0; i < dd.traitCount(); i++){
if(i < 9){
(string memory attributeName, string memory attributeValue, string memory attributeURI, string memory breedOverride, bool active) = dd.getUriValues(i, baseAtt[i], baseAtt[2]);
if(bytes(attributeValue).length > 0 && active == true){
| 47,617 |
2 | // the block difficulty | uint difficulty = block.difficulty;
| uint difficulty = block.difficulty;
| 23,855 |
1 | // Remark by service provider. If any parts were changed or not or other info. | string remark;
| string remark;
| 17,902 |
14 | // Change action contract address for new event output format. / | function changeActionContract(address _newActionContractAddress) external isWorker {
require(_newActionContractAddress != address(0), "Zero address for new action contract");
actionContractAddress = _newActionContractAddress;
}
| function changeActionContract(address _newActionContractAddress) external isWorker {
require(_newActionContractAddress != address(0), "Zero address for new action contract");
actionContractAddress = _newActionContractAddress;
}
| 35,637 |
15 | // Mapping from: swap address -> user -> swap_balances index | mapping(address => mapping(address => uint)) swap_balances_index;
| mapping(address => mapping(address => uint)) swap_balances_index;
| 49,908 |
28 | // Return an identical view with a different type. memView The view _newTypeThe new typereturnnewView - The new view with the specified type / | function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) {
// then | in the new type
assembly {
// solhint-disable-previous-line no-inline-assembly
// shift off the top 5 bytes
newView := or(and(memView, LOW_27_BYTES_MASK), shl(_27_BYTES_IN_BITS, _newType))
}
}
| function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) {
// then | in the new type
assembly {
// solhint-disable-previous-line no-inline-assembly
// shift off the top 5 bytes
newView := or(and(memView, LOW_27_BYTES_MASK), shl(_27_BYTES_IN_BITS, _newType))
}
}
| 30,295 |
67 | // Contract should have enough Parsec credits | require(parsecToken.balanceOf(this) >= MINIMAL_AMOUNT_OF_PARSECS);
| require(parsecToken.balanceOf(this) >= MINIMAL_AMOUNT_OF_PARSECS);
| 9,577 |
84 | // This function returns the signature of configure functionreturn bytes4 Configure function signature / | function getInitFunction() public pure returns (bytes4) {
return bytes4(keccak256("configure(uint256,uint256,uint256[],uint256[],uint256[],uint256[],uint256,uint256,uint8[],address,address)"));
}
| function getInitFunction() public pure returns (bytes4) {
return bytes4(keccak256("configure(uint256,uint256,uint256[],uint256[],uint256[],uint256[],uint256,uint256,uint8[],address,address)"));
}
| 40,194 |
10 | // Internal function that refunds an amount of reserve token for the given tokens.The given tokens are burned. / | function _sell(uint tenderAmount) internal {
require(tenderAmount > 0, "Tendered amount must be greater than zero");
require(token.balanceOf(msg.sender) >= tenderAmount, "Insufficient tokens to sell");
uint refundAmount = calculateRefundAmount(tenderAmount);
token.burn(msg.sender, tenderAmount);
payable(msg.sender).transfer(refundAmount);
reserveBalance -= refundAmount;
}
| function _sell(uint tenderAmount) internal {
require(tenderAmount > 0, "Tendered amount must be greater than zero");
require(token.balanceOf(msg.sender) >= tenderAmount, "Insufficient tokens to sell");
uint refundAmount = calculateRefundAmount(tenderAmount);
token.burn(msg.sender, tenderAmount);
payable(msg.sender).transfer(refundAmount);
reserveBalance -= refundAmount;
}
| 39,958 |
16 | // Thrown on attempting to add a token that is already in a collateral list | error TokenAlreadyAddedException();
| error TokenAlreadyAddedException();
| 20,229 |
56 | // Returns the latest price / | function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
| function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
return price;
}
| 6,564 |
103 | // Hardcode the River's approval so that users don't have to waste gas approving | if (_msgSender() != address(river))
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
| if (_msgSender() != address(river))
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
| 68,767 |
98 | // Update the status of a proposal (and get a reward, if updated)proposalId The ID of a proposal/ | function updateProposalStatus(uint256 proposalId) external;
| function updateProposalStatus(uint256 proposalId) external;
| 47,824 |
169 | // Resolves asset implementation contract for the caller and forwards there arguments along withthe caller address. return success. / | function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
| function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
| 45,456 |
2 | // op is uint8 | uint8 internal constant OP_TYPE_BYTES = 1;
| uint8 internal constant OP_TYPE_BYTES = 1;
| 6,724 |
83 | // See {IERC721Enumerable-totalSupply}. / | function totalSupply() public view override returns (uint256) {
return currentIndex;
}
| function totalSupply() public view override returns (uint256) {
return currentIndex;
}
| 1,337 |
146 | // Level pair | _keys[1] = keccak256(abi.encodePacked(_tokenId, "level"));
_values[1] = 1;
| _keys[1] = keccak256(abi.encodePacked(_tokenId, "level"));
_values[1] = 1;
| 43,780 |
41 | // Return Wrapped ETH address / | address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
| address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
| 18,745 |
75 | // include the signers in the salt so any contract deployed to a given address must have the same signers | bytes32 finalSalt = keccak256(abi.encodePacked(allowedSigners, salt));
address payable clone = createClone(implementationAddress, finalSalt);
WalletSimple(clone).init(allowedSigners);
emit WalletCreated(clone, allowedSigners);
| bytes32 finalSalt = keccak256(abi.encodePacked(allowedSigners, salt));
address payable clone = createClone(implementationAddress, finalSalt);
WalletSimple(clone).init(allowedSigners);
emit WalletCreated(clone, allowedSigners);
| 1,454 |
2 | // Sub instance should override this to set `from` for transaction/ return account The address for the contract wallet, also the/ `msg.sender` address which send the transaction. | function getAccountAddress() external view returns (address account);
function roleManager() external view returns (address _roleManager);
function authorizer() external view returns (address _authorizer);
| function getAccountAddress() external view returns (address account);
function roleManager() external view returns (address _roleManager);
function authorizer() external view returns (address _authorizer);
| 23,009 |
3 | // ========== EVENTS ========== | event Staked(
address indexed user,
uint256 indexed catId,
uint256 boostRate,
uint256 unlockTime
);
event Unstaked(
address indexed user,
uint256 indexed catId,
| event Staked(
address indexed user,
uint256 indexed catId,
uint256 boostRate,
uint256 unlockTime
);
event Unstaked(
address indexed user,
uint256 indexed catId,
| 35,237 |
24 | // Opens a new leveraged liquidity position; swaps cUSD for specified assetLeveragedLiquidityPositionManager checks if tokens are supportedLeveragedLiquidityPositionManager checks if farmAddress is supportedtokenA Address of first token in pairtokenB Address of second token in paircollateral Amount of cUSD to use as collateralamountToBorrow Amount of cUSD to borrowfarmAddress Address of token pair's Ubeswap farm/ | function openLeveragedLiquidityPosition(address tokenA, address tokenB, uint collateral, uint amountToBorrow, address farmAddress) external;
| function openLeveragedLiquidityPosition(address tokenA, address tokenB, uint collateral, uint amountToBorrow, address farmAddress) external;
| 40,656 |
91 | // Max profit coefficient contract will pay to user in ppm, cannot be lower 100 000 (10%) | uint256 public profitCoefficient;
| uint256 public profitCoefficient;
| 37,146 |
83 | // Approve the passed address to spend the specified amount of tokens on behalf of msg.senderand then call `onApprovalReceived` on spender.Beware that changing an allowance with this method brings the risk that someone may use both the oldand the new allowance by unfortunate transaction ordering. One possible solution to mitigate thisrace condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: spender address The address which will spend the funds amount uint256 The amount of tokens to be spent / | function approveAndCall(address spender, uint256 amount) external returns (bool);
| function approveAndCall(address spender, uint256 amount) external returns (bool);
| 2,137 |
81 | // CAKE tokens created per block. | uint256 public rewardPerBlock;
| uint256 public rewardPerBlock;
| 18,371 |
66 | // BsktToken/Bskt tokens are transferable, and can be created and redeemed by/ anyone. To create, a user must approve the contract to move the underlying/ tokens, then call `create`./CryptoFin | contract BsktToken is StandardToken, DetailedERC20, Pausable, ReentrancyGuard {
using SafeMath for uint256;
using AddressArrayUtils for address[];
struct TokenInfo {
address addr;
uint256 quantity;
}
uint256 public creationUnit;
TokenInfo[] public tokens;
event Create(address indexed creator, uint256 amount);
event Redeem(address indexed redeemer, uint256 amount, address[] skippedTokens);
/// @notice Requires value to be divisible by creationUnit
/// @param value Number to be checked
modifier requireMultiple(uint256 value) {
require((value % creationUnit) == 0);
_;
}
/// @notice Requires value to be non-zero
/// @param value Number to be checked
modifier requireNonZero(uint256 value) {
require(value > 0);
_;
}
/// @notice Initializes contract with a list of ERC20 token addresses and
/// corresponding minimum number of units required for a creation unit
/// @param addresses Addresses of the underlying ERC20 token contracts
/// @param quantities Number of token base units required per creation unit
/// @param _creationUnit Number of base units per creation unit
function BsktToken(
address[] addresses,
uint256[] quantities,
uint256 _creationUnit,
string _name,
string _symbol
) DetailedERC20(_name, _symbol, 18) public {
require(addresses.length > 0);
require(addresses.length == quantities.length);
require(_creationUnit >= 1);
for (uint256 i = 0; i < addresses.length; i++) {
tokens.push(TokenInfo({
addr: addresses[i],
quantity: quantities[i]
}));
}
creationUnit = _creationUnit;
name = _name;
symbol = _symbol;
}
/// @notice Creates Bskt tokens in exchange for underlying tokens. Before
/// calling, underlying tokens must be approved to be moved by the Bskt
/// contract. The number of approved tokens required depends on baseUnits.
/// @dev If any underlying tokens' `transferFrom` fails (eg. the token is
/// frozen), create will no longer work. At this point a token upgrade will
/// be necessary.
/// @param baseUnits Number of base units to create. Must be a multiple of
/// creationUnit.
function create(uint256 baseUnits)
external
whenNotPaused()
requireNonZero(baseUnits)
requireMultiple(baseUnits)
{
// Check overflow
require((totalSupply_ + baseUnits) > totalSupply_);
for (uint256 i = 0; i < tokens.length; i++) {
TokenInfo memory token = tokens[i];
ERC20 erc20 = ERC20(token.addr);
uint256 amount = baseUnits.div(creationUnit).mul(token.quantity);
require(erc20.transferFrom(msg.sender, address(this), amount));
}
mint(msg.sender, baseUnits);
emit Create(msg.sender, baseUnits);
}
/// @notice Redeems Bskt tokens in exchange for underlying tokens
/// @param baseUnits Number of base units to redeem. Must be a multiple of
/// creationUnit.
/// @param tokensToSkip Underlying token addresses to skip redemption for.
/// Intended to be used to skip frozen or broken tokens which would prevent
/// all underlying tokens from being withdrawn due to a revert. Skipped
/// tokens are left in the Bskt contract and are unclaimable.
function redeem(uint256 baseUnits, address[] tokensToSkip)
external
requireNonZero(baseUnits)
requireMultiple(baseUnits)
{
require(baseUnits <= totalSupply_);
require(baseUnits <= balances[msg.sender]);
require(tokensToSkip.length <= tokens.length);
// Total supply check not required since a user would have to have
// balance greater than the total supply
// Burn before to prevent re-entrancy
burn(msg.sender, baseUnits);
for (uint256 i = 0; i < tokens.length; i++) {
TokenInfo memory token = tokens[i];
ERC20 erc20 = ERC20(token.addr);
uint256 index;
bool ok;
(index, ok) = tokensToSkip.index(token.addr);
if (ok) {
continue;
}
uint256 amount = baseUnits.div(creationUnit).mul(token.quantity);
require(erc20.transfer(msg.sender, amount));
}
emit Redeem(msg.sender, baseUnits, tokensToSkip);
}
/// @return addresses Underlying token addresses
function tokenAddresses() external view returns (address[]){
address[] memory addresses = new address[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
addresses[i] = tokens[i].addr;
}
return addresses;
}
/// @return quantities Number of token base units required per creation unit
function tokenQuantities() external view returns (uint256[]){
uint256[] memory quantities = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
quantities[i] = tokens[i].quantity;
}
return quantities;
}
// @dev Mints new Bskt tokens
// @param to Address to mint to
// @param amount Amount to mint
// @return ok Whether the operation was successful
function mint(address to, uint256 amount) internal returns (bool) {
totalSupply_ = totalSupply_.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
return true;
}
// @dev Burns Bskt tokens
// @param from Address to burn from
// @param amount Amount to burn
// @return ok Whether the operation was successful
function burn(address from, uint256 amount) internal returns (bool) {
totalSupply_ = totalSupply_.sub(amount);
balances[from] = balances[from].sub(amount);
emit Transfer(from, address(0), amount);
return true;
}
// @notice Look up token quantity and whether token exists
// @param token Token address to look up
// @return (quantity, ok) Units of underlying token, and whether the
// token was found
function getQuantity(address token) internal view returns (uint256, bool) {
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i].addr == token) {
return (tokens[i].quantity, true);
}
}
return (0, false);
}
/// @notice Owner: Withdraw excess funds which don't belong to Bskt token
/// holders
/// @param token ERC20 token address to withdraw
function withdrawExcessToken(address token)
external
onlyOwner
nonReentrant
{
ERC20 erc20 = ERC20(token);
uint256 withdrawAmount;
uint256 amountOwned = erc20.balanceOf(address(this));
uint256 quantity;
bool ok;
(quantity, ok) = getQuantity(token);
if (ok) {
withdrawAmount = amountOwned.sub(
totalSupply_.div(creationUnit).mul(quantity)
);
} else {
withdrawAmount = amountOwned;
}
require(erc20.transfer(owner, withdrawAmount));
}
/// @dev Prevent Bskt tokens from being sent to the Bskt contract
/// @param _to The address to transfer tokens to
/// @param _value the amount of tokens to be transferred
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(this));
return super.transfer(_to, _value);
}
/// @dev Prevent Bskt tokens from being sent to the Bskt contract
/// @param _from The address to transfer tokens from
/// @param _to The address to transfer to
/// @param _value The amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(this));
return super.transferFrom(_from, _to, _value);
}
} | contract BsktToken is StandardToken, DetailedERC20, Pausable, ReentrancyGuard {
using SafeMath for uint256;
using AddressArrayUtils for address[];
struct TokenInfo {
address addr;
uint256 quantity;
}
uint256 public creationUnit;
TokenInfo[] public tokens;
event Create(address indexed creator, uint256 amount);
event Redeem(address indexed redeemer, uint256 amount, address[] skippedTokens);
/// @notice Requires value to be divisible by creationUnit
/// @param value Number to be checked
modifier requireMultiple(uint256 value) {
require((value % creationUnit) == 0);
_;
}
/// @notice Requires value to be non-zero
/// @param value Number to be checked
modifier requireNonZero(uint256 value) {
require(value > 0);
_;
}
/// @notice Initializes contract with a list of ERC20 token addresses and
/// corresponding minimum number of units required for a creation unit
/// @param addresses Addresses of the underlying ERC20 token contracts
/// @param quantities Number of token base units required per creation unit
/// @param _creationUnit Number of base units per creation unit
function BsktToken(
address[] addresses,
uint256[] quantities,
uint256 _creationUnit,
string _name,
string _symbol
) DetailedERC20(_name, _symbol, 18) public {
require(addresses.length > 0);
require(addresses.length == quantities.length);
require(_creationUnit >= 1);
for (uint256 i = 0; i < addresses.length; i++) {
tokens.push(TokenInfo({
addr: addresses[i],
quantity: quantities[i]
}));
}
creationUnit = _creationUnit;
name = _name;
symbol = _symbol;
}
/// @notice Creates Bskt tokens in exchange for underlying tokens. Before
/// calling, underlying tokens must be approved to be moved by the Bskt
/// contract. The number of approved tokens required depends on baseUnits.
/// @dev If any underlying tokens' `transferFrom` fails (eg. the token is
/// frozen), create will no longer work. At this point a token upgrade will
/// be necessary.
/// @param baseUnits Number of base units to create. Must be a multiple of
/// creationUnit.
function create(uint256 baseUnits)
external
whenNotPaused()
requireNonZero(baseUnits)
requireMultiple(baseUnits)
{
// Check overflow
require((totalSupply_ + baseUnits) > totalSupply_);
for (uint256 i = 0; i < tokens.length; i++) {
TokenInfo memory token = tokens[i];
ERC20 erc20 = ERC20(token.addr);
uint256 amount = baseUnits.div(creationUnit).mul(token.quantity);
require(erc20.transferFrom(msg.sender, address(this), amount));
}
mint(msg.sender, baseUnits);
emit Create(msg.sender, baseUnits);
}
/// @notice Redeems Bskt tokens in exchange for underlying tokens
/// @param baseUnits Number of base units to redeem. Must be a multiple of
/// creationUnit.
/// @param tokensToSkip Underlying token addresses to skip redemption for.
/// Intended to be used to skip frozen or broken tokens which would prevent
/// all underlying tokens from being withdrawn due to a revert. Skipped
/// tokens are left in the Bskt contract and are unclaimable.
function redeem(uint256 baseUnits, address[] tokensToSkip)
external
requireNonZero(baseUnits)
requireMultiple(baseUnits)
{
require(baseUnits <= totalSupply_);
require(baseUnits <= balances[msg.sender]);
require(tokensToSkip.length <= tokens.length);
// Total supply check not required since a user would have to have
// balance greater than the total supply
// Burn before to prevent re-entrancy
burn(msg.sender, baseUnits);
for (uint256 i = 0; i < tokens.length; i++) {
TokenInfo memory token = tokens[i];
ERC20 erc20 = ERC20(token.addr);
uint256 index;
bool ok;
(index, ok) = tokensToSkip.index(token.addr);
if (ok) {
continue;
}
uint256 amount = baseUnits.div(creationUnit).mul(token.quantity);
require(erc20.transfer(msg.sender, amount));
}
emit Redeem(msg.sender, baseUnits, tokensToSkip);
}
/// @return addresses Underlying token addresses
function tokenAddresses() external view returns (address[]){
address[] memory addresses = new address[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
addresses[i] = tokens[i].addr;
}
return addresses;
}
/// @return quantities Number of token base units required per creation unit
function tokenQuantities() external view returns (uint256[]){
uint256[] memory quantities = new uint256[](tokens.length);
for (uint256 i = 0; i < tokens.length; i++) {
quantities[i] = tokens[i].quantity;
}
return quantities;
}
// @dev Mints new Bskt tokens
// @param to Address to mint to
// @param amount Amount to mint
// @return ok Whether the operation was successful
function mint(address to, uint256 amount) internal returns (bool) {
totalSupply_ = totalSupply_.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
return true;
}
// @dev Burns Bskt tokens
// @param from Address to burn from
// @param amount Amount to burn
// @return ok Whether the operation was successful
function burn(address from, uint256 amount) internal returns (bool) {
totalSupply_ = totalSupply_.sub(amount);
balances[from] = balances[from].sub(amount);
emit Transfer(from, address(0), amount);
return true;
}
// @notice Look up token quantity and whether token exists
// @param token Token address to look up
// @return (quantity, ok) Units of underlying token, and whether the
// token was found
function getQuantity(address token) internal view returns (uint256, bool) {
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i].addr == token) {
return (tokens[i].quantity, true);
}
}
return (0, false);
}
/// @notice Owner: Withdraw excess funds which don't belong to Bskt token
/// holders
/// @param token ERC20 token address to withdraw
function withdrawExcessToken(address token)
external
onlyOwner
nonReentrant
{
ERC20 erc20 = ERC20(token);
uint256 withdrawAmount;
uint256 amountOwned = erc20.balanceOf(address(this));
uint256 quantity;
bool ok;
(quantity, ok) = getQuantity(token);
if (ok) {
withdrawAmount = amountOwned.sub(
totalSupply_.div(creationUnit).mul(quantity)
);
} else {
withdrawAmount = amountOwned;
}
require(erc20.transfer(owner, withdrawAmount));
}
/// @dev Prevent Bskt tokens from being sent to the Bskt contract
/// @param _to The address to transfer tokens to
/// @param _value the amount of tokens to be transferred
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(this));
return super.transfer(_to, _value);
}
/// @dev Prevent Bskt tokens from being sent to the Bskt contract
/// @param _from The address to transfer tokens from
/// @param _to The address to transfer to
/// @param _value The amount of tokens to be transferred
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(this));
return super.transferFrom(_from, _to, _value);
}
} | 23,546 |
32 | // User Liquidate | function liquidateBorrow(
address borrower,
address underlyingBorrow,
address underlyingCollateral,
uint256 repayAmount
| function liquidateBorrow(
address borrower,
address underlyingBorrow,
address underlyingCollateral,
uint256 repayAmount
| 51,138 |
58 | // INTERNAL FUNCTIONS/ | {
// accept the new register
airlines[newAirlineAddress].isRegistered = true;
numberOfRegisteredAirlines = numberOfRegisteredAirlines.add(1);
_voteDone(newAirlineAddress);
emit AirlineRegistered(newAirlineAddress);
}
| {
// accept the new register
airlines[newAirlineAddress].isRegistered = true;
numberOfRegisteredAirlines = numberOfRegisteredAirlines.add(1);
_voteDone(newAirlineAddress);
emit AirlineRegistered(newAirlineAddress);
}
| 48,556 |
19 | // Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:spender The address which will spend the funds.value The amount of tokens to be spent. / | function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| 25,096 |
71 | // Minter constructor _inflation Base inflation rate as a percentage of current total token supply _inflationChange Change in inflation rate each round (increase or decrease) if target bonding rate is not achieved _targetBondingRate Target bonding rate as a percentage of total bonded tokens / total token supply / | function Minter(address _controller, uint256 _inflation, uint256 _inflationChange, uint256 _targetBondingRate) public Manager(_controller) {
// Inflation must be valid percentage
require(MathUtils.validPerc(_inflation));
// Inflation change must be valid percentage
require(MathUtils.validPerc(_inflationChange));
// Target bonding rate must be valid percentage
require(MathUtils.validPerc(_targetBondingRate));
inflation = _inflation;
inflationChange = _inflationChange;
targetBondingRate = _targetBondingRate;
}
| function Minter(address _controller, uint256 _inflation, uint256 _inflationChange, uint256 _targetBondingRate) public Manager(_controller) {
// Inflation must be valid percentage
require(MathUtils.validPerc(_inflation));
// Inflation change must be valid percentage
require(MathUtils.validPerc(_inflationChange));
// Target bonding rate must be valid percentage
require(MathUtils.validPerc(_targetBondingRate));
inflation = _inflation;
inflationChange = _inflationChange;
targetBondingRate = _targetBondingRate;
}
| 35,751 |
6 | // Emitted when iToken's Distribution factor is changed by admin | event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
| event NewDistributionFactor(
address iToken,
uint256 oldDistributionFactorMantissa,
uint256 newDistributionFactorMantissa
);
function updateDistributionState(address _iToken, bool _isBorrow) external;
function updateReward(
address _iToken,
| 28,854 |
3 | // Gets the balance of the underlying assets held by the Yield Service/ return The underlying balance of asset tokens | function _balance() internal override returns (uint256) {
return cToken.balanceOfUnderlying(address(this));
}
| function _balance() internal override returns (uint256) {
return cToken.balanceOfUnderlying(address(this));
}
| 24,494 |
213 | // FiresToken | address public friesToken;
address public oven;
address public rewards;
uint256 public totalDeposited;
uint256 public flushActivator;
| address public friesToken;
address public oven;
address public rewards;
uint256 public totalDeposited;
uint256 public flushActivator;
| 2,081 |
21 | // fallback function can be used to buy tokens | function () payable {
buyTokens(msg.sender);
}
| function () payable {
buyTokens(msg.sender);
}
| 24,271 |
69 | // Calculate the bonus amount of network ion on a given lot AO Bonus Amount = B% x P_purchaseAmount The amount of primordial ion intended to be purchased _totalPrimordialMintable Total Primordial ion intable _totalPrimordialMinted Total Primordial ion minted so far _startingMultiplier The starting Network ion bonus multiplier _endingMultiplier The ending Network ion bonus multiplierreturn The bonus percentage / | function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network ion bonus amount
*/
uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkBonus;
}
| function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
/**
* Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
* when calculating the network ion bonus amount
*/
uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkBonus;
}
| 18,140 |
2 | // External contract used for try / catch examples | contract Foo {
address public owner;
constructor(address _owner) {
require(_owner != address(0), "invalid address");
assert(_owner != 0x0000000000000000000000000000000000000001);
owner = _owner;
}
function myFunc(uint x) public pure returns (string memory) {
require(x != 0, "require failed");
return "my func was called";
}
}
| contract Foo {
address public owner;
constructor(address _owner) {
require(_owner != address(0), "invalid address");
assert(_owner != 0x0000000000000000000000000000000000000001);
owner = _owner;
}
function myFunc(uint x) public pure returns (string memory) {
require(x != 0, "require failed");
return "my func was called";
}
}
| 48,071 |
18 | // Update the user profile of the caller of this method.Note: the user can modify only his own profile._newUserNameThe new user's displaying name _newStatus The new user's status / | function updateUser(string memory _newUserName, bytes32 _newStatus) checkSenderIsRegistered public
returns(uint)
| function updateUser(string memory _newUserName, bytes32 _newStatus) checkSenderIsRegistered public
returns(uint)
| 28,920 |
33 | // Check post-rebalance conditions. | uint256 _underlyingAfter = _totalUnderlyingInWad();
uint256 _supply = totalSupply();
| uint256 _underlyingAfter = _totalUnderlyingInWad();
uint256 _supply = totalSupply();
| 71,210 |
5 | // The balance of the fomo pool. / | uint256 public fomoPool = 0;
| uint256 public fomoPool = 0;
| 30,090 |
9 | // Function that ends the claiming period. Can only be done ifContract has been started and periodEnd is passed.Sends the remaining funds on contract back to the avatar contractaddress / | function end() public requirePeriodEnd {
DAOToken token = avatar.nativeToken();
uint256 remainingReserve = token.balanceOf(address(this));
if (remainingReserve > 0) {
require(
token.transfer(address(avatar), remainingReserve),
"end transfer failed"
);
}
removeRights();
super.end();
}
| function end() public requirePeriodEnd {
DAOToken token = avatar.nativeToken();
uint256 remainingReserve = token.balanceOf(address(this));
if (remainingReserve > 0) {
require(
token.transfer(address(avatar), remainingReserve),
"end transfer failed"
);
}
removeRights();
super.end();
}
| 5,368 |
78 | // 20% of 1st round of reward distribution | uint256 public _poolRewardDistributionRate = 0;
| uint256 public _poolRewardDistributionRate = 0;
| 52,753 |
203 | // Number of mints to execute | uint256 nMint = _ids.length;
| uint256 nMint = _ids.length;
| 9,698 |
370 | // Bootstrap Treasury | incentivize(treasuryAddress(), 5e23);
| incentivize(treasuryAddress(), 5e23);
| 24,701 |
10 | // total to shared | uint public totalRewarded;
uint public withdrewReward;
| uint public totalRewarded;
uint public withdrewReward;
| 28,297 |
158 | // Set a new escape hatch for the smart wallet unless it has been disabled. | _ESCAPE_HATCH_REGISTRY.setEscapeHatch(account);
| _ESCAPE_HATCH_REGISTRY.setEscapeHatch(account);
| 31,336 |
50 | // get the number of vaults for a specified account owner _accountOwner account owner addressreturn number of vaults / | function getAccountVaultCounter(address _accountOwner) external view returns (uint256) {
return accountVaultCounter[_accountOwner];
}
| function getAccountVaultCounter(address _accountOwner) external view returns (uint256) {
return accountVaultCounter[_accountOwner];
}
| 33,826 |
53 | // pass in a tokenReserve & the type of token (through _asset), update the reserveData | function updateReserveData(TokenReserve memory tokenReserve, address _asset) internal {
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
readReserveData();
// Basically just update the weight & bal of the corresponding token & write the reserveData again
if (_asset == xyt) {
(xytWeight, xytBalance) = (tokenReserve.weight, tokenReserve.balance);
} else {
(tokenWeight, tokenBalance) = (tokenReserve.weight, tokenReserve.balance);
xytWeight = Math.RONE.sub(tokenWeight);
}
writeReserveData(xytBalance, tokenBalance, xytWeight);
}
| function updateReserveData(TokenReserve memory tokenReserve, address _asset) internal {
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
readReserveData();
// Basically just update the weight & bal of the corresponding token & write the reserveData again
if (_asset == xyt) {
(xytWeight, xytBalance) = (tokenReserve.weight, tokenReserve.balance);
} else {
(tokenWeight, tokenBalance) = (tokenReserve.weight, tokenReserve.balance);
xytWeight = Math.RONE.sub(tokenWeight);
}
writeReserveData(xytBalance, tokenBalance, xytWeight);
}
| 39,659 |
96 | // The contract handles the share boosts. | address public boostContract;
| address public boostContract;
| 13,502 |
46 | // if ether is sent to this address, send it back. | revert();
| revert();
| 45,660 |
308 | // If the creation block has passed and not enough racers have joined | uint256 racersCount = _racers[race.id].length();
return race.startBlock <= block.number && racersCount == 1;
| uint256 racersCount = _racers[race.id].length();
return race.startBlock <= block.number && racersCount == 1;
| 41,600 |
43 | // dividing by zero is a bad idea | if (tokenSupply_ > 0) {
| if (tokenSupply_ > 0) {
| 3,674 |
257 | // If additional reward to existing period, calc sum | else {
uint256 remaining = periodFinish - currentTime;
uint256 leftover = remaining * rewardRate;
rewardRate = (_reward + leftover) / DURATION;
}
| else {
uint256 remaining = periodFinish - currentTime;
uint256 leftover = remaining * rewardRate;
rewardRate = (_reward + leftover) / DURATION;
}
| 43,044 |
103 | // Claim pending withdrawal _poolId id of the pool / | function linearClaimPendingWithdraw(uint256 _poolId)
external
nonReentrant
linearValidatePoolById(_poolId)
| function linearClaimPendingWithdraw(uint256 _poolId)
external
nonReentrant
linearValidatePoolById(_poolId)
| 42,106 |
141 | // set Earning Percent | EarningPercent[sender] = MonthlyEarningPercent;
| EarningPercent[sender] = MonthlyEarningPercent;
| 13,037 |
97 | // Recalls up to the harvestAmt from the active vault// This function will recall less than harvestAmt if only less is available//_recallAmt the amount to harvest from the active vault | function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal {
VaultWithIndirection.Data storage _activeVault = _vaults.last();
uint256 activeVaultVal = _activeVault.totalValue();
if (activeVaultVal < _recallAmt) {
_recallAmt = activeVaultVal;
}
if (_recallAmt > 0) {
_recallFundsFromActiveVault(_recallAmt);
}
}
| function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal {
VaultWithIndirection.Data storage _activeVault = _vaults.last();
uint256 activeVaultVal = _activeVault.totalValue();
if (activeVaultVal < _recallAmt) {
_recallAmt = activeVaultVal;
}
if (_recallAmt > 0) {
_recallFundsFromActiveVault(_recallAmt);
}
}
| 22,294 |
45 | // Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}by `operator` from `from`, this function is called. It must return its Solidity selector to confirm the token transfer.If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. / | function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
| function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
| 7,720 |
13 | // Certificate should not be expired | if (e < block.timestamp) {
return false;
}
| if (e < block.timestamp) {
return false;
}
| 51,693 |
38 | // Overflow check: 2700 1e61e18 < 10^30 < 2^105 < 2^256 | uint constant public SUPPLY_HARD_CAP = 2700 * 1e6 * 1e18;
bool public mintingFinished = false;
| uint constant public SUPPLY_HARD_CAP = 2700 * 1e6 * 1e18;
bool public mintingFinished = false;
| 22,835 |
193 | // end of every round | uint[2] public end;
| uint[2] public end;
| 81,400 |
13 | // deduct the immediately unlocked amount of tokens from the rule's amount of locked tokens | trInbound.tokens -= uint96(trInbound.tokens * trInbound.percUnlockedAtTimeUnlock / PERC_BASE);
| trInbound.tokens -= uint96(trInbound.tokens * trInbound.percUnlockedAtTimeUnlock / PERC_BASE);
| 438 |
265 | // Hook that is called before any token transfer. This includes mintingand burning. Calling conditions: - When `from` and `to` are both non-zero, ``from``'s `tokenId` will betransferred to `to`.- When `from` is zero, `tokenId` will be minted for `to`.- When `to` is zero, ``from``'s `tokenId` will be burned.- `from` cannot be the zero address.- `to` cannot be the zero address. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. / | function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {}
}
| function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual {}
}
| 2,132 |
673 | // Remove the synth from the availableSynths array. | for (uint i = 0; i < availableSynths.length; i++) {
if (address(availableSynths[i]) == synthToRemove) {
delete availableSynths[i];
| for (uint i = 0; i < availableSynths.length; i++) {
if (address(availableSynths[i]) == synthToRemove) {
delete availableSynths[i];
| 34,319 |
11 | // make sure that callTo address is either of the cBridge addresses | if (address(cBridge) != _callTo) {
revert ContractCallNotAllowed();
}
| if (address(cBridge) != _callTo) {
revert ContractCallNotAllowed();
}
| 11,678 |
154 | // Return `true` if the account belongs to the admin role. | function isAdmin(address account) public virtual view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
| function isAdmin(address account) public virtual view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, account);
}
| 16,520 |
10 | // Private Sale | if (now > 1522018800 && now < 1523228400 && tokenSold < 42000001) {
amount = msg.value * price;
amount += amount / 3;
}
| if (now > 1522018800 && now < 1523228400 && tokenSold < 42000001) {
amount = msg.value * price;
amount += amount / 3;
}
| 57,665 |
0 | // Declare state variables in this section |
uint8 public avgBlockTime; // Avg block time in seconds.
uint8 private decimals; // Decimals of our Shares. Has to be 0.
uint8 public tax; // Can Preset Tax rate in constructor. To be changed by government only.
uint8 public rentalLimitMonths; // Months any tenant can pay rent in advance for.
uint256 public rentalLimitBlocks; // ...in Blocks.
uint256 constant private MAX_UINT256 = 2**256 - 1; // Very large number.
uint256 public totalSupply; // By default 100 for 100% ownership. Can be changed.
uint256 public totalSupply2; // Only Ether incoming of multiples of this variable will be allowed. This way we can have two itterations of divisions through totalSupply without remainder. There is no Float in ETH, so we need to prevent remainders in division. E.g. 1. iteration (incoming ether value = MultipleOfTokenSupplyPower2) / totalSupply * uint (desired percentage); 2nd iteration ( ether value = MultipleOfTokenSupplyPower) / totalSupply * uint (desired percentage); --> no remainder
uint256 public rentPer30Day; // rate charged by mainPropertyOwner for 30 Days of rent.
|
uint8 public avgBlockTime; // Avg block time in seconds.
uint8 private decimals; // Decimals of our Shares. Has to be 0.
uint8 public tax; // Can Preset Tax rate in constructor. To be changed by government only.
uint8 public rentalLimitMonths; // Months any tenant can pay rent in advance for.
uint256 public rentalLimitBlocks; // ...in Blocks.
uint256 constant private MAX_UINT256 = 2**256 - 1; // Very large number.
uint256 public totalSupply; // By default 100 for 100% ownership. Can be changed.
uint256 public totalSupply2; // Only Ether incoming of multiples of this variable will be allowed. This way we can have two itterations of divisions through totalSupply without remainder. There is no Float in ETH, so we need to prevent remainders in division. E.g. 1. iteration (incoming ether value = MultipleOfTokenSupplyPower2) / totalSupply * uint (desired percentage); 2nd iteration ( ether value = MultipleOfTokenSupplyPower) / totalSupply * uint (desired percentage); --> no remainder
uint256 public rentPer30Day; // rate charged by mainPropertyOwner for 30 Days of rent.
| 16,221 |
8 | // send `_value` token to `_to` from `msg.sender`/_to The address of the recipient/_value The amount of token to be transferred/ return Whether the transfer was successful or not | function transfer(address _to, uint256 _value) returns (bool success) {}
| function transfer(address _to, uint256 _value) returns (bool success) {}
| 21,723 |
34 | // update profits | _dealer.profit = 0; // old tokens have been reinvested
_dealer.time = now; // generate tokens from now
| _dealer.profit = 0; // old tokens have been reinvested
_dealer.time = now; // generate tokens from now
| 46,984 |
21 | // : isProphecyValidatorActiveReturns boolean indicating if the validator that originallysubmitted the ProphecyClaim is still an active validator / | function isProphecyClaimValidatorActive(uint256 _prophecyID)
public
view
returns (bool)
| function isProphecyClaimValidatorActive(uint256 _prophecyID)
public
view
returns (bool)
| 28,564 |
20 | // Gets the amount of funds in Wei available to the sender. | function balance() constant returns (uint) {
if (!between[msg.sender]) {
// The sender of the message isn't part of the split. Ignore them.
return 0;
}
// `share` is the amount of funds which are available to each of the
// accounts specified in the constructor.
uint share = totalInput / count;
uint withdrew = amountsWithdrew[msg.sender];
uint available = share - withdrew;
assert(available >= 0 && available <= share);
return available;
}
| function balance() constant returns (uint) {
if (!between[msg.sender]) {
// The sender of the message isn't part of the split. Ignore them.
return 0;
}
// `share` is the amount of funds which are available to each of the
// accounts specified in the constructor.
uint share = totalInput / count;
uint withdrew = amountsWithdrew[msg.sender];
uint available = share - withdrew;
assert(available >= 0 && available <= share);
return available;
}
| 25,307 |
246 | // See {IRedeemBase-updateApprovedTokenRanges} / | function updateApprovedTokenRanges(address contract_, uint256[] memory minTokenIds, uint256[] memory maxTokenIds) public virtual override adminRequired {
require(minTokenIds.length == maxTokenIds.length, "Redeem: Invalid input parameters");
uint existingRangesLength = _approvedTokenRange[contract_].length;
for (uint i=0; i < existingRangesLength; i++) {
_approvedTokenRange[contract_][i].min = 0;
_approvedTokenRange[contract_][i].max = 0;
}
| function updateApprovedTokenRanges(address contract_, uint256[] memory minTokenIds, uint256[] memory maxTokenIds) public virtual override adminRequired {
require(minTokenIds.length == maxTokenIds.length, "Redeem: Invalid input parameters");
uint existingRangesLength = _approvedTokenRange[contract_].length;
for (uint i=0; i < existingRangesLength; i++) {
_approvedTokenRange[contract_][i].min = 0;
_approvedTokenRange[contract_][i].max = 0;
}
| 41,885 |
12 | // XTKManagementStakingModule xToken/ | contract XTKManagementStakingModule is Initializable, ERC20Upgradeable, OwnableUpgradeable {
using SafeERC20 for IERC20;
/* ============ State Variables ============ */
// Address of xtk token
address public constant xtk = 0x7F3EDcdD180Dbe4819Bd98FeE8929b5cEdB3AdEB;
// Unstake penalty percentage between 0 and 10%
uint256 public unstakePenalty;
bool public transferable;
uint256 private constant DEC_18 = 1e18;
uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 10;
/* ============ Events ============ */
event SetUnstakePenalty(uint256 indexed timestamp, uint256 unstakePenalty);
event Stake(address indexed sender, uint256 xtkAmount, uint256 xxtkAmount);
event UnStake(address indexed receiver, uint256 xxtkAmount, uint256 xtkAmount);
/* ============ Functions ============ */
function initialize() external initializer {
__Ownable_init();
__ERC20_init_unchained("xXTK-Mgmt", "xXTKa");
transferable = true;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
* Check if transferable
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(transferable, "token not transferable");
}
/**
* Governance function that allow/disallow xXTK token transfer
*/
function setTransferable(bool _transferable) external onlyOwner {
require(transferable != _transferable, "Same value");
transferable = _transferable;
}
/**
* Governance function that updates the unstake penalty percentage
* @notice penalty == 1e18 means penalty is 0
* @notice penalty to be between 0 and 10%
*
* @param _unstakePenalty Unstake penalty percentage
*/
function setUnstakePenalty(uint256 _unstakePenalty) external onlyOwner {
require(_unstakePenalty < DEC_18 && _unstakePenalty >= 9e17, "Penalty outside range");
unstakePenalty = _unstakePenalty;
emit SetUnstakePenalty(block.timestamp, _unstakePenalty);
}
/**
* Receive xtk token from user and mint propertional Xxtk to the user
* @param _xtkAmount xtk token amount to stake
*/
function stake(uint256 _xtkAmount) external {
require(_xtkAmount > 0, "Cannot stake 0");
uint256 mintAmount = calculateXxtkAmountToMint(_xtkAmount);
IERC20(xtk).safeTransferFrom(msg.sender, address(this), _xtkAmount);
_mint(msg.sender, mintAmount);
emit Stake(msg.sender, _xtkAmount, mintAmount);
}
/**
* Burn Xxtk token from user and send propertional xtk token
* @dev possible reentrance?
* @param _xxtkAmount Xxtk token amount to burn
*/
function unstake(uint256 _xxtkAmount) external {
uint256 xtkWithoutPenalty = calculateProRataXtk(_xxtkAmount);
uint256 xtkToDistribute = calculateXtkToDistributeOnUnstake(xtkWithoutPenalty);
_burn(msg.sender, _xxtkAmount);
IERC20(xtk).safeTransfer(msg.sender, xtkToDistribute);
emit UnStake(msg.sender, _xxtkAmount, xtkToDistribute);
}
function calculateXxtkAmountToMint(uint256 xtkAmount) public view returns (uint256) {
uint256 totalSupply = totalSupply();
if (totalSupply == 0) return xtkAmount * INITIAL_SUPPLY_MULTIPLIER;
uint256 xtkBalance = IERC20(xtk).balanceOf(address(this));
return (xtkAmount * totalSupply) / xtkBalance;
}
function calculateProRataXtk(uint256 xxtkAmount) public view returns (uint256) {
uint256 xtkBalance = IERC20(xtk).balanceOf(address(this));
return (xxtkAmount * xtkBalance) / totalSupply();
}
function calculateXtkToDistributeOnUnstake(uint256 proRataXtk) public view returns (uint256) {
return (proRataXtk * unstakePenalty) / DEC_18;
}
}
| contract XTKManagementStakingModule is Initializable, ERC20Upgradeable, OwnableUpgradeable {
using SafeERC20 for IERC20;
/* ============ State Variables ============ */
// Address of xtk token
address public constant xtk = 0x7F3EDcdD180Dbe4819Bd98FeE8929b5cEdB3AdEB;
// Unstake penalty percentage between 0 and 10%
uint256 public unstakePenalty;
bool public transferable;
uint256 private constant DEC_18 = 1e18;
uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 10;
/* ============ Events ============ */
event SetUnstakePenalty(uint256 indexed timestamp, uint256 unstakePenalty);
event Stake(address indexed sender, uint256 xtkAmount, uint256 xxtkAmount);
event UnStake(address indexed receiver, uint256 xxtkAmount, uint256 xtkAmount);
/* ============ Functions ============ */
function initialize() external initializer {
__Ownable_init();
__ERC20_init_unchained("xXTK-Mgmt", "xXTKa");
transferable = true;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
* Check if transferable
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(transferable, "token not transferable");
}
/**
* Governance function that allow/disallow xXTK token transfer
*/
function setTransferable(bool _transferable) external onlyOwner {
require(transferable != _transferable, "Same value");
transferable = _transferable;
}
/**
* Governance function that updates the unstake penalty percentage
* @notice penalty == 1e18 means penalty is 0
* @notice penalty to be between 0 and 10%
*
* @param _unstakePenalty Unstake penalty percentage
*/
function setUnstakePenalty(uint256 _unstakePenalty) external onlyOwner {
require(_unstakePenalty < DEC_18 && _unstakePenalty >= 9e17, "Penalty outside range");
unstakePenalty = _unstakePenalty;
emit SetUnstakePenalty(block.timestamp, _unstakePenalty);
}
/**
* Receive xtk token from user and mint propertional Xxtk to the user
* @param _xtkAmount xtk token amount to stake
*/
function stake(uint256 _xtkAmount) external {
require(_xtkAmount > 0, "Cannot stake 0");
uint256 mintAmount = calculateXxtkAmountToMint(_xtkAmount);
IERC20(xtk).safeTransferFrom(msg.sender, address(this), _xtkAmount);
_mint(msg.sender, mintAmount);
emit Stake(msg.sender, _xtkAmount, mintAmount);
}
/**
* Burn Xxtk token from user and send propertional xtk token
* @dev possible reentrance?
* @param _xxtkAmount Xxtk token amount to burn
*/
function unstake(uint256 _xxtkAmount) external {
uint256 xtkWithoutPenalty = calculateProRataXtk(_xxtkAmount);
uint256 xtkToDistribute = calculateXtkToDistributeOnUnstake(xtkWithoutPenalty);
_burn(msg.sender, _xxtkAmount);
IERC20(xtk).safeTransfer(msg.sender, xtkToDistribute);
emit UnStake(msg.sender, _xxtkAmount, xtkToDistribute);
}
function calculateXxtkAmountToMint(uint256 xtkAmount) public view returns (uint256) {
uint256 totalSupply = totalSupply();
if (totalSupply == 0) return xtkAmount * INITIAL_SUPPLY_MULTIPLIER;
uint256 xtkBalance = IERC20(xtk).balanceOf(address(this));
return (xtkAmount * totalSupply) / xtkBalance;
}
function calculateProRataXtk(uint256 xxtkAmount) public view returns (uint256) {
uint256 xtkBalance = IERC20(xtk).balanceOf(address(this));
return (xxtkAmount * xtkBalance) / totalSupply();
}
function calculateXtkToDistributeOnUnstake(uint256 proRataXtk) public view returns (uint256) {
return (proRataXtk * unstakePenalty) / DEC_18;
}
}
| 64,730 |
104 | // modifier for checking deadline | modifier checkDeadline(uint256 deadline) {
require(block.timestamp <= deadline, "Transaction too old");
_;
}
| modifier checkDeadline(uint256 deadline) {
require(block.timestamp <= deadline, "Transaction too old");
_;
}
| 39,913 |
25 | // Returns a cost for the payer to breed the trout that is no larger than the list price. | function _getBreedingFee(address _payer, TokenId _tokenId) internal view returns (uint256) {
if (TokenId.unwrap(_tokenId) == 0 || _payer == _ownerOf(_tokenId)) return 0;
(bool exists, uint256 fee) = studs.tryGet(TokenId.unwrap(_tokenId));
if (!exists) revert NotListed();
return fee;
}
| function _getBreedingFee(address _payer, TokenId _tokenId) internal view returns (uint256) {
if (TokenId.unwrap(_tokenId) == 0 || _payer == _ownerOf(_tokenId)) return 0;
(bool exists, uint256 fee) = studs.tryGet(TokenId.unwrap(_tokenId));
if (!exists) revert NotListed();
return fee;
}
| 26,566 |
1 | // - Detail | struct LockContractDetail {
uint index;
uint256 periodtime;
uint256 periodamount;
uint period;
bool confirm;
}
| struct LockContractDetail {
uint index;
uint256 periodtime;
uint256 periodamount;
uint period;
bool confirm;
}
| 8,024 |
556 | // Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned- E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address asset The address of the borrowed underlying asset previously borrowed amount The amount to repay- Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of theuser calling the function | ) external override whenNotPaused returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateRepay(
reserve,
amount,
interestRateMode,
onBehalfOf,
stableDebt,
variableDebt
);
uint256 paybackAmount =
interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt;
if (amount < paybackAmount) {
paybackAmount = amount;
}
reserve.updateState();
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(
onBehalfOf,
paybackAmount,
reserve.variableBorrowIndex
);
}
address aToken = reserve.aTokenAddress;
reserve.updateInterestRates(asset, aToken, paybackAmount, 0);
if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) {
_usersConfig[onBehalfOf].setBorrowing(reserve.id, false);
}
IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount);
emit Repay(asset, onBehalfOf, msg.sender, paybackAmount);
return paybackAmount;
}
| ) external override whenNotPaused returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateRepay(
reserve,
amount,
interestRateMode,
onBehalfOf,
stableDebt,
variableDebt
);
uint256 paybackAmount =
interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt;
if (amount < paybackAmount) {
paybackAmount = amount;
}
reserve.updateState();
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(
onBehalfOf,
paybackAmount,
reserve.variableBorrowIndex
);
}
address aToken = reserve.aTokenAddress;
reserve.updateInterestRates(asset, aToken, paybackAmount, 0);
if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) {
_usersConfig[onBehalfOf].setBorrowing(reserve.id, false);
}
IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount);
emit Repay(asset, onBehalfOf, msg.sender, paybackAmount);
return paybackAmount;
}
| 25,108 |
3 | // Set the Nutmeg | function setNutmegAddress(address addr) external onlyGov {
nutmeg = addr;
}
| function setNutmegAddress(address addr) external onlyGov {
nutmeg = addr;
}
| 81,745 |
120 | // Getter function for requestId based on the queryHash_queryHash hash(of string api and granularity) to check if a request already exists return uint requestId/ | function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) {
return self.requestIdByQueryHash[_queryHash];
}
| function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) {
return self.requestIdByQueryHash[_queryHash];
}
| 31,851 |
105 | // offset of the first element in the array | offset := identityCommitments.offset
| offset := identityCommitments.offset
| 31,146 |
27 | // returns current EAA Rate / | function getCurrentEAAR() external view returns (uint256) {
return _calculateEAARate();
}
| function getCurrentEAAR() external view returns (uint256) {
return _calculateEAARate();
}
| 8,666 |
209 | // update free-memory pointerallocating the array padded to 32 bytes like the compiler does now | mstore(0x40, and(add(mc, 31), not(31)))
| mstore(0x40, and(add(mc, 31), not(31)))
| 1,692 |
7 | // Feed user for conversion. (i.e: Using the example above and ETH/USD willoutput RAI price in USD) | ConverterFeedLike public denominationFeed;
| ConverterFeedLike public denominationFeed;
| 26,396 |
272 | // Pay with PLAT. | function payWithPLAT(uint256 _amount)
private
| function payWithPLAT(uint256 _amount)
private
| 57,907 |
11 | // Playing around with code and thought this was interesting, I made two contracts/ | contract restrictedAccessAccountContract {
event senderLogger(address);
event valueLogger(uint);
address private owner;
function transaction() {
owner = msg.sender;
}
modifier isOwner {
require(owner == msg.sender);
_;
}
modifier validValue {
require(msg.value >= 1 ether);
_;
}
function () payable isOwner validValue {
senderLogger(msg.sender);
valueLogger(msg.value);
}
}
| contract restrictedAccessAccountContract {
event senderLogger(address);
event valueLogger(uint);
address private owner;
function transaction() {
owner = msg.sender;
}
modifier isOwner {
require(owner == msg.sender);
_;
}
modifier validValue {
require(msg.value >= 1 ether);
_;
}
function () payable isOwner validValue {
senderLogger(msg.sender);
valueLogger(msg.value);
}
}
| 48,387 |
2 | // _token : cToken address _underlying : underlying token (eg DAI) address / | constructor(address _token, address _underlying) public {
require(_token != address(0) && _underlying != address(0), 'COMP: some addr is 0');
token = _token;
underlying = _underlying;
blocksPerYear = 2371428;
IERC20(_underlying).safeApprove(_token, uint256(-1));
}
| constructor(address _token, address _underlying) public {
require(_token != address(0) && _underlying != address(0), 'COMP: some addr is 0');
token = _token;
underlying = _underlying;
blocksPerYear = 2371428;
IERC20(_underlying).safeApprove(_token, uint256(-1));
}
| 25,178 |
117 | // minimum amount before adding auto liquidity _amount the amount of tokens before executing auto liquidity / | function setMinAmountBeforeAutoLiquidity(uint256 _amount) public onlyOwner {
minAmountBeforeAutoLiquidity = _amount;
emit SetMinAmountBeforeAutoLiquidity(_amount);
}
| function setMinAmountBeforeAutoLiquidity(uint256 _amount) public onlyOwner {
minAmountBeforeAutoLiquidity = _amount;
emit SetMinAmountBeforeAutoLiquidity(_amount);
}
| 7,160 |
32 | // just a normal collection | collection = price[tokenId]
.mul(now.sub(previousTokenCollection))
.mul(patronageNumerator[tokenId])
.div(patronageDenominator)
.div(365 days);
timeLastCollected[tokenId] = now;
timeLastCollectedPatron[tokenPatron] = now;
currentCollected[tokenId] = currentCollected[tokenId].add(
collection
);
| collection = price[tokenId]
.mul(now.sub(previousTokenCollection))
.mul(patronageNumerator[tokenId])
.div(patronageDenominator)
.div(365 days);
timeLastCollected[tokenId] = now;
timeLastCollectedPatron[tokenPatron] = now;
currentCollected[tokenId] = currentCollected[tokenId].add(
collection
);
| 12,181 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.