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 |
|---|---|---|---|---|
14 | // ========== RESTRICTED FUNCTIONS ========== // Allows the inclusion of a new provider to the registry. | * Emits a {ProviderAdded} event indicating the newly added provider.
*
* Requirements:
* - the caller must be the owner of the contract
* - the provider must not already exist in the registry
*
* @param provider provider to add
* @param fee fee to go to provider
*/
function addProvider(address provider, uint16 fee) external onlyOwner {
require(
!_provider[provider],
"RiskProviderRegistry::addProvider: Provider already exists"
);
_provider[provider] = true;
feeHandler.setRiskProviderFee(provider, fee);
emit ProviderAdded(provider);
}
| * Emits a {ProviderAdded} event indicating the newly added provider.
*
* Requirements:
* - the caller must be the owner of the contract
* - the provider must not already exist in the registry
*
* @param provider provider to add
* @param fee fee to go to provider
*/
function addProvider(address provider, uint16 fee) external onlyOwner {
require(
!_provider[provider],
"RiskProviderRegistry::addProvider: Provider already exists"
);
_provider[provider] = true;
feeHandler.setRiskProviderFee(provider, fee);
emit ProviderAdded(provider);
}
| 35,062 |
40 | // A map to register the ACO creator. / | mapping(address => address) public creators;
| mapping(address => address) public creators;
| 28,449 |
175 | // GETTERS / | function _baseURI() internal view virtual override returns (string memory) {
return BASE_URI;
}
| function _baseURI() internal view virtual override returns (string memory) {
return BASE_URI;
}
| 31,046 |
32 | // distribute bonus wei to bonus fund | fbf.setOwnedBonus.value(weiForBonusFund)();
| fbf.setOwnedBonus.value(weiForBonusFund)();
| 24,899 |
27 | // Transfer token for a specified address_to The address to transfer to._value The amount to be transferred./ | function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 2,048 |
210 | // Presale and Play2Mint Structs | struct PresaleConfig {
uint256 mintMax;
}
| struct PresaleConfig {
uint256 mintMax;
}
| 39,554 |
41 | // Generate a request for oracles to fetch flight information | function fetchFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp
)
external
requireIsOperational
| function fetchFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp
)
external
requireIsOperational
| 5,691 |
365 | // Return fee-adjusted amount of collateral deleted from position. | return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
| return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
| 34,904 |
7 | // Division of two int256 variables and fails on overflow. / | function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256, "div: b == 1 OR A == MIN_INT256");
// Solidity already throws when dividing by 0.
return a / b;
}
| function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256, "div: b == 1 OR A == MIN_INT256");
// Solidity already throws when dividing by 0.
return a / b;
}
| 4,023 |
104 | // Deploy new BPool (bFactory and bPool are interfaces; all calls are external) | bPool = bFactory.newBPool();
| bPool = bFactory.newBPool();
| 3,760 |
101 | // Finalizing. Transfer token ownership to wallet for safe-keeping until it will be transferred to the DAO.Called from the finalize function in FinalizableCrowdsale./ | function finalization() internal {
MintableToken(token).transferOwnership(wallet);
super.finalization();
}
| function finalization() internal {
MintableToken(token).transferOwnership(wallet);
super.finalization();
}
| 17,303 |
282 | // BoredApeYachtClub contract Extends ERC721 Non-Fungible Token Standard basic implementation / | contract BoredApeYachtClub is ERC721, Ownable {
using SafeMath for uint256;
string public BAYC_PROVENANCE = "";
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public constant apePrice = 80000000000000000; //0.08 ETH
uint public constant maxApePurchase = 20;
uint256 public MAX_APES;
bool public saleIsActive = false;
uint256 public REVEAL_TIMESTAMP;
constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) {
MAX_APES = maxNftSupply;
REVEAL_TIMESTAMP = saleStart + (86400 * 9);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* Set some Bored Apes aside
*/
function reserveApes() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 30; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* DM Gargamel in Discord that you're standing right behind him.
*/
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = revealTimeStamp;
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
BAYC_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* Mints Bored Apes
*/
function mintApe(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Ape");
require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes");
require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_APES) {
_safeMint(msg.sender, mintIndex);
}
}
// If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_APES;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
} | contract BoredApeYachtClub is ERC721, Ownable {
using SafeMath for uint256;
string public BAYC_PROVENANCE = "";
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public constant apePrice = 80000000000000000; //0.08 ETH
uint public constant maxApePurchase = 20;
uint256 public MAX_APES;
bool public saleIsActive = false;
uint256 public REVEAL_TIMESTAMP;
constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) {
MAX_APES = maxNftSupply;
REVEAL_TIMESTAMP = saleStart + (86400 * 9);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* Set some Bored Apes aside
*/
function reserveApes() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 30; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* DM Gargamel in Discord that you're standing right behind him.
*/
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = revealTimeStamp;
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
BAYC_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* Mints Bored Apes
*/
function mintApe(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Ape");
require(numberOfTokens <= maxApePurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_APES, "Purchase would exceed max supply of Apes");
require(apePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_APES) {
_safeMint(msg.sender, mintIndex);
}
}
// If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_APES || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_APES;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_APES;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
} | 7,018 |
202 | // no options when esop is being converted and conversion deadline expired | bool isESOPConverted = conversionOfferedAt > 0 && calcAtTime >= conversionOfferedAt; // this function time-travels
uint issuedOptions = emp.poolOptions + emp.extraOptions;
| bool isESOPConverted = conversionOfferedAt > 0 && calcAtTime >= conversionOfferedAt; // this function time-travels
uint issuedOptions = emp.poolOptions + emp.extraOptions;
| 30,380 |
64 | // File: contracts/libraries/UniswapV2Library.sol | library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
| library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
| 30,504 |
42 | // bubbleSort(listener_count); | for (uint256 x = 0; x < k; x++) {
artistsList[x] = (copyArtists[x]);
}
| for (uint256 x = 0; x < k; x++) {
artistsList[x] = (copyArtists[x]);
}
| 38,278 |
16 | // ========== MUTATIVE FUNCTIONS ========== // Set the rates stored in this contract currencyKeys The currency keys you wish to update the rates for (in order) newRates The rates for each currency (in order) timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly evenif it takes a long time for the transaction to confirm. / | function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns (bool) {
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
| function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns (bool) {
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
| 19,150 |
18 | // Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./ | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| 2,007 |
85 | // Section for ERC1363 Implementation //Note: the ERC-165 identifier for this interface is 0x4bbee2df.0x4bbee2df ===bytes4(keccak256('transferAndCall(address,uint256)')) ^bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) / | bytes4 internal constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df;
| bytes4 internal constant _INTERFACE_ID_ERC1363_TRANSFER = 0x4bbee2df;
| 3,623 |
38 | // Open or close a given channel. Only callable by the controller.channel The channel to open or close. isOpenThe status of the channel (either open or closed). / | function updateChannel(address channel, bool isOpen) external override {
// Ensure that the caller is the controller of this contract.
if (msg.sender != _controller) {
revert InvalidController();
}
// Ensure that the channel does not already have the indicated status.
if (_channels[channel] == isOpen) {
revert ChannelStatusAlreadySet(channel, isOpen);
}
// Update the status of the channel.
_channels[channel] = isOpen;
// Emit a corresponding event.
emit ChannelUpdated(channel, isOpen);
}
| function updateChannel(address channel, bool isOpen) external override {
// Ensure that the caller is the controller of this contract.
if (msg.sender != _controller) {
revert InvalidController();
}
// Ensure that the channel does not already have the indicated status.
if (_channels[channel] == isOpen) {
revert ChannelStatusAlreadySet(channel, isOpen);
}
// Update the status of the channel.
_channels[channel] = isOpen;
// Emit a corresponding event.
emit ChannelUpdated(channel, isOpen);
}
| 4,063 |
56 | // changeApprover(): Allows any of the issuers to change a particular approver of the bounty/_sender the sender of the transaction issuing the bounty (should be the same as msg.sender unless the txn is called by the meta tx relayer)/_bountyId the index of the bounty/_issuerId the index of the issuer who is calling the function/_approverId the index of the approver who is being changed/_approver the address of the new approver | function changeApprover(
address _sender,
uint _bountyId,
uint _issuerId,
uint _approverId,
address payable _approver)
external
senderIsValid(_sender)
validateBountyArrayIndex(_bountyId)
onlyIssuer(_sender, _bountyId, _issuerId)
| function changeApprover(
address _sender,
uint _bountyId,
uint _issuerId,
uint _approverId,
address payable _approver)
external
senderIsValid(_sender)
validateBountyArrayIndex(_bountyId)
onlyIssuer(_sender, _bountyId, _issuerId)
| 11,597 |
76 | // Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` isconfigured to use block numbers, this will return the value at the end of the corresponding block. / | function getPastVotes(address account, uint256 timepoint) external view returns (uint256);
| function getPastVotes(address account, uint256 timepoint) external view returns (uint256);
| 12,476 |
80 | // Sell | if(to == uniswapV2Pair){
_taxFee = _addressFees[from]._sellTaxFee;
_liquidityFee = _addressFees[from]._sellLiquidityFee;
}
| if(to == uniswapV2Pair){
_taxFee = _addressFees[from]._sellTaxFee;
_liquidityFee = _addressFees[from]._sellLiquidityFee;
}
| 37,857 |
5 | // these functions aren't abstract since the compiler emits automatically generated getter functions as external | function name() public view returns (string) {}
function symbol() public view returns (string) {}
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
| function name() public view returns (string) {}
function symbol() public view returns (string) {}
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
| 37,382 |
14 | // Usage: - create type constants - use `assertType` for runtime type assertions - - unfortunately we can't do this at compile time yet :( - recommended: implement modifiers that perform type checking - - e.g. - - `uint40 constant MY_TYPE = 3;` | // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }`
// - instantiate a typed view from a bytearray using `ref`
// - use `index` to inspect the contents of the view
// - use `slice` to create smaller views into the same memory
// - - `slice` can increase the offset
// - - `slice can decrease the length`
// - - must specify the output type of `slice`
// - - `slice` will return a null view if you try to overrun
// - - make sure to explicitly check for this with `notNull` or `assertType`
// - use `equal` for typed comparisons.
// The null view
bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff;
uint256 constant TWENTY_SEVEN_BYTES = 8 * 27;
uint256 private constant _27_BYTES_IN_BITS = 8 * 27; // <--- also used this named constant where ever 216 is used.
uint256 private constant LOW_27_BYTES_MASK = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffff; // (1 << _27_BYTES_IN_BITS) - 1;
// ========== Custom Errors ===========
error TypedMemView__assertType_typeAssertionFailed(uint256 actual, uint256 expected);
error TypedMemView__index_overrun(uint256 loc, uint256 len, uint256 index, uint256 slice);
error TypedMemView__index_indexMoreThan32Bytes();
error TypedMemView__unsafeCopyTo_nullPointer();
error TypedMemView__unsafeCopyTo_invalidPointer();
error TypedMemView__unsafeCopyTo_identityOOG();
error TypedMemView__assertValid_validityAssertionFailed();
/**
* @notice Changes the endianness of a uint256.
* @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
* @param _b The unsigned integer to reverse
* @return v - The reversed value
*/
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v =
((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v =
((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v =
((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v =
((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
| // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }`
// - instantiate a typed view from a bytearray using `ref`
// - use `index` to inspect the contents of the view
// - use `slice` to create smaller views into the same memory
// - - `slice` can increase the offset
// - - `slice can decrease the length`
// - - must specify the output type of `slice`
// - - `slice` will return a null view if you try to overrun
// - - make sure to explicitly check for this with `notNull` or `assertType`
// - use `equal` for typed comparisons.
// The null view
bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff;
uint256 constant TWENTY_SEVEN_BYTES = 8 * 27;
uint256 private constant _27_BYTES_IN_BITS = 8 * 27; // <--- also used this named constant where ever 216 is used.
uint256 private constant LOW_27_BYTES_MASK = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffff; // (1 << _27_BYTES_IN_BITS) - 1;
// ========== Custom Errors ===========
error TypedMemView__assertType_typeAssertionFailed(uint256 actual, uint256 expected);
error TypedMemView__index_overrun(uint256 loc, uint256 len, uint256 index, uint256 slice);
error TypedMemView__index_indexMoreThan32Bytes();
error TypedMemView__unsafeCopyTo_nullPointer();
error TypedMemView__unsafeCopyTo_invalidPointer();
error TypedMemView__unsafeCopyTo_identityOOG();
error TypedMemView__assertValid_validityAssertionFailed();
/**
* @notice Changes the endianness of a uint256.
* @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
* @param _b The unsigned integer to reverse
* @return v - The reversed value
*/
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v =
((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v =
((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v =
((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v =
((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
| 30,284 |
16 | // calculate the total reward amount | uint256 totalReward = stakes[stakeholder].unclaimed + (TWAP - stakes[stakeholder].TWAP) * stakes[stakeholder].totalStaked;
| uint256 totalReward = stakes[stakeholder].unclaimed + (TWAP - stakes[stakeholder].TWAP) * stakes[stakeholder].totalStaked;
| 4,756 |
27 | // Store service metadata | struct Record {
string serviceURI; // Service URI endpoint that can be used to send off-chain requests
}
| struct Record {
string serviceURI; // Service URI endpoint that can be used to send off-chain requests
}
| 16,140 |
49 | // Put in Reward Slot | uint256 slot = _putSlotReward(_jobId);
| uint256 slot = _putSlotReward(_jobId);
| 19,501 |
127 | // +Infinity. / | bytes16 private constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000;
| bytes16 private constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000;
| 83,947 |
25 | // Is it a enabled side chain? | } else if (sideChains[id].status == ChainStatus.Enable) {
| } else if (sideChains[id].status == ChainStatus.Enable) {
| 45,298 |
176 | // Only the Account Recovery Manager contract may call this function. | if (msg.sender != _account_recovery_manager816) {
revert(_REVERTREASON31(8));
}
| if (msg.sender != _account_recovery_manager816) {
revert(_REVERTREASON31(8));
}
| 27,324 |
14 | // require(_startTime >= now); | require(_endTime >= _startTime);
require(_token != address(0));
startTime = _startTime;
endTime = _endTime;
token = IERC20(_token);
| require(_endTime >= _startTime);
require(_token != address(0));
startTime = _startTime;
endTime = _endTime;
token = IERC20(_token);
| 27,974 |
75 | // transfer DAI to pool | token.safeTransferFrom(msg.sender, address(this), _amount);
| token.safeTransferFrom(msg.sender, address(this), _amount);
| 3,979 |
314 | // calculate openNotional (it's different depends on long or short side) long: unrealizedPnl = positionNotional - openNotional => openNotional = positionNotional - unrealizedPnl short: unrealizedPnl = openNotional - positionNotional => openNotional = positionNotional + unrealizedPnl positionNotional = oldPositionNotional - exchangedQuoteAssetAmount | SignedDecimal.signedDecimal memory remainOpenNotional = oldPosition.size.toInt() > 0
? MixedDecimal.fromDecimal(oldPositionNotional).subD(positionResp.exchangedQuoteAssetAmount).subD(
positionResp.unrealizedPnlAfter
)
: positionResp.unrealizedPnlAfter.addD(oldPositionNotional).subD(
positionResp.exchangedQuoteAssetAmount
);
require(remainOpenNotional.toInt() > 0, "value of openNotional <= 0");
positionResp.position = Position(
| SignedDecimal.signedDecimal memory remainOpenNotional = oldPosition.size.toInt() > 0
? MixedDecimal.fromDecimal(oldPositionNotional).subD(positionResp.exchangedQuoteAssetAmount).subD(
positionResp.unrealizedPnlAfter
)
: positionResp.unrealizedPnlAfter.addD(oldPositionNotional).subD(
positionResp.exchangedQuoteAssetAmount
);
require(remainOpenNotional.toInt() > 0, "value of openNotional <= 0");
positionResp.position = Position(
| 8,091 |
1 | // This is the interface that {BeaconProxy} expects of its beacon./ Must return an address that can be used as a delegate call target. {BeaconProxy} will check that this address is a contract. / | function implementation() external view returns (address);
| function implementation() external view returns (address);
| 37,240 |
18 | // Create new MerkleDistributorSEV _token Token address _edenNetworkProxy Eden Network Proxy contract _admin Admin address _updateThreshold Number of updaters required to update _updaters Initial updaters _slashers Initial slashers / | constructor(
IERC20Mintable _token,
IEdenNetwork _edenNetworkProxy,
address _admin,
uint8 _updateThreshold,
address[] memory _updaters,
address[] memory _slashers
| constructor(
IERC20Mintable _token,
IEdenNetwork _edenNetworkProxy,
address _admin,
uint8 _updateThreshold,
address[] memory _updaters,
address[] memory _slashers
| 50,795 |
5 | // Upgrade event is emitted each time the implementation address is set (including deployment) | event Upgrade(address indexed implementation);
| event Upgrade(address indexed implementation);
| 4,479 |
158 | // FEI stablecoin interface/Fei Protocol | interface IFei is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
| interface IFei is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
| 15,150 |
4 | // Make sure that the cut is still alive | uint256 endsAt = cut.endsAt;
| uint256 endsAt = cut.endsAt;
| 26,368 |
157 | // Fetch parameters to be used for pool creation/Called by the pool constructor to fetch the parameters of the pool/ return factory The factory address/ return poolOracle The pool oracle for twap/ return token0 First pool token by address sort order/ return token1 Second pool token by address sort order/ return swapFeeUnits Fee to be collected upon every swap in the pool, in fee units/ return tickDistance Minimum number of ticks between initialized ticks | function parameters()
external
view
returns (
address factory,
address poolOracle,
address token0,
address token1,
uint24 swapFeeUnits,
int24 tickDistance
| function parameters()
external
view
returns (
address factory,
address poolOracle,
address token0,
address token1,
uint24 swapFeeUnits,
int24 tickDistance
| 30,832 |
52 | // Whitelist The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. This simplifies the implementation of "user permissions". / | contract Whitelist is Ownable, RBAC {
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
checkRole(msg.sender, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr)
onlyOwner
public
{
addRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressAdded(addr);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address addr)
public
view
returns (bool)
{
return hasRole(addr, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr)
onlyOwner
public
{
removeRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressRemoved(addr);
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
removeAddressFromWhitelist(addrs[i]);
}
}
}
| contract Whitelist is Ownable, RBAC {
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
checkRole(msg.sender, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr)
onlyOwner
public
{
addRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressAdded(addr);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address addr)
public
view
returns (bool)
{
return hasRole(addr, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr)
onlyOwner
public
{
removeRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressRemoved(addr);
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
removeAddressFromWhitelist(addrs[i]);
}
}
}
| 1,111 |
34 | // Returns hypothetical reserves of metapool if the FRAX price went to the CR, assuming no removal of liquidity from the metapool. | function iterate() public view returns (uint256, uint256, uint256) {
uint256 frax_balance = FRAX.balanceOf(frax3crv_metapool_address);
uint256 crv3_balance = three_pool_erc20.balanceOf(frax3crv_metapool_address);
uint256 floor_price_frax = uint(1e18).mul(fraxFloor()).div(1e6);
uint256 crv3_received;
uint256 dollar_value; // 3crv is usually slightly above $1 due to collecting 3pool swap fees
uint256 virtual_price = three_pool.get_virtual_price();
for(uint i = 0; i < 256; i++){
crv3_received = frax3crv_metapool.get_dy(0, 1, 1e18, [frax_balance, crv3_balance]);
dollar_value = crv3_received.mul(1e18).div(virtual_price);
if(dollar_value <= floor_price_frax.add(convergence_window)){
return (frax_balance, crv3_balance, i);
}
uint256 frax_to_swap = frax_balance.div(10);
crv3_balance = crv3_balance.sub(frax3crv_metapool.get_dy(0, 1, frax_to_swap, [frax_balance, crv3_balance]));
frax_balance = frax_balance.add(frax_to_swap);
}
revert("No hypothetical point"); // in 256 rounds
}
| function iterate() public view returns (uint256, uint256, uint256) {
uint256 frax_balance = FRAX.balanceOf(frax3crv_metapool_address);
uint256 crv3_balance = three_pool_erc20.balanceOf(frax3crv_metapool_address);
uint256 floor_price_frax = uint(1e18).mul(fraxFloor()).div(1e6);
uint256 crv3_received;
uint256 dollar_value; // 3crv is usually slightly above $1 due to collecting 3pool swap fees
uint256 virtual_price = three_pool.get_virtual_price();
for(uint i = 0; i < 256; i++){
crv3_received = frax3crv_metapool.get_dy(0, 1, 1e18, [frax_balance, crv3_balance]);
dollar_value = crv3_received.mul(1e18).div(virtual_price);
if(dollar_value <= floor_price_frax.add(convergence_window)){
return (frax_balance, crv3_balance, i);
}
uint256 frax_to_swap = frax_balance.div(10);
crv3_balance = crv3_balance.sub(frax3crv_metapool.get_dy(0, 1, frax_to_swap, [frax_balance, crv3_balance]));
frax_balance = frax_balance.add(frax_to_swap);
}
revert("No hypothetical point"); // in 256 rounds
}
| 36,172 |
112 | // Time dYdX Library for dealing with time, assuming timestamps fit within 32 bits (valid until year 2106) / | library Time {
// ============ Library Functions ============
function currentTime()
internal
view
returns (uint32)
{
return Math.to32(block.timestamp);
}
}
| library Time {
// ============ Library Functions ============
function currentTime()
internal
view
returns (uint32)
{
return Math.to32(block.timestamp);
}
}
| 59,119 |
544 | // withdrawFromSP(): - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between all depositors and front ends - Removes the deposit's front end tag if it is a full withdrawal - Sends all depositor's accumulated gains (LQTY, ETH) to depositor - Sends the tagged front end's accumulated LQTY gains to the tagged front end - Decreases deposit and tagged front end's stake, and takes new snapshots for each. If _amount > userDeposit, the user withdraws all of their compounded deposit./ | function withdrawFromSP(uint _amount) external override {
if (_amount !=0) {_requireNoUnderCollateralizedTroves();}
uint initialDeposit = deposits[msg.sender].initialValue;
_requireUserHasDeposit(initialDeposit);
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDtoWithdraw = LiquityMath._min(_amount, compoundedLUSDDeposit);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake.sub(LUSDtoWithdraw);
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_sendLUSDToDepositor(msg.sender, LUSDtoWithdraw);
// Update deposit
uint newDeposit = compoundedLUSDDeposit.sub(LUSDtoWithdraw);
_updateDepositAndSnapshots(msg.sender, newDeposit);
emit UserDepositChanged(msg.sender, newDeposit);
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log
_sendETHGainToDepositor(depositorETHGain);
}
| function withdrawFromSP(uint _amount) external override {
if (_amount !=0) {_requireNoUnderCollateralizedTroves();}
uint initialDeposit = deposits[msg.sender].initialValue;
_requireUserHasDeposit(initialDeposit);
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDtoWithdraw = LiquityMath._min(_amount, compoundedLUSDDeposit);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake.sub(LUSDtoWithdraw);
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_sendLUSDToDepositor(msg.sender, LUSDtoWithdraw);
// Update deposit
uint newDeposit = compoundedLUSDDeposit.sub(LUSDtoWithdraw);
_updateDepositAndSnapshots(msg.sender, newDeposit);
emit UserDepositChanged(msg.sender, newDeposit);
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log
_sendETHGainToDepositor(depositorETHGain);
}
| 41,022 |
9 | // actualCharge is an _estimated_ charge, which assumes postRelayedCall will use all available gas. This implementation's gas cost can be roughly estimated as 10k gas, for the two SSTORE operations in an ERC20 transfer. | uint256 overestimation = _computeCharge(POST_RELAYED_CALL_MAX_GAS.sub(10000), gasPrice, transactionFee);
actualCharge = actualCharge.sub(overestimation);
| uint256 overestimation = _computeCharge(POST_RELAYED_CALL_MAX_GAS.sub(10000), gasPrice, transactionFee);
actualCharge = actualCharge.sub(overestimation);
| 11,710 |
124 | // Base IBearRenderer | abstract contract BearRenderer is IBearRenderer {
using Strings for uint256;
/// @dev The IBearRenderTechProvider for this IBearRenderer
IBearRenderTechProvider internal immutable _renderTech;
/// @dev Constructs a new instance passing in the IBearRenderTechProvider
constructor(address renderTech) {
_renderTech = IBearRenderTechProvider(renderTech);
}
/// The ear ratio to apply based on the genes and token id
/// @param geneBytes The Bear's genes as bytes22
/// @param tokenId The Bear's Token Id
/// @return ratio The ear ratio as a uint
function earRatio(bytes22 geneBytes, uint256 tokenId) internal pure returns (uint ratio) {
ratio = uint8(geneBytes[(tokenId + 21) % 22]);
}
/// The eye ratio to apply based on the genes and token id
/// @param geneBytes The Bear's genes as bytes22
/// @param tokenId The Bear's Token Id
/// @return The eye ratio as a uint8
function eyeRatio(bytes22 geneBytes, uint256 tokenId) internal pure returns (uint8) {
return uint8(geneBytes[(tokenId + 20) % 22]);
}
/// The jowl ratio to apply based on the genes and token id
/// @param geneBytes The Bear's genes as bytes22
/// @param tokenId The Bear's Token Id
/// @return The jowl ratio as a uint8
function jowlRatio(bytes22 geneBytes, uint256 tokenId) internal pure returns (uint8) {
return uint8(geneBytes[(tokenId + 19) % 22]);
}
/// Prevents a function from executing if not called by the IBearRenderTechProvider
modifier onlyRenderTech() {
if (msg.sender != address(_renderTech)) revert OnlyBearRenderTech();
_;
}
function _assignScars(uint surfaceCount, IBear3Traits.ScarColor[] memory scars, bytes22 genes, uint256 tokenId) internal pure returns (IBear3Traits.ScarColor[] memory initializedScars) {
initializedScars = new IBear3Traits.ScarColor[](surfaceCount);
uint scarIndex = scars.length;
for (uint i = 0; i < surfaceCount; i++) {
if (scarIndex > 0 && scars[0] != IBear3Traits.ScarColor.None) {
// The further we get, the more likely we assign the next scar (i.e. decrease the divisor)
uint random = uint8(genes[(tokenId+i) % 18]);
uint remaining = 1 + surfaceCount - i;
if (random % remaining <= 1) { // Give our modulo a little push with <=
initializedScars[i] = scars[--scarIndex];
continue;
}
}
initializedScars[i] = IBear3Traits.ScarColor.None;
}
}
function _firstStop(ISVGTypes.Color memory color) internal pure returns (bytes memory) {
return abi.encodePacked(" stop-color='", SVG.colorAttributeRGBValue(color) , "'");
}
function _firstStopPacked(uint24 packedColor) internal pure returns (bytes memory) {
return _firstStop(SVG.fromPackedColor(packedColor));
}
function _lastStop(ISVGTypes.Color memory color) internal pure returns (bytes memory) {
return abi.encodePacked(" offset='1' stop-color='", SVG.colorAttributeRGBValue(color) , "'");
}
function _lastStopPacked(uint24 packedColor) internal pure returns (bytes memory) {
return _lastStop(SVG.fromPackedColor(packedColor));
}
function _scarColor(IBear3Traits.ScarColor scarColor) internal pure returns (ISVGTypes.Color memory, ISVGTypes.Color memory) {
if (scarColor == IBear3Traits.ScarColor.Blue) {
return (SVG.fromPackedColor(0x1795BA), SVG.fromPackedColor(0x9CF3FF));
} else if (scarColor == IBear3Traits.ScarColor.Magenta) {
return (SVG.fromPackedColor(0x9D143E), SVG.fromPackedColor(0xDB3F74));
} else /* if (scarColor == IBear3Traits.ScarColor.Gold) */ {
return (SVG.fromPackedColor(0xA06E01), SVG.fromPackedColor(0xFFC701));
}
}
function _surfaceGradient(uint id, bytes memory points, uint24 firstStop, uint24 lastStop, IBear3Traits.ScarColor[] memory assignedScars) internal view returns (bytes memory) {
bytes memory identifier = abi.encodePacked("paint", id.toString());
if (assignedScars[id] == IBear3Traits.ScarColor.None) {
return _renderTech.linearGradient(identifier, points, _firstStopPacked(firstStop), _lastStopPacked(lastStop));
}
(ISVGTypes.Color memory lower, ISVGTypes.Color memory higher) = _scarColor(assignedScars[id]);
(ISVGTypes.Color memory first, ISVGTypes.Color memory last) = firstStop < lastStop ? (lower, higher) : (higher, lower);
return _renderTech.linearGradient(identifier, points, _firstStop(first), _lastStop(last));
}
}
| abstract contract BearRenderer is IBearRenderer {
using Strings for uint256;
/// @dev The IBearRenderTechProvider for this IBearRenderer
IBearRenderTechProvider internal immutable _renderTech;
/// @dev Constructs a new instance passing in the IBearRenderTechProvider
constructor(address renderTech) {
_renderTech = IBearRenderTechProvider(renderTech);
}
/// The ear ratio to apply based on the genes and token id
/// @param geneBytes The Bear's genes as bytes22
/// @param tokenId The Bear's Token Id
/// @return ratio The ear ratio as a uint
function earRatio(bytes22 geneBytes, uint256 tokenId) internal pure returns (uint ratio) {
ratio = uint8(geneBytes[(tokenId + 21) % 22]);
}
/// The eye ratio to apply based on the genes and token id
/// @param geneBytes The Bear's genes as bytes22
/// @param tokenId The Bear's Token Id
/// @return The eye ratio as a uint8
function eyeRatio(bytes22 geneBytes, uint256 tokenId) internal pure returns (uint8) {
return uint8(geneBytes[(tokenId + 20) % 22]);
}
/// The jowl ratio to apply based on the genes and token id
/// @param geneBytes The Bear's genes as bytes22
/// @param tokenId The Bear's Token Id
/// @return The jowl ratio as a uint8
function jowlRatio(bytes22 geneBytes, uint256 tokenId) internal pure returns (uint8) {
return uint8(geneBytes[(tokenId + 19) % 22]);
}
/// Prevents a function from executing if not called by the IBearRenderTechProvider
modifier onlyRenderTech() {
if (msg.sender != address(_renderTech)) revert OnlyBearRenderTech();
_;
}
function _assignScars(uint surfaceCount, IBear3Traits.ScarColor[] memory scars, bytes22 genes, uint256 tokenId) internal pure returns (IBear3Traits.ScarColor[] memory initializedScars) {
initializedScars = new IBear3Traits.ScarColor[](surfaceCount);
uint scarIndex = scars.length;
for (uint i = 0; i < surfaceCount; i++) {
if (scarIndex > 0 && scars[0] != IBear3Traits.ScarColor.None) {
// The further we get, the more likely we assign the next scar (i.e. decrease the divisor)
uint random = uint8(genes[(tokenId+i) % 18]);
uint remaining = 1 + surfaceCount - i;
if (random % remaining <= 1) { // Give our modulo a little push with <=
initializedScars[i] = scars[--scarIndex];
continue;
}
}
initializedScars[i] = IBear3Traits.ScarColor.None;
}
}
function _firstStop(ISVGTypes.Color memory color) internal pure returns (bytes memory) {
return abi.encodePacked(" stop-color='", SVG.colorAttributeRGBValue(color) , "'");
}
function _firstStopPacked(uint24 packedColor) internal pure returns (bytes memory) {
return _firstStop(SVG.fromPackedColor(packedColor));
}
function _lastStop(ISVGTypes.Color memory color) internal pure returns (bytes memory) {
return abi.encodePacked(" offset='1' stop-color='", SVG.colorAttributeRGBValue(color) , "'");
}
function _lastStopPacked(uint24 packedColor) internal pure returns (bytes memory) {
return _lastStop(SVG.fromPackedColor(packedColor));
}
function _scarColor(IBear3Traits.ScarColor scarColor) internal pure returns (ISVGTypes.Color memory, ISVGTypes.Color memory) {
if (scarColor == IBear3Traits.ScarColor.Blue) {
return (SVG.fromPackedColor(0x1795BA), SVG.fromPackedColor(0x9CF3FF));
} else if (scarColor == IBear3Traits.ScarColor.Magenta) {
return (SVG.fromPackedColor(0x9D143E), SVG.fromPackedColor(0xDB3F74));
} else /* if (scarColor == IBear3Traits.ScarColor.Gold) */ {
return (SVG.fromPackedColor(0xA06E01), SVG.fromPackedColor(0xFFC701));
}
}
function _surfaceGradient(uint id, bytes memory points, uint24 firstStop, uint24 lastStop, IBear3Traits.ScarColor[] memory assignedScars) internal view returns (bytes memory) {
bytes memory identifier = abi.encodePacked("paint", id.toString());
if (assignedScars[id] == IBear3Traits.ScarColor.None) {
return _renderTech.linearGradient(identifier, points, _firstStopPacked(firstStop), _lastStopPacked(lastStop));
}
(ISVGTypes.Color memory lower, ISVGTypes.Color memory higher) = _scarColor(assignedScars[id]);
(ISVGTypes.Color memory first, ISVGTypes.Color memory last) = firstStop < lastStop ? (lower, higher) : (higher, lower);
return _renderTech.linearGradient(identifier, points, _firstStop(first), _lastStop(last));
}
}
| 81,304 |
2 | // The map of lock ids to pending custodian changes. | mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
| mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
| 45,017 |
127 | // Emit an event | emit LogDarknodeDeregistered(_darknodeID);
| emit LogDarknodeDeregistered(_darknodeID);
| 38,100 |
171 | // Safely mints 'tokenId' and transfers it to 'to'. Requirements: - 'tokenId' must not exist. | * - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
| * - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
| 71,060 |
210 | // View function to see pending JOEs on frontend. | function pendingTokens(uint256 _pid, address _user)
external
view
returns (
uint256 pendingJoe
)
| function pendingTokens(uint256 _pid, address _user)
external
view
returns (
uint256 pendingJoe
)
| 9,099 |
3 | // For any call to the contract (except for querying the `implementation` address) do a delegate/ call. | fallback() external payable {
// CG: using this assembly instead of the delegate call of solidity allows us to return values in this
// fallback function.
assembly
{
let _target := sload(0)
calldatacopy(0x0, 0x0, calldatasize())
let result := delegatecall(gas(), _target, 0x0, calldatasize(), 0x0, 0)
returndatacopy(0x0, 0x0, returndatasize())
switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())}
}
}
| fallback() external payable {
// CG: using this assembly instead of the delegate call of solidity allows us to return values in this
// fallback function.
assembly
{
let _target := sload(0)
calldatacopy(0x0, 0x0, calldatasize())
let result := delegatecall(gas(), _target, 0x0, calldatasize(), 0x0, 0)
returndatacopy(0x0, 0x0, returndatasize())
switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())}
}
}
| 49,856 |
119 | // Transfer out underlying asset | if (_underlyingTokenAddress == address(0x0)) {
TransferHelper.safeTransferETH(msg.sender, uTokenAmount);
} else {
| if (_underlyingTokenAddress == address(0x0)) {
TransferHelper.safeTransferETH(msg.sender, uTokenAmount);
} else {
| 45,556 |
11 | // 2% harvert tax | token.mint(_user, harvestAmount.mul(98).div(100));
emit Harvested(_user, harvestAmount, _pool);
| token.mint(_user, harvestAmount.mul(98).div(100));
emit Harvested(_user, harvestAmount, _pool);
| 14,997 |
19 | // There are multiple mintlists in this sale. Which one are we using now? | uint256 public currentMerkleRootIndex;
| uint256 public currentMerkleRootIndex;
| 33,153 |
304 | // if we have nothing borrowed then we can't deleverage any more | if (borrowed == 0 && deficit) {
return 0;
}
| if (borrowed == 0 && deficit) {
return 0;
}
| 40,887 |
166 | // Maximum weight for token | uint public constant MAX_WEIGHT = BONE * 50;
| uint public constant MAX_WEIGHT = BONE * 50;
| 23,138 |
6 | // Specify a new base URI for item metadata | function setBaseURI (
string memory new_uri
| function setBaseURI (
string memory new_uri
| 9,357 |
71 | // add tokens to AAC UID | coloredTokens[_colorIndex].balances[_to[i]] += _tokens;
| coloredTokens[_colorIndex].balances[_to[i]] += _tokens;
| 33,384 |
1 | // Setup contract with given params Used by Initializable contract (can be called only once) manager Address to which MANAGER_ROLE should be granted / | function initialize(address manager) external;
| function initialize(address manager) external;
| 5,696 |
1 | // address owner | address public owner;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 public totalSupply;
mapping(address => uint256) public balances;
mapping(uint256 => address) public stakedAssets;
| address public owner;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 public totalSupply;
mapping(address => uint256) public balances;
mapping(uint256 => address) public stakedAssets;
| 11,972 |
18 | // Transfer tokens from other address / | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (block.number < tokenFrozenUntilBlock) throw; // Throw is token is frozen in case of emergency
require(_value <= allowed[_from][msg.sender]); // Check allowance
allowed[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (block.number < tokenFrozenUntilBlock) throw; // Throw is token is frozen in case of emergency
require(_value <= allowed[_from][msg.sender]); // Check allowance
allowed[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| 54,047 |
17 | // 1: Regular, 2: Premium, 3: Royal, 4: Special | uint256 prefix = uint256(SafeMath.div(stakingList[user].tokenIds[i], 1000000));
uint256 ratio = 0;
if (prefix == 1) {
ratio = regular;
}
| uint256 prefix = uint256(SafeMath.div(stakingList[user].tokenIds[i], 1000000));
uint256 ratio = 0;
if (prefix == 1) {
ratio = regular;
}
| 19,012 |
277 | // Updates and treats the reward of before DIP4 as already received. / | function __updateLegacyWithdrawableInterestAmount(
address _property,
address _user
| function __updateLegacyWithdrawableInterestAmount(
address _property,
address _user
| 10,670 |
15 | // Approve `spender` to transfer up to `amount` from `src`This will overwrite the approval amount for `spender`spender The address of the account which may transfer tokensamount The number of tokens that are approved return Whether or not the approval succeeded/ | function approve(address spender, uint256 amount) external returns (bool success);
| function approve(address spender, uint256 amount) external returns (bool success);
| 15,336 |
35 | // See {IERC20-mint}. Requirements: - `recipient` cannot be the zero address.- the caller must have a balance of at least `amount`. / |
function mint(address recipient, uint256 amount) hasPermissionToMint public virtual returns (bool) {
_mint(recipient, amount);
return true;
}
|
function mint(address recipient, uint256 amount) hasPermissionToMint public virtual returns (bool) {
_mint(recipient, amount);
return true;
}
| 9,828 |
21 | // Copy msg.data. | calldatacopy(0, 0, calldatasize)
| calldatacopy(0, 0, calldatasize)
| 24,077 |
4 | // 定義創世神才能執行 | modifier OnlyOwner {
require(owner != address(0) && msg.sender == owner);
_;
}
| modifier OnlyOwner {
require(owner != address(0) && msg.sender == owner);
_;
}
| 33,391 |
45 | // An event to make the transfer easy to find on the blockchain | Transfer(_from, _to, _amount);
| Transfer(_from, _to, _amount);
| 78,727 |
33 | // Raffle for rare items | function buyRaffleTicket(uint256 amount) external {
require(raffleEndTime >= block.timestamp); //close it if need test
require(amount > 0 && amount<=MAX_LIMIT);
uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_PRICE, amount);
require(cards.balanceOf(msg.sender) >= ticketsCost);
// Update player's jade
cards.updatePlayersCoinByPurchase(msg.sender, ticketsCost);
// Handle new tickets
TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender];
// If we need to reset tickets from a previous raffle
if (purchases.raffleRareId != raffleRareId) {
purchases.numPurchases = 0;
purchases.raffleRareId = raffleRareId;
rafflePlayers[raffleRareId].push(msg.sender); // Add user to raffle
}
// Store new ticket purchase
if (purchases.numPurchases == purchases.ticketsBought.length) {
purchases.ticketsBought.length = SafeMath.add(purchases.ticketsBought.length,1);
}
purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(raffleTicketsBought, raffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9)
// Finally update ticket total
raffleTicketsBought = SafeMath.add(raffleTicketsBought,amount);
//event
UnitBought(msg.sender,raffleRareId,amount);
}
| function buyRaffleTicket(uint256 amount) external {
require(raffleEndTime >= block.timestamp); //close it if need test
require(amount > 0 && amount<=MAX_LIMIT);
uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_PRICE, amount);
require(cards.balanceOf(msg.sender) >= ticketsCost);
// Update player's jade
cards.updatePlayersCoinByPurchase(msg.sender, ticketsCost);
// Handle new tickets
TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender];
// If we need to reset tickets from a previous raffle
if (purchases.raffleRareId != raffleRareId) {
purchases.numPurchases = 0;
purchases.raffleRareId = raffleRareId;
rafflePlayers[raffleRareId].push(msg.sender); // Add user to raffle
}
// Store new ticket purchase
if (purchases.numPurchases == purchases.ticketsBought.length) {
purchases.ticketsBought.length = SafeMath.add(purchases.ticketsBought.length,1);
}
purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(raffleTicketsBought, raffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9)
// Finally update ticket total
raffleTicketsBought = SafeMath.add(raffleTicketsBought,amount);
//event
UnitBought(msg.sender,raffleRareId,amount);
}
| 52,383 |
1 | // Set TellorMaster address _TellorMasterAddress is the Tellor Master address/ | function setTellorMaster(address payable _TellorMasterAddress) public {
require(msg.sender == owner, "Sender is not owner");
tellorMasterAddress = _TellorMasterAddress;
tellorMaster = TellorMaster(_TellorMasterAddress);
}
| function setTellorMaster(address payable _TellorMasterAddress) public {
require(msg.sender == owner, "Sender is not owner");
tellorMasterAddress = _TellorMasterAddress;
tellorMaster = TellorMaster(_TellorMasterAddress);
}
| 41,015 |
14 | // transfer/license the IP to the order taker | uint256 orderType = storageContract.getUint(keccak256("order.type", _marketplaceAddress, _orderIndex));
address takerAddress = storageContract.getAddress(keccak256("order.taker.address", _marketplaceAddress, _orderIndex));
require(ipRightToken.executeOrder(ipIndex, orderType, ipOwner, takerAddress) == true);
| uint256 orderType = storageContract.getUint(keccak256("order.type", _marketplaceAddress, _orderIndex));
address takerAddress = storageContract.getAddress(keccak256("order.taker.address", _marketplaceAddress, _orderIndex));
require(ipRightToken.executeOrder(ipIndex, orderType, ipOwner, takerAddress) == true);
| 3,959 |
27 | // withdraw | function _withdraw() internal {
require(auctionSettled == true && block.timestamp > auctionEndDateTime, 'Auction not settled||not ended.');
(bool success, ) = payee.call{value: address(this).balance}('');
require(success, 'Failed to send to payee.');
}
| function _withdraw() internal {
require(auctionSettled == true && block.timestamp > auctionEndDateTime, 'Auction not settled||not ended.');
(bool success, ) = payee.call{value: address(this).balance}('');
require(success, 'Failed to send to payee.');
}
| 17,140 |
9 | // Number of reward tokens distributed per block for this pool | mapping(uint256 => uint256) public poolIdToRewardPerBlock;
| mapping(uint256 => uint256) public poolIdToRewardPerBlock;
| 72,194 |
4,544 | // 2273 | entry "uneased" : ENG_ADJECTIVE
| entry "uneased" : ENG_ADJECTIVE
| 18,885 |
108 | // Creates a new validator ID that includes a validator name, description,commission or fee rate, and a minimum delegation amount accepted by the validator. | * Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
| * Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
| 81,572 |
35 | // Sets the guaranteed merkle root for the mint _guaranteedMerkleRoot The merkle root to set / | function setGuaranteedMerkleRoot(bytes32 _guaranteedMerkleRoot)
external
onlyOwner
| function setGuaranteedMerkleRoot(bytes32 _guaranteedMerkleRoot)
external
onlyOwner
| 10,956 |
40 | // helper | function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
| function isWhiteListed(address verifier) view public returns(bool){
return !useWhiteList || whitelist[verifier];
}
| 43,927 |
4 | // Provides a descriptive tag for bot consumption This should be modified weekly to provide a summary of the actions | string constant public description = "2020-08-24 Test Spell";
address constant public MCD_JUG = 0xF38d987939084c68a2078Ff6FC8804a994197eBC;
| string constant public description = "2020-08-24 Test Spell";
address constant public MCD_JUG = 0xF38d987939084c68a2078Ff6FC8804a994197eBC;
| 47,633 |
32 | // set the delta pot payout fraction./ every epoch,/ a fraction of the delta pot is payed out./ Only theOwner, the DAO is allowed to set the delta pot payout fraction. | function setdeltaPotPayoutFraction(uint256 _value)
external
| function setdeltaPotPayoutFraction(uint256 _value)
external
| 15,134 |
2 | // EIP712 Domain Version value | string constant internal EIP712_DOMAIN_VERSION = "2";
| string constant internal EIP712_DOMAIN_VERSION = "2";
| 5,787 |
347 | // Reentrancy Guard | bool private _entered;
bool public _eventSend;
Destinations public destinations;
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
| bool private _entered;
bool public _eventSend;
Destinations public destinations;
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
| 47,546 |
8 | // fetches all posts / | function fetchPosts() public view returns (Post[] memory) {
uint256 itemCount = _postIds.current();
Post[] memory posts = new Post[](itemCount);
for (uint256 i = 0; i < itemCount; i++) {
uint256 currentId = i + 1;
Post storage currentItem = idToPost[currentId];
posts[i] = currentItem;
}
return posts;
}
| function fetchPosts() public view returns (Post[] memory) {
uint256 itemCount = _postIds.current();
Post[] memory posts = new Post[](itemCount);
for (uint256 i = 0; i < itemCount; i++) {
uint256 currentId = i + 1;
Post storage currentItem = idToPost[currentId];
posts[i] = currentItem;
}
return posts;
}
| 16,453 |
17 | // Start timestamp != 0 is a sufficient condition for a claim to exist This is because we only ever add claims (or modify startTs) in the createClaim function Which requires that its input startTimestamp be nonzero So therefore, a zero value for this indicates the claim does not exist. | require(_claim.startTimestamp == 0, "CLAIM_ALREADY_EXISTS");
| require(_claim.startTimestamp == 0, "CLAIM_ALREADY_EXISTS");
| 22,118 |
11 | // | function _mintWithURI(address _to, uint256 _tokenId, string memory _tokenURI) internal {
_mint(_to, _tokenId);
_setTokenURI(_tokenId, _tokenURI);
}
| function _mintWithURI(address _to, uint256 _tokenId, string memory _tokenURI) internal {
_mint(_to, _tokenId);
_setTokenURI(_tokenId, _tokenURI);
}
| 38,058 |
198 | // `msgSender == from || msgSender == approvedAddress`. | result := or(eq(msgSender, from), eq(msgSender, approvedAddress))
| result := or(eq(msgSender, from), eq(msgSender, approvedAddress))
| 24,216 |
65 | // /Token contract | contract HERO is TokenDetailed, ERC20Burnable, Stoppable {
constructor (
string memory name,
string memory symbol,
uint256 totalSupply,
uint8 decimals
) TokenDetailed(name, symbol, decimals)
public {
_mint(owner(), totalSupply * 10**uint(decimals));
}
// Don't accept ETH
function () payable external {
revert();
}
//------------------------
// Lock account transfer
mapping (address => uint256) private _lockTimes;
mapping (address => uint256) private _lockAmounts;
event LockChanged(address indexed account, uint256 releaseTime, uint256 amount);
/// Lock user amount. (run only owner)
/// @param account account to lock
/// @param releaseTime Time to release from lock state.
/// @param amount amount to lock.
/// @return Boolean
function setLock(address account, uint256 releaseTime, uint256 amount) onlyOwner public {
//require(now < releaseTime, "ERC20 : Current time is greater than release time");
require(block.timestamp < releaseTime, "ERC20 : Current time is greater than release time");
require(amount != 0, "ERC20: Amount error");
_lockTimes[account] = releaseTime;
_lockAmounts[account] = amount;
emit LockChanged( account, releaseTime, amount );
}
/// Get Lock information (run anyone)
/// @param account user acount
/// @return lokced time and locked amount.
function getLock(address account) public view returns (uint256 lockTime, uint256 lockAmount) {
return (_lockTimes[account], _lockAmounts[account]);
}
/// Check lock state (run anyone)
/// @param account user acount
/// @param amount amount to check.
/// @return Boolean : Don't use balance (true)
function _isLocked(address account, uint256 amount) internal view returns (bool) {
return _lockAmounts[account] != 0 &&
_lockTimes[account] > block.timestamp &&
(
balanceOf(account) <= _lockAmounts[account] ||
balanceOf(account).sub(_lockAmounts[account]) < amount
);
}
/// Transfer token (run anyone)
/// @param recipient Token trasfer destination acount.
/// @param amount Token transfer amount.
/// @return Boolean
function transfer(address recipient, uint256 amount) enabled public returns (bool) {
require( !_isLocked( msg.sender, amount ) , "ERC20: Locked balance");
return super.transfer(recipient, amount);
}
/// Transfer token (run anyone)
/// @param sender Token trasfer source acount.
/// @param recipient Token transfer destination acount.
/// @param amount Token transfer amount.
/// @return Boolean
function transferFrom(address sender, address recipient, uint256 amount) enabled public returns (bool) {
require( !_isLocked( sender, amount ) , "ERC20: Locked balance");
return super.transferFrom(sender, recipient, amount);
}
/// Decrease token balance (run only owner)
/// @param value Amount to decrease.
function burn(uint256 value) onlyOwner public {
require( !_isLocked( msg.sender, value ) , "ERC20: Locked balance");
super.burn(value);
}
} | contract HERO is TokenDetailed, ERC20Burnable, Stoppable {
constructor (
string memory name,
string memory symbol,
uint256 totalSupply,
uint8 decimals
) TokenDetailed(name, symbol, decimals)
public {
_mint(owner(), totalSupply * 10**uint(decimals));
}
// Don't accept ETH
function () payable external {
revert();
}
//------------------------
// Lock account transfer
mapping (address => uint256) private _lockTimes;
mapping (address => uint256) private _lockAmounts;
event LockChanged(address indexed account, uint256 releaseTime, uint256 amount);
/// Lock user amount. (run only owner)
/// @param account account to lock
/// @param releaseTime Time to release from lock state.
/// @param amount amount to lock.
/// @return Boolean
function setLock(address account, uint256 releaseTime, uint256 amount) onlyOwner public {
//require(now < releaseTime, "ERC20 : Current time is greater than release time");
require(block.timestamp < releaseTime, "ERC20 : Current time is greater than release time");
require(amount != 0, "ERC20: Amount error");
_lockTimes[account] = releaseTime;
_lockAmounts[account] = amount;
emit LockChanged( account, releaseTime, amount );
}
/// Get Lock information (run anyone)
/// @param account user acount
/// @return lokced time and locked amount.
function getLock(address account) public view returns (uint256 lockTime, uint256 lockAmount) {
return (_lockTimes[account], _lockAmounts[account]);
}
/// Check lock state (run anyone)
/// @param account user acount
/// @param amount amount to check.
/// @return Boolean : Don't use balance (true)
function _isLocked(address account, uint256 amount) internal view returns (bool) {
return _lockAmounts[account] != 0 &&
_lockTimes[account] > block.timestamp &&
(
balanceOf(account) <= _lockAmounts[account] ||
balanceOf(account).sub(_lockAmounts[account]) < amount
);
}
/// Transfer token (run anyone)
/// @param recipient Token trasfer destination acount.
/// @param amount Token transfer amount.
/// @return Boolean
function transfer(address recipient, uint256 amount) enabled public returns (bool) {
require( !_isLocked( msg.sender, amount ) , "ERC20: Locked balance");
return super.transfer(recipient, amount);
}
/// Transfer token (run anyone)
/// @param sender Token trasfer source acount.
/// @param recipient Token transfer destination acount.
/// @param amount Token transfer amount.
/// @return Boolean
function transferFrom(address sender, address recipient, uint256 amount) enabled public returns (bool) {
require( !_isLocked( sender, amount ) , "ERC20: Locked balance");
return super.transferFrom(sender, recipient, amount);
}
/// Decrease token balance (run only owner)
/// @param value Amount to decrease.
function burn(uint256 value) onlyOwner public {
require( !_isLocked( msg.sender, value ) , "ERC20: Locked balance");
super.burn(value);
}
} | 9,879 |
3 | // Crowdsale Stage functions // Public Account Functionality/ function to participate in the crowdsale by contributing ETH, limit represent the TBN per ETH limit a user would like to enforce (0 means no limit set, free participation) | function participate(uint256 limit) external payable returns (bool);
| function participate(uint256 limit) external payable returns (bool);
| 37,901 |
261 | // Perform implementation upgrade with additional setup call. | * Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
| * Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
| 2,685 |
5 | // function mint() external virtual payable; |
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
|
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
| 9,247 |
177 | // import "@nomiclabs/buidler/console.sol"; | interface IMigratorChef {
// Perform LP token migration from legacy PancakeSwap to CakeSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to PancakeSwap LP tokens.
// CakeSwap must mint EXACTLY the same amount of CakeSwap LP tokens or
// else something bad will happen. Traditional PancakeSwap does not
// do that so be careful!
function migrate(IBEP20 token) external returns (IBEP20);
}
| interface IMigratorChef {
// Perform LP token migration from legacy PancakeSwap to CakeSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to PancakeSwap LP tokens.
// CakeSwap must mint EXACTLY the same amount of CakeSwap LP tokens or
// else something bad will happen. Traditional PancakeSwap does not
// do that so be careful!
function migrate(IBEP20 token) external returns (IBEP20);
}
| 2,317 |
9 | // Opens a new position in the Beta smart contract. | function open(
address _owner,
address _underlying,
address _collateral
) external returns (uint pid);
| function open(
address _owner,
address _underlying,
address _collateral
) external returns (uint pid);
| 28,664 |
100 | // Transfer tokens from one address to another and then call `onTransferReceived` on receiver sender address The address which you want to send tokens from recipient address The address which you want to transfer to amount uint256 The amount of tokens to be transferredreturn true unless throwing / | function transferFromAndCall(
address sender,
| function transferFromAndCall(
address sender,
| 18,059 |
395 | // if the claim doesn't yet exist, store it in state | if (cur == 0)
{
| if (cur == 0)
{
| 14,962 |
209 | // View function to see pending GRIFFINs on frontend. | function pendingGriffin(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accGriffinPerShare = pool.accGriffinPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 griffinReward = multiplier.mul(griffinPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accGriffinPerShare = accGriffinPerShare.add(griffinReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accGriffinPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingGriffin(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accGriffinPerShare = pool.accGriffinPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 griffinReward = multiplier.mul(griffinPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accGriffinPerShare = accGriffinPerShare.add(griffinReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accGriffinPerShare).div(1e12).sub(user.rewardDebt);
}
| 25,179 |
178 | // Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex account The address whose balance should be calculated after updating borrowIndexreturn The calculated balance / | function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
| function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
| 5,332 |
39 | // withdraw stuck funds | function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
| function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
| 1,003 |
26 | // should only be called by controller | function salvage(address destination, address token, uint256 amount) external restricted {
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(destination, amount);
}
| function salvage(address destination, address token, uint256 amount) external restricted {
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(destination, amount);
}
| 30,610 |
430 | // remove any empty slots | uint256 nToCull = culledTrisWorldSpace.length - nextIx;
| uint256 nToCull = culledTrisWorldSpace.length - nextIx;
| 72,141 |
19 | // retrieve the size of the code on target address, this needs assembly | length := extcodesize(_addr)
| length := extcodesize(_addr)
| 11,028 |
16 | // Sets how many Witnet nodes will be "hired" for resolving the request./_numWitnesses Number of witnesses required to be involved for solving this Witnet Data Request./_minWitnessingConsensus Threshold percentage for aborting resolution of a request if the witnessing / nodes did not arrive to a broad consensus. | function setWitnessingQuorum(uint8 _numWitnesses, uint8 _minWitnessingConsensus)
public
virtual
onlyOwner
| function setWitnessingQuorum(uint8 _numWitnesses, uint8 _minWitnessingConsensus)
public
virtual
onlyOwner
| 43,064 |
69 | // Trade ETH to token _uniswapFactory - Address of uniswap v1 factory _token - Address of the output token _amount - uint256 of the ETH amount _dest - Address of the trade recipientreturn bought - Amount of output token bought / | function _ethToToken(
IUniswapFactory _uniswapFactory,
IERC20 _token,
uint256 _amount,
address _dest
| function _ethToToken(
IUniswapFactory _uniswapFactory,
IERC20 _token,
uint256 _amount,
address _dest
| 40,807 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.