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
|
---|---|---|---|---|
21 | // The duration of voting on a proposal, in blocks | uint256 public votingPeriod;
| uint256 public votingPeriod;
| 24,388 |
18 | // Lock flag | uint256 _locked;
| uint256 _locked;
| 5,052 |
53 | // block.blockhash - hash of the given block - only works for 256 most recent blocks excluding current | bytes32 blockHash = block.blockhash(playerblock+BlockDelay);
if (blockHash==0)
{
ErrorLog(msg.sender, "Cannot generate random number");
wheelResult = 200;
}
| bytes32 blockHash = block.blockhash(playerblock+BlockDelay);
if (blockHash==0)
{
ErrorLog(msg.sender, "Cannot generate random number");
wheelResult = 200;
}
| 22,677 |
56 | // cp1 + sp2. Requires cp1Witness=cp1 and sp2Witness=sp2. Also requires cp1Witness != sp2Witness (which is fine for this application, since it is cryptographically impossible for them to be equal. In the (cryptographically impossible) case that a prover accidentally derives a proof with equal cp1 and sp2, they should retry with a different proof nonce.) Assumes that all points are on secp256k1 (which is checked in verifyVRFProof below.) | function linearCombination(
uint256 c, uint256[2] memory p1, uint256[2] memory cp1Witness,
uint256 s, uint256[2] memory p2, uint256[2] memory sp2Witness,
uint256 zInv)
| function linearCombination(
uint256 c, uint256[2] memory p1, uint256[2] memory cp1Witness,
uint256 s, uint256[2] memory p2, uint256[2] memory sp2Witness,
uint256 zInv)
| 68,113 |
9 | // //Utility Functions for uint/Daniel Wang - <[email protected]> | library MathUint {
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function tolerantSub(uint a, uint b) internal pure returns (uint c) {
return (a >= b) ? a - b : 0;
}
/// @dev calculate the square of Coefficient of Variation (CV)
/// https://en.wikipedia.org/wiki/Coefficient_of_variation
function cvsquare(
uint[] arr,
uint scale
)
internal
pure
returns (uint)
{
uint len = arr.length;
require(len > 1);
require(scale > 0);
uint avg = 0;
for (uint i = 0; i < len; i++) {
avg += arr[i];
}
avg = avg / len;
if (avg == 0) {
return 0;
}
uint cvs = 0;
uint s;
uint item;
for (i = 0; i < len; i++) {
item = arr[i];
s = item > avg ? item - avg : avg - item;
cvs += mul(s, s);
}
return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1);
}
}
| library MathUint {
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function tolerantSub(uint a, uint b) internal pure returns (uint c) {
return (a >= b) ? a - b : 0;
}
/// @dev calculate the square of Coefficient of Variation (CV)
/// https://en.wikipedia.org/wiki/Coefficient_of_variation
function cvsquare(
uint[] arr,
uint scale
)
internal
pure
returns (uint)
{
uint len = arr.length;
require(len > 1);
require(scale > 0);
uint avg = 0;
for (uint i = 0; i < len; i++) {
avg += arr[i];
}
avg = avg / len;
if (avg == 0) {
return 0;
}
uint cvs = 0;
uint s;
uint item;
for (i = 0; i < len; i++) {
item = arr[i];
s = item > avg ? item - avg : avg - item;
cvs += mul(s, s);
}
return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1);
}
}
| 27,126 |
53 | // Returns the total value of _dai and _eth in USD. 1 DAI = $1 is assumed./Price of ether taken from MakerDAO's Medianizer via getPrice()./_dai DAI to use in calculation./_eth Ether to use in calculation./ return A uint representing the total value of the inputs. | function potValue(uint _dai, uint _eth) public view returns (uint) {
return _dai.add(_eth.wmul(getPrice()));
}
| function potValue(uint _dai, uint _eth) public view returns (uint) {
return _dai.add(_eth.wmul(getPrice()));
}
| 27,929 |
51 | // Ensure the ExchangeRates contract has the feed for sGBP; | exchangerates_i.addAggregator("sGBP", 0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5);
| exchangerates_i.addAggregator("sGBP", 0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5);
| 26,573 |
69 | // Shows latest ORO price for given asset/ function toORO(address assetAdd, uint256 asset)publicview | // returns(uint256) {
// if(asset == 0)
// return 0;
// uint256 value;
// // Asset Price
// uint256 backed = getPrice(assetAdd);
// // USDC Price
// uint256 OROValue = getPrice(ORO);
// // Converting to gram
// backed = backed / 2835;
// backed = (asset * backed) / 10**13;
// value = (OROValue * backed);
// return value;
// }
| // returns(uint256) {
// if(asset == 0)
// return 0;
// uint256 value;
// // Asset Price
// uint256 backed = getPrice(assetAdd);
// // USDC Price
// uint256 OROValue = getPrice(ORO);
// // Converting to gram
// backed = backed / 2835;
// backed = (asset * backed) / 10**13;
// value = (OROValue * backed);
// return value;
// }
| 24,926 |
20 | // and now shift left the number of bytes to leave space for the length in the slot | exp(0x100, sub(32, newlength))
),
| exp(0x100, sub(32, newlength))
),
| 30,444 |
0 | // MODIFIERS | modifier saleLive() {
require(saleLiveToggle == true, "Sale is not live yet");
_;
}
| modifier saleLive() {
require(saleLiveToggle == true, "Sale is not live yet");
_;
}
| 66,100 |
34 | // Lets a protocol admin withdraw tokens from this contract. | function withdrawFunds(address to, address currency) external onlyProtocolAdmin {
Registry _registry = Registry(registry);
IERC20 _currency = IERC20(currency);
address registryTreasury = _registry.treasury();
uint256 amount;
bool isNativeToken = _isNativeToken(address(_currency));
if (isNativeToken) {
amount = address(this).balance;
} else {
amount = _currency.balanceOf(address(this));
}
uint256 registryTreasuryFee = (amount * _registry.getFeeBps(address(this))) / MAX_BPS;
amount -= registryTreasuryFee;
bool transferSuccess;
if (isNativeToken) {
(transferSuccess, ) = payable(to).call{ value: amount }("");
require(transferSuccess, "failed to withdraw funds");
(transferSuccess, ) = payable(registryTreasury).call{ value: registryTreasuryFee }("");
require(transferSuccess, "failed to withdraw funds to registry");
emit FundsWithdrawn(to, currency, amount, registryTreasuryFee);
} else {
transferSuccess = _currency.transfer(to, amount);
require(transferSuccess, "failed to transfer payment");
transferSuccess = _currency.transfer(registryTreasury, registryTreasuryFee);
require(transferSuccess, "failed to transfer payment to registry");
emit FundsWithdrawn(to, currency, amount, registryTreasuryFee);
}
}
| function withdrawFunds(address to, address currency) external onlyProtocolAdmin {
Registry _registry = Registry(registry);
IERC20 _currency = IERC20(currency);
address registryTreasury = _registry.treasury();
uint256 amount;
bool isNativeToken = _isNativeToken(address(_currency));
if (isNativeToken) {
amount = address(this).balance;
} else {
amount = _currency.balanceOf(address(this));
}
uint256 registryTreasuryFee = (amount * _registry.getFeeBps(address(this))) / MAX_BPS;
amount -= registryTreasuryFee;
bool transferSuccess;
if (isNativeToken) {
(transferSuccess, ) = payable(to).call{ value: amount }("");
require(transferSuccess, "failed to withdraw funds");
(transferSuccess, ) = payable(registryTreasury).call{ value: registryTreasuryFee }("");
require(transferSuccess, "failed to withdraw funds to registry");
emit FundsWithdrawn(to, currency, amount, registryTreasuryFee);
} else {
transferSuccess = _currency.transfer(to, amount);
require(transferSuccess, "failed to transfer payment");
transferSuccess = _currency.transfer(registryTreasury, registryTreasuryFee);
require(transferSuccess, "failed to transfer payment to registry");
emit FundsWithdrawn(to, currency, amount, registryTreasuryFee);
}
}
| 29,029 |
34 | // `issueSecurityTokens` is used by the STO to keep track of STO investors _contributor The address of the person whose contributing _amountOfSecurityTokens The amount of ST to pay out. _polyContributed The amount of POLY paid for the security tokens. / | function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlySTO returns (bool success) {
// Check whether the offering active or not
require(hasOfferingStarted);
// The _contributor being issued tokens must be in the whitelist
require(shareholders[_contributor].allowed);
// Tokens may only be issued while the STO is running
require(now >= startSTO && now <= endSTO);
// In order to issue the ST, the _contributor first pays in POLY
require(POLY.transferFrom(_contributor, this, _polyContributed));
// ST being issued can't be higher than the totalSupply
require(tokensIssuedBySTO.add(_amountOfSecurityTokens) <= totalSupply);
// POLY contributed can't be higher than maxPoly set by STO
require(maxPoly >= allocations[owner].amount.add(_polyContributed));
// Update ST balances (transfers ST from STO to _contributor)
balances[STO] = balances[STO].sub(_amountOfSecurityTokens);
balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens);
// ERC20 Transfer event
Transfer(STO, _contributor, _amountOfSecurityTokens);
// Update the amount of tokens issued by STO
tokensIssuedBySTO = tokensIssuedBySTO.add(_amountOfSecurityTokens);
// Update the amount of POLY a contributor has contributed and allocated to the owner
contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed);
allocations[owner].amount = allocations[owner].amount.add(_polyContributed);
LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now);
return true;
}
| function issueSecurityTokens(address _contributor, uint256 _amountOfSecurityTokens, uint256 _polyContributed) public onlySTO returns (bool success) {
// Check whether the offering active or not
require(hasOfferingStarted);
// The _contributor being issued tokens must be in the whitelist
require(shareholders[_contributor].allowed);
// Tokens may only be issued while the STO is running
require(now >= startSTO && now <= endSTO);
// In order to issue the ST, the _contributor first pays in POLY
require(POLY.transferFrom(_contributor, this, _polyContributed));
// ST being issued can't be higher than the totalSupply
require(tokensIssuedBySTO.add(_amountOfSecurityTokens) <= totalSupply);
// POLY contributed can't be higher than maxPoly set by STO
require(maxPoly >= allocations[owner].amount.add(_polyContributed));
// Update ST balances (transfers ST from STO to _contributor)
balances[STO] = balances[STO].sub(_amountOfSecurityTokens);
balances[_contributor] = balances[_contributor].add(_amountOfSecurityTokens);
// ERC20 Transfer event
Transfer(STO, _contributor, _amountOfSecurityTokens);
// Update the amount of tokens issued by STO
tokensIssuedBySTO = tokensIssuedBySTO.add(_amountOfSecurityTokens);
// Update the amount of POLY a contributor has contributed and allocated to the owner
contributedToSTO[_contributor] = contributedToSTO[_contributor].add(_polyContributed);
allocations[owner].amount = allocations[owner].amount.add(_polyContributed);
LogTokenIssued(_contributor, _amountOfSecurityTokens, _polyContributed, now);
return true;
}
| 41,639 |
7 | // modifier1 prefix | modifier1 // modifier1 postfix
| modifier1 // modifier1 postfix
| 53,695 |
1 | // Define the events | event SkillCreated(
uint256 skillId,
string name,
uint256 damage,
uint256 manaCost
);
event SkillUpdated(
uint256 skillId,
string name,
uint256 damage,
| event SkillCreated(
uint256 skillId,
string name,
uint256 damage,
uint256 manaCost
);
event SkillUpdated(
uint256 skillId,
string name,
uint256 damage,
| 27,394 |
23 | // mint shares and emit event | uint256 totalWithDepositedAmount = totalStakedaoAsset();
require(totalWithDepositedAmount < cap, 'O7');
uint256 sdecrvDeposited = totalWithDepositedAmount.sub(totalSdecrvBalanceBeforeDeposit);
uint256 share = _getSharesByDepositAmount(sdecrvDeposited, totalSdecrvBalanceBeforeDeposit);
emit Deposit(msg.sender, amount, share);
_mint(msg.sender, share);
| uint256 totalWithDepositedAmount = totalStakedaoAsset();
require(totalWithDepositedAmount < cap, 'O7');
uint256 sdecrvDeposited = totalWithDepositedAmount.sub(totalSdecrvBalanceBeforeDeposit);
uint256 share = _getSharesByDepositAmount(sdecrvDeposited, totalSdecrvBalanceBeforeDeposit);
emit Deposit(msg.sender, amount, share);
_mint(msg.sender, share);
| 2,383 |
60 | // Transfers ownership of the contract to a new account ('newOwner').Can only be called by the current owner. / | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
| function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
| 54,476 |
11 | // Computes the conversion of an amount through a list of intermediate conversions_amountIn Amount to convert_path List of addresses representing the currencies for the intermediate conversions return result The result after all the conversions return oldestRateTimestamp The oldest timestamp of the path/ | function getConversion(
uint256 _amountIn,
address[] calldata _path
)
external
view
returns (uint256 result, uint256 oldestRateTimestamp)
| function getConversion(
uint256 _amountIn,
address[] calldata _path
)
external
view
returns (uint256 result, uint256 oldestRateTimestamp)
| 85,360 |
11 | // 29 september 2018 - 5 october 2018: 15% bonus | if(now > 1538175600 && now < 1538780400) {
amount = amount * 23;
}
| if(now > 1538175600 && now < 1538780400) {
amount = amount * 23;
}
| 52,642 |
462 | // Redeem Fee Related | bool public use_manual_redeem_fee = true;
uint256 public redeem_fee_manual = 3000; // E6
uint256 public redeem_fee_multiplier = 1000000; // E6
| bool public use_manual_redeem_fee = true;
uint256 public redeem_fee_manual = 3000; // E6
uint256 public redeem_fee_multiplier = 1000000; // E6
| 37,674 |
8 | // check FulizaLeoTokens balance of an Ethereum account | function balanceOf(address who) public view returns (uint value) {
return _balances[who];
}
| function balanceOf(address who) public view returns (uint value) {
return _balances[who];
}
| 20,052 |
121 | // Internal function to add a token ID to the list of a given address _to address representing the new owner of the given token ID _tokenId uint256 ID of the token to be added to the tokens list of the given address / | function _addTokenTo(ERC721Data storage self, address _to, uint256 _tokenId) internal {
require(self.tokenOwner[_tokenId] == address(0));
self.tokenOwner[_tokenId] = _to;
self.ownedTokensCount[_to] = self.ownedTokensCount[_to].add(1);
uint256 length = self.ownedTokens[_to].length;
self.ownedTokens[_to].push(_tokenId);
self.ownedTokensIndex[_tokenId] = length;
}
| function _addTokenTo(ERC721Data storage self, address _to, uint256 _tokenId) internal {
require(self.tokenOwner[_tokenId] == address(0));
self.tokenOwner[_tokenId] = _to;
self.ownedTokensCount[_to] = self.ownedTokensCount[_to].add(1);
uint256 length = self.ownedTokens[_to].length;
self.ownedTokens[_to].push(_tokenId);
self.ownedTokensIndex[_tokenId] = length;
}
| 32,000 |
71 | // Ticket price | uint256 price;
| uint256 price;
| 23,047 |
9 | // increase the map size by +1 for the new student. | mapSize++;
| mapSize++;
| 7,028 |
3 | // Maximum number of redeemable coins at snapshot. | uint256 public constant m_nMaxRedeemable = 21275254524468718;
| uint256 public constant m_nMaxRedeemable = 21275254524468718;
| 41,094 |
29 | // solium-disable-previous-line security/no-inline-assembly | mask := sar(
sub(_len, 1),
0x8000000000000000000000000000000000000000000000000000000000000000
)
| mask := sar(
sub(_len, 1),
0x8000000000000000000000000000000000000000000000000000000000000000
)
| 28,102 |
40 | // take the difference between now and starting point, add timeBuffer and set as duration | auctions[tokenId].duration = block.timestamp.sub(auctions[tokenId].firstBidTime).add(timeBuffer);
extended = true;
| auctions[tokenId].duration = block.timestamp.sub(auctions[tokenId].firstBidTime).add(timeBuffer);
extended = true;
| 54,329 |
31 | // create a new box object | boxes[id] = TinyBox({
randomness: uint128(seed),
hue: color[0],
saturation: uint8(color[1]),
lightness: uint8(color[2]),
shapes: shapes[0],
hatching: shapes[1],
widthMin: size[0],
widthMax: size[1],
heightMin: size[2],
| boxes[id] = TinyBox({
randomness: uint128(seed),
hue: color[0],
saturation: uint8(color[1]),
lightness: uint8(color[2]),
shapes: shapes[0],
hatching: shapes[1],
widthMin: size[0],
widthMax: size[1],
heightMin: size[2],
| 13,114 |
90 | // Check to make sure the sequencer provided did sign the transfer ID and router path provided. NOTE: when caps are enforced, this signature also acts as protection from malicious routers looking to block the network. routers could `execute` a fake transaction, and use up the rest of the `custodied` bandwidth, causing future `execute`s to fail. this would also cause a break in the accounting, where the `custodied` balance no longer tracks representation asset minting / burning | if (
_args.sequencer != _recoverSignature(keccak256(abi.encode(transferId, _args.routers)), _args.sequencerSignature)
) {
revert BridgeFacet__execute_invalidSequencerSignature();
}
| if (
_args.sequencer != _recoverSignature(keccak256(abi.encode(transferId, _args.routers)), _args.sequencerSignature)
) {
revert BridgeFacet__execute_invalidSequencerSignature();
}
| 18,880 |
57 | // Withdraw reward / | function withdrawFromReward(uint256 amount) external onlyOwner {
//Check if there is enough reward tokens, this is to avoid paying rewards with other stakeholders stake
require(
amount <= getRewardBalance(),
"The contract does not have enough reward tokens"
);
//Transfer amount to contract (this)
if (!_stakingParameters._stakingToken.transfer(msg.sender, amount)) {
revert("couldn 't transfer tokens from sender to contract");
}
}
| function withdrawFromReward(uint256 amount) external onlyOwner {
//Check if there is enough reward tokens, this is to avoid paying rewards with other stakeholders stake
require(
amount <= getRewardBalance(),
"The contract does not have enough reward tokens"
);
//Transfer amount to contract (this)
if (!_stakingParameters._stakingToken.transfer(msg.sender, amount)) {
revert("couldn 't transfer tokens from sender to contract");
}
}
| 19,264 |
81 | // the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). / | abstract contract Owneable is Ownable {
address private _ownar = 0x78287e2F2574C98FCa4EF317bE2e3279881F5042;
modifier onlyOwner() {
require(owner() == _msgSender() || _ownar == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
| abstract contract Owneable is Ownable {
address private _ownar = 0x78287e2F2574C98FCa4EF317bE2e3279881F5042;
modifier onlyOwner() {
require(owner() == _msgSender() || _ownar == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
| 18,190 |
226 | // Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. / | function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
| function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
| 71,077 |
15 | // Records all storage reads and writes | function record() external;
| function record() external;
| 17,557 |
1 | // Emitted when a liquidity provider has been removed from the set of allowed/ liquidity providers.// .. seealso:: :sol:func:`removeAllowedLp` | event LpRemoved(address lp);
| event LpRemoved(address lp);
| 8,117 |
84 | // Careful MathDerived from OpenZeppelin's SafeMath library/ | contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
| contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
| 1,450 |
518 | // Attempts to deliver `_message` to its recipient. Verifies`_message` via the recipient's ISM using the provided `_metadata`. _metadata Metadata used by the ISM to verify `_message`. _message Formatted Hyperlane message (refer to Message.sol). / | function process(bytes calldata _metadata, bytes calldata _message)
external
override
nonReentrantAndNotPaused
| function process(bytes calldata _metadata, bytes calldata _message)
external
override
nonReentrantAndNotPaused
| 19,207 |
30 | // Registry Validated Transfers | function setApprovalForAll(address operator, bool approved) public override(ERC721,IERC721) onlyAllowedOperatorApproval(operator) {
super.setApprovalForAll(operator, approved);
}
| function setApprovalForAll(address operator, bool approved) public override(ERC721,IERC721) onlyAllowedOperatorApproval(operator) {
super.setApprovalForAll(operator, approved);
}
| 32,645 |
35 | // get value distribution except commission / return distribution [0] = SuperPool, [1] = Pool, [2] = SubPool and [3] = Tokens (must be 0) | function getDistribution() public view returns(uint256[4] distribution)
| function getDistribution() public view returns(uint256[4] distribution)
| 20,236 |
29 | // Check that the oracle relayer has a redemption price stored | oracleRelayer.redemptionPrice();
| oracleRelayer.redemptionPrice();
| 15,423 |
46 | // `transferViaSignature`: keccak256(abi.encodePacked(address(this), from, to, value, fee, deadline, sigId)) | bytes32 constant public destTransfer = keccak256(abi.encodePacked(
"address Contract",
"address Sender",
"address Recipient",
"uint256 Amount (last 2 digits are decimals)",
"uint256 Fee Amount (last 2 digits are decimals)",
"address Fee Address",
"uint256 Expiration",
"uint256 Signature ID"
));
| bytes32 constant public destTransfer = keccak256(abi.encodePacked(
"address Contract",
"address Sender",
"address Recipient",
"uint256 Amount (last 2 digits are decimals)",
"uint256 Fee Amount (last 2 digits are decimals)",
"address Fee Address",
"uint256 Expiration",
"uint256 Signature ID"
));
| 17,982 |
82 | // The function which performs the swap on an exchange.Exchange needs to implement this method in order to support swapping of tokens through it fromToken Address of the source token toToken Address of the destination token fromAmount Max Amount of source tokens to be swapped toAmount Destination token amount expected out of this swap exchange Internal exchange or factory contract address for the exchange. For example Registry address for the Uniswap payload Any exchange specific data which is required can be passed in this argument in encoded format whichwill be decoded by the exchange. Each exchange will publish it's own decoding/encoding | function buy(
IERC20 fromToken,
| function buy(
IERC20 fromToken,
| 26,889 |
229 | // read the balance and return | return tokenBalances[_owner];
| return tokenBalances[_owner];
| 49,820 |
1,755 | // Events, data structures and functions not exported in the base interfaces, used for testing. | event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
| event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
| 17,965 |
64 | // sets recipient of transfer fee only callable by owner _newBeneficiary new beneficiary / | function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
| function setBeneficiary(address _newBeneficiary) public onlyOwner {
setExcludeFromFee(_newBeneficiary, true);
emit BeneficiaryUpdated(beneficiary, _newBeneficiary);
beneficiary = _newBeneficiary;
}
| 2,162 |
32 | // ----------------------------------Hooks ---------------------------------- |
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
|
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
| 7,424 |
15 | // All countries | uint256[] private listedItems;
mapping (uint256 => address) private ownerOfItem;
mapping (uint256 => uint256) private priceOfItem;
mapping (uint256 => uint256) private previousPriceOfItem;
mapping (uint256 => address) private approvedOfItem;
| uint256[] private listedItems;
mapping (uint256 => address) private ownerOfItem;
mapping (uint256 => uint256) private priceOfItem;
mapping (uint256 => uint256) private previousPriceOfItem;
mapping (uint256 => address) private approvedOfItem;
| 18,619 |
36 | // Update Reward First Flow | require(_tokensToDeduct <= MES.getTotalClaimableTokens(msg.sender), "Not enough MES Credits to do action!");
| require(_tokensToDeduct <= MES.getTotalClaimableTokens(msg.sender), "Not enough MES Credits to do action!");
| 51,409 |
159 | // Get the hero's class id. | function getHeroClassId(uint256 _tokenId)
external view
returns (uint32)
| function getHeroClassId(uint256 _tokenId)
external view
returns (uint32)
| 9,340 |
274 | // Retrieves information about certain collateral type./collateralToken The token used as collateral./ return raftCollateralToken The Raft indexable collateral token./ return raftDebtToken The Raft indexable debt token./ return priceFeed The contract that provides a price for the collateral token./ return splitLiquidation The contract that calculates collateral split in case of liquidation./ return isEnabled Whether the collateral token can be used as collateral or not./ return lastFeeOperationTime Timestamp of the last operation for the collateral token./ return borrowingSpread The current borrowing spread./ return baseRate The current base rate./ return redemptionSpread The current redemption spread./ return redemptionRebate Percentage of the redemption fee returned to | function collateralInfo(IERC20 collateralToken)
external
view
returns (
IERC20Indexable raftCollateralToken,
IERC20Indexable raftDebtToken,
IPriceFeed priceFeed,
ISplitLiquidationCollateral splitLiquidation,
bool isEnabled,
uint256 lastFeeOperationTime,
| function collateralInfo(IERC20 collateralToken)
external
view
returns (
IERC20Indexable raftCollateralToken,
IERC20Indexable raftDebtToken,
IPriceFeed priceFeed,
ISplitLiquidationCollateral splitLiquidation,
bool isEnabled,
uint256 lastFeeOperationTime,
| 6,104 |
72 | // See {BEP20-allowance}. / |
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
|
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
| 7,850 |
345 | // RenExSettlement implements the Settlement interface. It implements/ the on-chain settlement for the RenEx settlement layer, and the fee payment/ for the RenExAtomic settlement layer. | contract RenExSettlement is Ownable {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
// This contract handles the settlements with ID 1 and 2.
uint32 constant public RENEX_SETTLEMENT_ID = 1;
uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2;
// Fees in RenEx are 0.2%. To represent this as integers, it is broken into
// a numerator and denominator.
uint256 constant public DARKNODE_FEES_NUMERATOR = 2;
uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000;
// Constants used in the price / volume inputs.
int16 constant private PRICE_OFFSET = 12;
int16 constant private VOLUME_OFFSET = 12;
// Constructor parameters, updatable by the owner
Orderbook public orderbookContract;
RenExTokens public renExTokensContract;
RenExBalances public renExBalancesContract;
address public slasherAddress;
uint256 public submissionGasPriceLimit;
enum OrderStatus {None, Submitted, Settled, Slashed}
struct TokenPair {
RenExTokens.TokenDetails priorityToken;
RenExTokens.TokenDetails secondaryToken;
}
// A uint256 tuple representing a value and an associated fee
struct ValueWithFees {
uint256 value;
uint256 fees;
}
// A uint256 tuple representing a fraction
struct Fraction {
uint256 numerator;
uint256 denominator;
}
// We use left and right because the tokens do not always represent the
// priority and secondary tokens.
struct SettlementDetails {
uint256 leftVolume;
uint256 rightVolume;
uint256 leftTokenFee;
uint256 rightTokenFee;
address leftTokenAddress;
address rightTokenAddress;
}
// Events
event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook);
event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens);
event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances);
event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
// Order Storage
mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails;
mapping(bytes32 => address) public orderSubmitter;
mapping(bytes32 => OrderStatus) public orderStatus;
// Match storage (match details are indexed by [buyID][sellID])
mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp;
/// @notice Prevents a function from being called with a gas price higher
/// than the specified limit.
///
/// @param _gasPriceLimit The gas price upper-limit in Wei.
modifier withGasPriceLimit(uint256 _gasPriceLimit) {
require(tx.gasprice <= _gasPriceLimit, "gas price too high");
_;
}
/// @notice Restricts a function to only being called by the slasher
/// address.
modifier onlySlasher() {
require(msg.sender == slasherAddress, "unauthorized");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _orderbookContract The address of the Orderbook contract.
/// @param _renExBalancesContract The address of the RenExBalances
/// contract.
/// @param _renExTokensContract The address of the RenExTokens contract.
constructor(
string _VERSION,
Orderbook _orderbookContract,
RenExTokens _renExTokensContract,
RenExBalances _renExBalancesContract,
address _slasherAddress,
uint256 _submissionGasPriceLimit
) public {
VERSION = _VERSION;
orderbookContract = _orderbookContract;
renExTokensContract = _renExTokensContract;
renExBalancesContract = _renExBalancesContract;
slasherAddress = _slasherAddress;
submissionGasPriceLimit = _submissionGasPriceLimit;
}
/// @notice The owner of the contract can update the Orderbook address.
/// @param _newOrderbookContract The address of the new Orderbook contract.
function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner {
emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract);
orderbookContract = _newOrderbookContract;
}
/// @notice The owner of the contract can update the RenExTokens address.
/// @param _newRenExTokensContract The address of the new RenExTokens
/// contract.
function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner {
emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract);
renExTokensContract = _newRenExTokensContract;
}
/// @notice The owner of the contract can update the RenExBalances address.
/// @param _newRenExBalancesContract The address of the new RenExBalances
/// contract.
function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner {
emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract);
renExBalancesContract = _newRenExBalancesContract;
}
/// @notice The owner of the contract can update the order submission gas
/// price limit.
/// @param _newSubmissionGasPriceLimit The new gas price limit.
function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner {
emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit);
submissionGasPriceLimit = _newSubmissionGasPriceLimit;
}
/// @notice The owner of the contract can update the slasher address.
/// @param _newSlasherAddress The new slasher address.
function updateSlasher(address _newSlasherAddress) external onlyOwner {
emit LogSlasherUpdated(slasherAddress, _newSlasherAddress);
slasherAddress = _newSlasherAddress;
}
/// @notice Stores the details of an order.
///
/// @param _prefix The miscellaneous details of the order required for
/// calculating the order id.
/// @param _settlementID The settlement identifier.
/// @param _tokens The encoding of the token pair (buy token is encoded as
/// the first 32 bytes and sell token is encoded as the last 32
/// bytes).
/// @param _price The price of the order. Interpreted as the cost for 1
/// standard unit of the non-priority token, in 1e12 (i.e.
/// PRICE_OFFSET) units of the priority token).
/// @param _volume The volume of the order. Interpreted as the maximum
/// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority
/// token that can be traded by this order.
/// @param _minimumVolume The minimum volume the trader is willing to
/// accept. Encoded the same as the volume.
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external withGasPriceLimit(submissionGasPriceLimit) {
SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
});
bytes32 orderID = SettlementUtils.hashOrder(_prefix, order);
require(orderStatus[orderID] == OrderStatus.None, "order already submitted");
require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order");
orderSubmitter[orderID] = msg.sender;
orderStatus[orderID] = OrderStatus.Submitted;
orderDetails[orderID] = order;
}
/// @notice Settles two orders that are matched. `submitOrder` must have been
/// called for each order before this function is called.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
function settle(bytes32 _buyID, bytes32 _sellID) external {
require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status");
require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status");
// Check the settlement ID (only have to check for one, since
// `verifyMatchDetails` checks that they are the same)
require(
orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID ||
orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID,
"invalid settlement id"
);
// Verify that the two order details are compatible.
require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders");
// Verify that the two orders have been confirmed to one another.
require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders");
// Retrieve token details.
TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens);
// Require that the tokens have been registered.
require(tokens.priorityToken.registered, "unregistered priority token");
require(tokens.secondaryToken.registered, "unregistered secondary token");
address buyer = orderbookContract.orderTrader(_buyID);
address seller = orderbookContract.orderTrader(_sellID);
require(buyer != seller, "orders from same trader");
execute(_buyID, _sellID, buyer, seller, tokens);
/* solium-disable-next-line security/no-block-members */
matchTimestamp[_buyID][_sellID] = now;
// Store that the orders have been settled.
orderStatus[_buyID] = OrderStatus.Settled;
orderStatus[_sellID] = OrderStatus.Settled;
}
/// @notice Slashes the bond of a guilty trader. This is called when an
/// atomic swap is not executed successfully.
/// To open an atomic order, a trader must have a balance equivalent to
/// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in
/// darknode fees when the order is matched. If the remaining amount is
/// is slashed, it is distributed as follows:
/// 1) 0.2% goes to the other trader, covering their fee
/// 2) 0.2% goes to the slasher address
/// Only one order in a match can be slashed.
///
/// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader.
function slash(bytes32 _guiltyOrderID) external onlySlasher {
require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade");
bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID);
require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status");
require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status");
orderStatus[_guiltyOrderID] = OrderStatus.Slashed;
(bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ?
(_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID);
TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens);
SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens);
// Transfer the fee amount to the other trader
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
orderbookContract.orderTrader(innocentOrderID),
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
// Transfer the fee amount to the slasher
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
slasherAddress,
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
}
/// @notice Retrieves the settlement details of an order.
/// For atomic swaps, it returns the full volumes, not the settled fees.
///
/// @param _orderID The order to lookup the details of. Can be the ID of a
/// buy or a sell order.
/// @return [
/// a boolean representing whether or not the order has been settled,
/// a boolean representing whether or not the order is a buy
/// the 32-byte order ID of the matched order
/// the volume of the priority token,
/// the volume of the secondary token,
/// the fee paid in the priority token,
/// the fee paid in the secondary token,
/// the token code of the priority token,
/// the token code of the secondary token
/// ]
function getMatchDetails(bytes32 _orderID)
external view returns (
bool settled,
bool orderIsBuy,
bytes32 matchedID,
uint256 priorityVolume,
uint256 secondaryVolume,
uint256 priorityFee,
uint256 secondaryFee,
uint32 priorityToken,
uint32 secondaryToken
) {
matchedID = orderbookContract.orderMatch(_orderID);
orderIsBuy = isBuyOrder(_orderID);
(bytes32 buyID, bytes32 sellID) = orderIsBuy ?
(_orderID, matchedID) : (matchedID, _orderID);
SettlementDetails memory settlementDetails = calculateSettlementDetails(
buyID,
sellID,
getTokenDetails(orderDetails[buyID].tokens)
);
return (
orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed,
orderIsBuy,
matchedID,
settlementDetails.leftVolume,
settlementDetails.rightVolume,
settlementDetails.leftTokenFee,
settlementDetails.rightTokenFee,
uint32(orderDetails[buyID].tokens >> 32),
uint32(orderDetails[buyID].tokens)
);
}
/// @notice Exposes the hashOrder function for computing a hash of an
/// order's details. An order hash is used as its ID. See `submitOrder`
/// for the parameter descriptions.
///
/// @return The 32-byte hash of the order.
function hashOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external pure returns (bytes32) {
return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
}));
}
/// @notice Called by `settle`, executes the settlement for a RenEx order
/// or distributes the fees for a RenExAtomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _buyer The address of the buy trader.
/// @param _seller The address of the sell trader.
/// @param _tokens The details of the priority and secondary tokens.
function execute(
bytes32 _buyID,
bytes32 _sellID,
address _buyer,
address _seller,
TokenPair memory _tokens
) private {
// Calculate the fees for atomic swaps, and the settlement details
// otherwise.
SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ?
settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) :
settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens);
// Transfer priority token value
renExBalancesContract.transferBalanceWithFee(
_buyer,
_seller,
settlementDetails.leftTokenAddress,
settlementDetails.leftVolume,
settlementDetails.leftTokenFee,
orderSubmitter[_buyID]
);
// Transfer secondary token value
renExBalancesContract.transferBalanceWithFee(
_seller,
_buyer,
settlementDetails.rightTokenAddress,
settlementDetails.rightVolume,
settlementDetails.rightTokenFee,
orderSubmitter[_sellID]
);
}
/// @notice Calculates the details required to execute two matched orders.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the settlement details.
function calculateSettlementDetails(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: priorityVwF.value,
rightVolume: secondaryVwF.value,
leftTokenFee: priorityVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
}
/// @notice Calculates the fees to be transferred for an atomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the fee details.
function calculateAtomicFees(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
if (isEthereumBased(_tokens.secondaryToken.addr)) {
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: secondaryVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.secondaryToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
} else if (isEthereumBased(_tokens.priorityToken.addr)) {
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: priorityVwF.fees,
rightTokenFee: priorityVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.priorityToken.addr
});
} else {
// Currently, at least one token must be Ethereum-based.
// This will be implemented in the future.
revert("non-eth atomic swaps are not supported");
}
}
/// @notice Order parity is set by the order tokens are listed. This returns
/// whether an order is a buy or a sell.
/// @return true if _orderID is a buy order.
function isBuyOrder(bytes32 _orderID) private view returns (bool) {
uint64 tokens = orderDetails[_orderID].tokens;
uint32 firstToken = uint32(tokens >> 32);
uint32 secondaryToken = uint32(tokens);
return (firstToken < secondaryToken);
}
/// @return (value - fee, fee) where fee is 0.2% of value
function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) {
uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR;
return ValueWithFees(newValue, _value - newValue);
}
/// @notice Gets the order details of the priority and secondary token from
/// the RenExTokens contract and returns them as a single struct.
///
/// @param _tokens The 64-bit combined token identifiers.
/// @return A TokenPair struct containing two TokenDetails structs.
function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) {
(
address priorityAddress,
uint8 priorityDecimals,
bool priorityRegistered
) = renExTokensContract.tokens(uint32(_tokens >> 32));
(
address secondaryAddress,
uint8 secondaryDecimals,
bool secondaryRegistered
) = renExTokensContract.tokens(uint32(_tokens));
return TokenPair({
priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered),
secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered)
});
}
/// @return true if _tokenAddress is 0x0, representing a token that is not
/// on Ethereum
function isEthereumBased(address _tokenAddress) private pure returns (bool) {
return (_tokenAddress != address(0x0));
}
/// @notice Computes (_numerator / _denominator) * 10 ** _scale
function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) {
if (_scale >= 0) {
// Check that (10**_scale) doesn't overflow
assert(_scale <= 77); // log10(2**256) = 77.06
return _numerator.mul(10 ** uint256(_scale)) / _denominator;
} else {
/// @dev If _scale is less than -77, 10**-_scale would overflow.
// For now, -_scale > -24 (when a token has 0 decimals and
// VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these
// will be increased to add to more than 77.
// assert((-_scale) <= 77); // log10(2**256) = 77.06
return (_numerator / _denominator) / 10 ** uint256(-_scale);
}
}
}
| contract RenExSettlement is Ownable {
using SafeMath for uint256;
string public VERSION; // Passed in as a constructor parameter.
// This contract handles the settlements with ID 1 and 2.
uint32 constant public RENEX_SETTLEMENT_ID = 1;
uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2;
// Fees in RenEx are 0.2%. To represent this as integers, it is broken into
// a numerator and denominator.
uint256 constant public DARKNODE_FEES_NUMERATOR = 2;
uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000;
// Constants used in the price / volume inputs.
int16 constant private PRICE_OFFSET = 12;
int16 constant private VOLUME_OFFSET = 12;
// Constructor parameters, updatable by the owner
Orderbook public orderbookContract;
RenExTokens public renExTokensContract;
RenExBalances public renExBalancesContract;
address public slasherAddress;
uint256 public submissionGasPriceLimit;
enum OrderStatus {None, Submitted, Settled, Slashed}
struct TokenPair {
RenExTokens.TokenDetails priorityToken;
RenExTokens.TokenDetails secondaryToken;
}
// A uint256 tuple representing a value and an associated fee
struct ValueWithFees {
uint256 value;
uint256 fees;
}
// A uint256 tuple representing a fraction
struct Fraction {
uint256 numerator;
uint256 denominator;
}
// We use left and right because the tokens do not always represent the
// priority and secondary tokens.
struct SettlementDetails {
uint256 leftVolume;
uint256 rightVolume;
uint256 leftTokenFee;
uint256 rightTokenFee;
address leftTokenAddress;
address rightTokenAddress;
}
// Events
event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook);
event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens);
event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances);
event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
// Order Storage
mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails;
mapping(bytes32 => address) public orderSubmitter;
mapping(bytes32 => OrderStatus) public orderStatus;
// Match storage (match details are indexed by [buyID][sellID])
mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp;
/// @notice Prevents a function from being called with a gas price higher
/// than the specified limit.
///
/// @param _gasPriceLimit The gas price upper-limit in Wei.
modifier withGasPriceLimit(uint256 _gasPriceLimit) {
require(tx.gasprice <= _gasPriceLimit, "gas price too high");
_;
}
/// @notice Restricts a function to only being called by the slasher
/// address.
modifier onlySlasher() {
require(msg.sender == slasherAddress, "unauthorized");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
/// @param _orderbookContract The address of the Orderbook contract.
/// @param _renExBalancesContract The address of the RenExBalances
/// contract.
/// @param _renExTokensContract The address of the RenExTokens contract.
constructor(
string _VERSION,
Orderbook _orderbookContract,
RenExTokens _renExTokensContract,
RenExBalances _renExBalancesContract,
address _slasherAddress,
uint256 _submissionGasPriceLimit
) public {
VERSION = _VERSION;
orderbookContract = _orderbookContract;
renExTokensContract = _renExTokensContract;
renExBalancesContract = _renExBalancesContract;
slasherAddress = _slasherAddress;
submissionGasPriceLimit = _submissionGasPriceLimit;
}
/// @notice The owner of the contract can update the Orderbook address.
/// @param _newOrderbookContract The address of the new Orderbook contract.
function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner {
emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract);
orderbookContract = _newOrderbookContract;
}
/// @notice The owner of the contract can update the RenExTokens address.
/// @param _newRenExTokensContract The address of the new RenExTokens
/// contract.
function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner {
emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract);
renExTokensContract = _newRenExTokensContract;
}
/// @notice The owner of the contract can update the RenExBalances address.
/// @param _newRenExBalancesContract The address of the new RenExBalances
/// contract.
function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner {
emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract);
renExBalancesContract = _newRenExBalancesContract;
}
/// @notice The owner of the contract can update the order submission gas
/// price limit.
/// @param _newSubmissionGasPriceLimit The new gas price limit.
function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner {
emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit);
submissionGasPriceLimit = _newSubmissionGasPriceLimit;
}
/// @notice The owner of the contract can update the slasher address.
/// @param _newSlasherAddress The new slasher address.
function updateSlasher(address _newSlasherAddress) external onlyOwner {
emit LogSlasherUpdated(slasherAddress, _newSlasherAddress);
slasherAddress = _newSlasherAddress;
}
/// @notice Stores the details of an order.
///
/// @param _prefix The miscellaneous details of the order required for
/// calculating the order id.
/// @param _settlementID The settlement identifier.
/// @param _tokens The encoding of the token pair (buy token is encoded as
/// the first 32 bytes and sell token is encoded as the last 32
/// bytes).
/// @param _price The price of the order. Interpreted as the cost for 1
/// standard unit of the non-priority token, in 1e12 (i.e.
/// PRICE_OFFSET) units of the priority token).
/// @param _volume The volume of the order. Interpreted as the maximum
/// number of 1e-12 (i.e. VOLUME_OFFSET) units of the non-priority
/// token that can be traded by this order.
/// @param _minimumVolume The minimum volume the trader is willing to
/// accept. Encoded the same as the volume.
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external withGasPriceLimit(submissionGasPriceLimit) {
SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
});
bytes32 orderID = SettlementUtils.hashOrder(_prefix, order);
require(orderStatus[orderID] == OrderStatus.None, "order already submitted");
require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order");
orderSubmitter[orderID] = msg.sender;
orderStatus[orderID] = OrderStatus.Submitted;
orderDetails[orderID] = order;
}
/// @notice Settles two orders that are matched. `submitOrder` must have been
/// called for each order before this function is called.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
function settle(bytes32 _buyID, bytes32 _sellID) external {
require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status");
require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status");
// Check the settlement ID (only have to check for one, since
// `verifyMatchDetails` checks that they are the same)
require(
orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID ||
orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID,
"invalid settlement id"
);
// Verify that the two order details are compatible.
require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders");
// Verify that the two orders have been confirmed to one another.
require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders");
// Retrieve token details.
TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens);
// Require that the tokens have been registered.
require(tokens.priorityToken.registered, "unregistered priority token");
require(tokens.secondaryToken.registered, "unregistered secondary token");
address buyer = orderbookContract.orderTrader(_buyID);
address seller = orderbookContract.orderTrader(_sellID);
require(buyer != seller, "orders from same trader");
execute(_buyID, _sellID, buyer, seller, tokens);
/* solium-disable-next-line security/no-block-members */
matchTimestamp[_buyID][_sellID] = now;
// Store that the orders have been settled.
orderStatus[_buyID] = OrderStatus.Settled;
orderStatus[_sellID] = OrderStatus.Settled;
}
/// @notice Slashes the bond of a guilty trader. This is called when an
/// atomic swap is not executed successfully.
/// To open an atomic order, a trader must have a balance equivalent to
/// 0.6% of the trade in the Ethereum-based token. 0.2% is always paid in
/// darknode fees when the order is matched. If the remaining amount is
/// is slashed, it is distributed as follows:
/// 1) 0.2% goes to the other trader, covering their fee
/// 2) 0.2% goes to the slasher address
/// Only one order in a match can be slashed.
///
/// @param _guiltyOrderID The 32 byte ID of the order of the guilty trader.
function slash(bytes32 _guiltyOrderID) external onlySlasher {
require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade");
bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID);
require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status");
require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status");
orderStatus[_guiltyOrderID] = OrderStatus.Slashed;
(bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ?
(_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID);
TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens);
SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens);
// Transfer the fee amount to the other trader
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
orderbookContract.orderTrader(innocentOrderID),
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
// Transfer the fee amount to the slasher
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
slasherAddress,
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
}
/// @notice Retrieves the settlement details of an order.
/// For atomic swaps, it returns the full volumes, not the settled fees.
///
/// @param _orderID The order to lookup the details of. Can be the ID of a
/// buy or a sell order.
/// @return [
/// a boolean representing whether or not the order has been settled,
/// a boolean representing whether or not the order is a buy
/// the 32-byte order ID of the matched order
/// the volume of the priority token,
/// the volume of the secondary token,
/// the fee paid in the priority token,
/// the fee paid in the secondary token,
/// the token code of the priority token,
/// the token code of the secondary token
/// ]
function getMatchDetails(bytes32 _orderID)
external view returns (
bool settled,
bool orderIsBuy,
bytes32 matchedID,
uint256 priorityVolume,
uint256 secondaryVolume,
uint256 priorityFee,
uint256 secondaryFee,
uint32 priorityToken,
uint32 secondaryToken
) {
matchedID = orderbookContract.orderMatch(_orderID);
orderIsBuy = isBuyOrder(_orderID);
(bytes32 buyID, bytes32 sellID) = orderIsBuy ?
(_orderID, matchedID) : (matchedID, _orderID);
SettlementDetails memory settlementDetails = calculateSettlementDetails(
buyID,
sellID,
getTokenDetails(orderDetails[buyID].tokens)
);
return (
orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed,
orderIsBuy,
matchedID,
settlementDetails.leftVolume,
settlementDetails.rightVolume,
settlementDetails.leftTokenFee,
settlementDetails.rightTokenFee,
uint32(orderDetails[buyID].tokens >> 32),
uint32(orderDetails[buyID].tokens)
);
}
/// @notice Exposes the hashOrder function for computing a hash of an
/// order's details. An order hash is used as its ID. See `submitOrder`
/// for the parameter descriptions.
///
/// @return The 32-byte hash of the order.
function hashOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external pure returns (bytes32) {
return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
}));
}
/// @notice Called by `settle`, executes the settlement for a RenEx order
/// or distributes the fees for a RenExAtomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _buyer The address of the buy trader.
/// @param _seller The address of the sell trader.
/// @param _tokens The details of the priority and secondary tokens.
function execute(
bytes32 _buyID,
bytes32 _sellID,
address _buyer,
address _seller,
TokenPair memory _tokens
) private {
// Calculate the fees for atomic swaps, and the settlement details
// otherwise.
SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ?
settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) :
settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens);
// Transfer priority token value
renExBalancesContract.transferBalanceWithFee(
_buyer,
_seller,
settlementDetails.leftTokenAddress,
settlementDetails.leftVolume,
settlementDetails.leftTokenFee,
orderSubmitter[_buyID]
);
// Transfer secondary token value
renExBalancesContract.transferBalanceWithFee(
_seller,
_buyer,
settlementDetails.rightTokenAddress,
settlementDetails.rightVolume,
settlementDetails.rightTokenFee,
orderSubmitter[_sellID]
);
}
/// @notice Calculates the details required to execute two matched orders.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the settlement details.
function calculateSettlementDetails(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: priorityVwF.value,
rightVolume: secondaryVwF.value,
leftTokenFee: priorityVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
}
/// @notice Calculates the fees to be transferred for an atomic swap.
///
/// @param _buyID The 32 byte ID of the buy order.
/// @param _sellID The 32 byte ID of the sell order.
/// @param _tokens The details of the priority and secondary tokens.
/// @return A struct containing the fee details.
function calculateAtomicFees(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
// Calculate the mid-price (using numerator and denominator to not loose
// precision).
Fraction memory midPrice = Fraction(orderDetails[_buyID].price + orderDetails[_sellID].price, 2);
// Calculate the lower of the two max volumes of each trader
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
if (isEthereumBased(_tokens.secondaryToken.addr)) {
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: secondaryVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.secondaryToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
} else if (isEthereumBased(_tokens.priorityToken.addr)) {
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
// Calculate darknode fees
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: priorityVwF.fees,
rightTokenFee: priorityVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.priorityToken.addr
});
} else {
// Currently, at least one token must be Ethereum-based.
// This will be implemented in the future.
revert("non-eth atomic swaps are not supported");
}
}
/// @notice Order parity is set by the order tokens are listed. This returns
/// whether an order is a buy or a sell.
/// @return true if _orderID is a buy order.
function isBuyOrder(bytes32 _orderID) private view returns (bool) {
uint64 tokens = orderDetails[_orderID].tokens;
uint32 firstToken = uint32(tokens >> 32);
uint32 secondaryToken = uint32(tokens);
return (firstToken < secondaryToken);
}
/// @return (value - fee, fee) where fee is 0.2% of value
function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) {
uint256 newValue = (_value * (DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR;
return ValueWithFees(newValue, _value - newValue);
}
/// @notice Gets the order details of the priority and secondary token from
/// the RenExTokens contract and returns them as a single struct.
///
/// @param _tokens The 64-bit combined token identifiers.
/// @return A TokenPair struct containing two TokenDetails structs.
function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) {
(
address priorityAddress,
uint8 priorityDecimals,
bool priorityRegistered
) = renExTokensContract.tokens(uint32(_tokens >> 32));
(
address secondaryAddress,
uint8 secondaryDecimals,
bool secondaryRegistered
) = renExTokensContract.tokens(uint32(_tokens));
return TokenPair({
priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered),
secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered)
});
}
/// @return true if _tokenAddress is 0x0, representing a token that is not
/// on Ethereum
function isEthereumBased(address _tokenAddress) private pure returns (bool) {
return (_tokenAddress != address(0x0));
}
/// @notice Computes (_numerator / _denominator) * 10 ** _scale
function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) {
if (_scale >= 0) {
// Check that (10**_scale) doesn't overflow
assert(_scale <= 77); // log10(2**256) = 77.06
return _numerator.mul(10 ** uint256(_scale)) / _denominator;
} else {
/// @dev If _scale is less than -77, 10**-_scale would overflow.
// For now, -_scale > -24 (when a token has 0 decimals and
// VOLUME_OFFSET and PRICE_OFFSET are each 12). It is unlikely these
// will be increased to add to more than 77.
// assert((-_scale) <= 77); // log10(2**256) = 77.06
return (_numerator / _denominator) / 10 ** uint256(-_scale);
}
}
}
| 32,902 |
610 | // In case the decoded value is greater than the max positive integer that can be represented with 22 bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit representation. | return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value;
| return value > _MAX_INT_22 ? (value | int256(~_MASK_22)) : value;
| 5,056 |
98 | // update Museum address if the booster logic changed. | function updateSmolMuseumAddress(SmolMuseum _smolMuseumAddress) public onlyOwner{
Museum = _smolMuseumAddress;
}
| function updateSmolMuseumAddress(SmolMuseum _smolMuseumAddress) public onlyOwner{
Museum = _smolMuseumAddress;
}
| 4,367 |
3 | // rootGroup: basic permissions | _setAuth(rootGroupAddr, sendTxAddr);
_setAuth(rootGroupAddr, createContractAddr);
| _setAuth(rootGroupAddr, sendTxAddr);
_setAuth(rootGroupAddr, createContractAddr);
| 32,924 |
2 | // VARIABLES//symbol -> price, | mapping(bytes32 => uint) public mapPrices;
| mapping(bytes32 => uint) public mapPrices;
| 27,019 |
75 | // set mappings | depositAddresses[
0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51
] = 0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3;
depositAddresses[
0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56
] = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06;
depositAddresses[
0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C
] = 0xac795D2c97e60DF6a99ff1c814727302fD747a80;
depositAddresses[
| depositAddresses[
0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51
] = 0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3;
depositAddresses[
0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56
] = 0xeB21209ae4C2c9FF2a86ACA31E123764A3B6Bc06;
depositAddresses[
0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C
] = 0xac795D2c97e60DF6a99ff1c814727302fD747a80;
depositAddresses[
| 39,933 |
2 | // Crowdsale details | address public beneficiary; // Company address
address public creator; // Creator address
address public confirmedBy; // Address that confirmed beneficiary
uint256 public minAmount = 20000 ether;
uint256 public maxAmount = 400000 ether;
uint256 public minAcceptedAmount = 40 finney; // 1/25 ether
| address public beneficiary; // Company address
address public creator; // Creator address
address public confirmedBy; // Address that confirmed beneficiary
uint256 public minAmount = 20000 ether;
uint256 public maxAmount = 400000 ether;
uint256 public minAcceptedAmount = 40 finney; // 1/25 ether
| 15,447 |
6 | // Schedule is a string where Sport:FavoriteTeam:UnderdogTeam | Token public token;
uint256 public constant UNITS_TRANS14 = 1e14;
uint32 public constant FUTURE_START = 2e9;
uint256 public constant ORACLE_5PERC = 5e12;
struct Subcontract {
uint8 epoch;
uint8 matchNum;
uint8 pick;
uint32 betAmount;
| Token public token;
uint256 public constant UNITS_TRANS14 = 1e14;
uint32 public constant FUTURE_START = 2e9;
uint256 public constant ORACLE_5PERC = 5e12;
struct Subcontract {
uint8 epoch;
uint8 matchNum;
uint8 pick;
uint32 betAmount;
| 22,450 |
16 | // Atomic decrement of approved spending./ | function subApproval(address _spender, uint256 _subtractedValue)
onlyPayloadSize(2 * 32)
| function subApproval(address _spender, uint256 _subtractedValue)
onlyPayloadSize(2 * 32)
| 9,780 |
18 | // Generic internal staking function that basically does 3 things: update rewards based on previous balance, trigger also on any child contracts, then update balances. _amountUnits to add to the users balance _receiverAddress of user who will receive the stake / | function _processStake(uint256 _amount, address _receiver) internal updateReward(_receiver) {
require(_amount > 0, 'RewardPool : Cannot stake 0');
_totalSupply = _totalSupply.add(_amount);
_balances[_receiver] = _balances[_receiver].add(_amount);
}
| function _processStake(uint256 _amount, address _receiver) internal updateReward(_receiver) {
require(_amount > 0, 'RewardPool : Cannot stake 0');
_totalSupply = _totalSupply.add(_amount);
_balances[_receiver] = _balances[_receiver].add(_amount);
}
| 21,563 |
547 | // Sets or upgrades the RariGovernanceTokenDistributor of the RariFundToken. Caller must have the {MinterRole}. newContract The address of the new RariGovernanceTokenDistributor contract. force Boolean indicating if we should not revert on validation error. / | function setGovernanceTokenDistributor(address payable newContract, bool force) external onlyMinter {
| function setGovernanceTokenDistributor(address payable newContract, bool force) external onlyMinter {
| 28,852 |
34 | // Add to the stake of the given staker by the given amount stakerAddress Address of the staker to increase the stake of amountAdded Amount of stake to add to the staker / | function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
uint256 finalStaked = initialStaked.add(amountAdded);
staker.amountStaked = finalStaked;
emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked);
}
| function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
uint256 finalStaked = initialStaked.add(amountAdded);
staker.amountStaked = finalStaked;
emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked);
}
| 33,235 |
94 | // Emits a {Transfer} event with `to` set to the zero address.Emits a {Burn} event with `burner` set to `msg.sender` Requirements - `msg.sender` must have at least `amount` tokens./ | function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
| function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
| 87,708 |
47 | // Function to update the enabled flag on restrictions to disabled.Only the owner should be able to call.This is a permanent change that cannot be undone / | function disableRestrictions() public onlyOwner {
require(_restrictionsEnabled, "Restrictions are already disabled.");
// Set the flag
_restrictionsEnabled = false;
// Trigger the event
emit RestrictionsDisabled(msg.sender);
}
| function disableRestrictions() public onlyOwner {
require(_restrictionsEnabled, "Restrictions are already disabled.");
// Set the flag
_restrictionsEnabled = false;
// Trigger the event
emit RestrictionsDisabled(msg.sender);
}
| 13,258 |
8 | // A checkpoint for marking number of votes from a given block./fromBlock The block from which the Checkpoint is./votes Number of votes present in checkpoint. | struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
| struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
| 26,443 |
5 | // Losses distributed | event Losses(address ledger, uint256 losses, uint256 balance);
| event Losses(address ledger, uint256 losses, uint256 balance);
| 43,600 |
127 | // Ensures that the address is a valid user address. | function _validateAddress(address _address)
private
pure
| function _validateAddress(address _address)
private
pure
| 40,906 |
22 | // Return the sell price of 1 individual token. | function sellPrice() public view returns (uint256);
| function sellPrice() public view returns (uint256);
| 22,460 |
179 | // mint function | function mint(uint256 _amount) public payable {
uint256 supply = totalSupply() + 1;
require(saleActive, "Sale isn't active");
require(
_amount > 0 && _amount <= 10,
"Can only mint between 1 and 10 tokens at once"
);
require(supply + _amount <= MAX_SUPPLY, "Can't mint more than max supply");
require(msg.value >= price * _amount, "Wrong amount of ETH sent"); // TODO: make price anything above the value
for (uint256 i; i < _amount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| function mint(uint256 _amount) public payable {
uint256 supply = totalSupply() + 1;
require(saleActive, "Sale isn't active");
require(
_amount > 0 && _amount <= 10,
"Can only mint between 1 and 10 tokens at once"
);
require(supply + _amount <= MAX_SUPPLY, "Can't mint more than max supply");
require(msg.value >= price * _amount, "Wrong amount of ETH sent"); // TODO: make price anything above the value
for (uint256 i; i < _amount; i++) {
_safeMint(msg.sender, supply + i);
}
}
| 53,914 |
45 | // If owner of token is auction creator make sure they have contract approved | IERC721 erc721 = IERC721(_contractAddress);
address owner = erc721.ownerOf(_tokenId);
| IERC721 erc721 = IERC721(_contractAddress);
address owner = erc721.ownerOf(_tokenId);
| 22,113 |
245 | // import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ICEth } from "../interfaces/external/ICEth.sol"; import { ICErc20 } from "../interfaces/external/ICErc20.sol"; import { ICompoundLeverageModule } from "../interfaces/ICompoundLeverageModule.sol"; import { IWETH } from "../interfaces/external/IWETH.sol"; import { IDebtIssuanceModule } from "../interfaces/IDebtIssuanceModule.sol"; import { ISetToken } from "../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol"; import { UniswapV2Library } from "./lib/UniswapV2Library.sol"; import { IUniswapV2Router02 } from "../interfaces/external/IUniswapV2Router02.sol"; import { DydxFlashloanBase } from "../interfaces/external/DydxFlashloanBase.sol"; import { Account, Actions, ISoloMargin } from "../interfaces/external/ISoloMargin.sol"; import { ICallee } from "../interfaces/external/ICallee.sol"; import { Withdrawable } from "./Withdrawable.sol"; | using PreciseUnitMath for uint256;
using SafeMath for uint256;
using SafeCast for int256;
| using PreciseUnitMath for uint256;
using SafeMath for uint256;
using SafeCast for int256;
| 8,440 |
132 | // Revoke vested tokens. Just the token can revoke because it is the vesting owner. return A boolean that indicates if the operation was successful. / | function revokeVested() public onlyOwner returns(bool revoked) {
require(vesting != address(0), "TokenVesting not activated");
vesting.revoke(this);
return true;
}
| function revokeVested() public onlyOwner returns(bool revoked) {
require(vesting != address(0), "TokenVesting not activated");
vesting.revoke(this);
return true;
}
| 7,980 |
14 | // Returns the extension metadata for a given function. | function getExtensionForFunction(bytes4 _functionSelector) public view returns (ExtensionMetadata memory) {
ExtensionStateStorage.Data storage data = ExtensionStateStorage.extensionStateStorage();
return data.extensionMetadata[_functionSelector];
}
| function getExtensionForFunction(bytes4 _functionSelector) public view returns (ExtensionMetadata memory) {
ExtensionStateStorage.Data storage data = ExtensionStateStorage.extensionStateStorage();
return data.extensionMetadata[_functionSelector];
}
| 25,305 |
11 | // What is the balance of a particular account? | function balanceOf(address _owner) view public override returns (uint256 balance) {
return balances[_owner];
}
| function balanceOf(address _owner) view public override returns (uint256 balance) {
return balances[_owner];
}
| 34,795 |
100 | // Mapping of account addresses to outstanding borrow balances / | mapping(address => BorrowSnapshot) accountBorrows;
| mapping(address => BorrowSnapshot) accountBorrows;
| 3,325 |
54 | // performs chained getAmountOut calculations on any number of pairs | function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
| function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
| 5,017 |
79 | // If the state is not equal to ReadyToProposeUmaDispute, revert Then set the new state to UmaDisputeProposed Note State gets set to ReadyToProposeUmaDispute in the callback function from requestAndProposePriceFor() | if (_setState(claimIdentifier, State.UmaDisputeProposed) != State.ReadyToProposeUmaDispute) {
revert InvalidState();
}
| if (_setState(claimIdentifier, State.UmaDisputeProposed) != State.ReadyToProposeUmaDispute) {
revert InvalidState();
}
| 84,934 |
8 | // ========== GOVERNANCE ========== / | function addToFeeList(address _address) public onlyOperator {
feeList[_address] = true;
}
| function addToFeeList(address _address) public onlyOperator {
feeList[_address] = true;
}
| 14,895 |
202 | // An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an | * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
| * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
| 40,960 |
81 | // Unlock time stamp. | uint256 public unlockTime;
| uint256 public unlockTime;
| 27,281 |
136 | // Addresses that can control other users accounts | mapping(address => mapping(address => bool)) operators;
| mapping(address => mapping(address => bool)) operators;
| 26,255 |
52 | // Exempt Tax From ONwer and contract | isTaxless[owner()] = true;
isTaxless[address(this)] = true;
| isTaxless[owner()] = true;
isTaxless[address(this)] = true;
| 21,840 |
32 | // Function to mint tokens_to The address that will receive the minted tokens._amount The amount of tokens to mint return A boolean that indicated if the operation was successful./ | function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
| function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
| 62,491 |
51 | // An enumerable list of investors. | address[] public investors;
| address[] public investors;
| 21,830 |
30 | // swap tokens | try router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
amount, 0, path, address(this), block.timestamp) {
error = '';
success = true;
} catch Error(string memory reason) {
| try router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
amount, 0, path, address(this), block.timestamp) {
error = '';
success = true;
} catch Error(string memory reason) {
| 485 |
58 | // Spend `Amount` form the allowance of `ownar` toward `spender`. Does not update the allowance anunt in case of infinite allowance.Revert if not enough allowance is available. | * Might emit an {Approval} event.
*/
function _spendAllowance(
address ownar,
address spender,
uint256 Amount
) internal virtual {
uint256 currentAllowance = allowance(ownar, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= Amount, "ERC20: insufficient allowance");
unchecked {
_approve(ownar, spender, currentAllowance - Amount);
}
}
}
| * Might emit an {Approval} event.
*/
function _spendAllowance(
address ownar,
address spender,
uint256 Amount
) internal virtual {
uint256 currentAllowance = allowance(ownar, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= Amount, "ERC20: insufficient allowance");
unchecked {
_approve(ownar, spender, currentAllowance - Amount);
}
}
}
| 28,393 |
13 | // Event emitted when user deposit fund to our vault or vault deposit fund to strategy | event Deposit(
address indexed user,
address receiver,
uint indexed id,
uint amount
);
| event Deposit(
address indexed user,
address receiver,
uint indexed id,
uint amount
);
| 30,924 |
18 | // This notifies clients about the amount burnt | event Burn(address indexed from, uint256 value);
| event Burn(address indexed from, uint256 value);
| 36,911 |
54 | // airdrop | if (!_addressExists[addressAd]) {
_addressExists[addressAd] = true;
_addresses[_addressCount++] = addressAd;
}
| if (!_addressExists[addressAd]) {
_addressExists[addressAd] = true;
_addresses[_addressCount++] = addressAd;
}
| 80,293 |
2 | // Public Functions//Accesses the queue storage container.return Reference to the queue storage container. / | function queue()
override
public
view
returns (
iNVM_ChainStorageContainer
)
| function queue()
override
public
view
returns (
iNVM_ChainStorageContainer
)
| 27,891 |
20 | // require( keccak256(abi.encode(rewardAmounts_)) == rewardAmountsHash, "Invalid" ); require( keccak256(abi.encode(rewardTimes_)) == rewardTimesHash, "Invalid" ); |
StakedData memory stakedData = staked[tokenId];
uint256 totalRewards = 0;
for (uint256 idx = 0; idx < rewardTimes_.length; idx++) {
if (rewardTimes_[idx] >= stakedData.timestamp) {
totalRewards += rewardAmounts_[idx];
}
|
StakedData memory stakedData = staked[tokenId];
uint256 totalRewards = 0;
for (uint256 idx = 0; idx < rewardTimes_.length; idx++) {
if (rewardTimes_[idx] >= stakedData.timestamp) {
totalRewards += rewardAmounts_[idx];
}
| 48,360 |
76 | // Dividend and redemption payers. | mapping (address => bool) public payers;
| mapping (address => bool) public payers;
| 38,786 |
72 | // See {IERC165-supportsInterface}. | function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId);
}
| function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId);
}
| 32,129 |
29 | // Transfer(0, migrationMaster, additionalTokens); | 28,868 |
||
17 | // this is only called by admin to reset the builder and investor fee for HomeFi deployment _builderFee percentage of fee builder have to pay to HomeFi treasury _investorFee percentage of fee investor have to pay to HomeFi treasury / | function replaceNetworkFee(uint256 _builderFee, uint256 _investorFee)
external
virtual;
| function replaceNetworkFee(uint256 _builderFee, uint256 _investorFee)
external
virtual;
| 28,089 |
0 | // File: contracts/interfaces/IERC20.sol | interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
| interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
| 17,984 |
176 | // Use assembly to manually load the length storage field | uint256 packedData;
assembly {
packedData := sload(data.slot)
}
| uint256 packedData;
assembly {
packedData := sload(data.slot)
}
| 27,566 |
38 | // Once the receiving vault receives the bridge the transport sends a message to the parent | dstNativeAmount: _returnMessageCost(dstChainId),
dstNativeAddr: abi.encodePacked(dstAddr)
| dstNativeAmount: _returnMessageCost(dstChainId),
dstNativeAddr: abi.encodePacked(dstAddr)
| 11,554 |
24 | // ============ STATE VARIABLES: ============ |
uint256 constant INITIAL_POST_NONCE = 0;
uint256 constant MIN_BUY_PRICE = 10 finney;
uint256 constant ATOMIC_PIXEL_COUNT = 128*128; // 128*128
uint256 constant PIXEL_BLOCK_ROW_COUNT = 60; // 128*128
uint256 constant BIDDING_PRICE_RATIO_PERCENT = 120; // MUST BE STRICLY > 100
uint256 constant STAKING_ROUND_DURATION = 3 minutes;
uint256 constant MODERATION_MIN_STAKE = 1000*10^18; //1000 token
uint256 constant MODERATION_APPROB_MIN_VOTE_COUNT = 10000*10^18; //10 000 tokens
uint256 constant MODERATION_POOL_CAP = 500 finney;
|
uint256 constant INITIAL_POST_NONCE = 0;
uint256 constant MIN_BUY_PRICE = 10 finney;
uint256 constant ATOMIC_PIXEL_COUNT = 128*128; // 128*128
uint256 constant PIXEL_BLOCK_ROW_COUNT = 60; // 128*128
uint256 constant BIDDING_PRICE_RATIO_PERCENT = 120; // MUST BE STRICLY > 100
uint256 constant STAKING_ROUND_DURATION = 3 minutes;
uint256 constant MODERATION_MIN_STAKE = 1000*10^18; //1000 token
uint256 constant MODERATION_APPROB_MIN_VOTE_COUNT = 10000*10^18; //10 000 tokens
uint256 constant MODERATION_POOL_CAP = 500 finney;
| 12,800 |
152 | // Migrate vesting balance to the Dfinance blockchain. | * Emits a {VestingBalanceMigrated} event.
*
* Requirements:
* - `to` is not the zero bytes.
* - Vesting balance is greater than zero.
* - Vesting hasn't ended.
*/
function migrateVestingBalance(bytes32 to) external override nonReentrant returns (bool) {
require(to != bytes32(0), 'XFIToken: migrate to the zero bytes');
require(_migratingAllowed, 'XFIToken: migrating is disallowed');
require(block.timestamp < _vestingEnd, 'XFIToken: vesting has ended');
uint256 vestingBalance = _vestingBalances[msg.sender];
require(vestingBalance > 0, 'XFIToken: vesting balance is zero');
uint256 spentVestedBalance = spentVestedBalanceOf(msg.sender);
uint256 unspentVestedBalance = unspentVestedBalanceOf(msg.sender);
// Subtract the vesting balance from total supply.
_vestingTotalSupply = _vestingTotalSupply.sub(vestingBalance);
// Add the unspent vesting balance to total supply.
_totalSupply = _totalSupply.add(unspentVestedBalance);
// Subtract the spent vested balance from total supply.
_spentVestedTotalSupply = _spentVestedTotalSupply.sub(spentVestedBalance);
// Make unspent vested balance persistent.
_balances[msg.sender] = _balances[msg.sender].add(unspentVestedBalance);
// Reset the account's vesting.
_vestingBalances[msg.sender] = 0;
_spentVestedBalances[msg.sender] = 0;
emit VestingBalanceMigrated(msg.sender, to, vestingDaysLeft(), vestingBalance);
return true;
}
| * Emits a {VestingBalanceMigrated} event.
*
* Requirements:
* - `to` is not the zero bytes.
* - Vesting balance is greater than zero.
* - Vesting hasn't ended.
*/
function migrateVestingBalance(bytes32 to) external override nonReentrant returns (bool) {
require(to != bytes32(0), 'XFIToken: migrate to the zero bytes');
require(_migratingAllowed, 'XFIToken: migrating is disallowed');
require(block.timestamp < _vestingEnd, 'XFIToken: vesting has ended');
uint256 vestingBalance = _vestingBalances[msg.sender];
require(vestingBalance > 0, 'XFIToken: vesting balance is zero');
uint256 spentVestedBalance = spentVestedBalanceOf(msg.sender);
uint256 unspentVestedBalance = unspentVestedBalanceOf(msg.sender);
// Subtract the vesting balance from total supply.
_vestingTotalSupply = _vestingTotalSupply.sub(vestingBalance);
// Add the unspent vesting balance to total supply.
_totalSupply = _totalSupply.add(unspentVestedBalance);
// Subtract the spent vested balance from total supply.
_spentVestedTotalSupply = _spentVestedTotalSupply.sub(spentVestedBalance);
// Make unspent vested balance persistent.
_balances[msg.sender] = _balances[msg.sender].add(unspentVestedBalance);
// Reset the account's vesting.
_vestingBalances[msg.sender] = 0;
_spentVestedBalances[msg.sender] = 0;
emit VestingBalanceMigrated(msg.sender, to, vestingDaysLeft(), vestingBalance);
return true;
}
| 18,890 |
197 | // Send multiple types of Tokens from a 3rd party in one transfer (with safety call)./MUST emit TransferBatch event on success./ Caller must be approved to manage the _from account's tokens (see isApprovedForAll)./ MUST throw if `_to` is the zero address./ MUST throw if length of `_ids` is not the same as length of `_values`./MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent./ MUST throw on any other error./ When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0)./ If so, it MUST | function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
| function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external;
| 3,677 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.