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
|
|---|---|---|---|---|
7
|
// EIP2981 royalties implementation. / Maintain flexibility to modify royalties recipient (could also add basis points).
|
function _setRoyalties(address newRecipient) internal {
require(
newRecipient != address(0),
"Royalties: new recipient is the zero address"
);
_recipient = newRecipient;
}
|
function _setRoyalties(address newRecipient) internal {
require(
newRecipient != address(0),
"Royalties: new recipient is the zero address"
);
_recipient = newRecipient;
}
| 34,736
|
22
|
// Multiplies two exponentials given their mantissas, returning a new exponential. /
|
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
|
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
| 48,327
|
277
|
// stakable/burnable for x
|
slot = 15;
o = uint16(seq[sp++] % n1[slot]);
for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i];
slot = 6;
o = uint16(seq[sp++] % n1[slot]);
for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i];
|
slot = 15;
o = uint16(seq[sp++] % n1[slot]);
for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i];
slot = 6;
o = uint16(seq[sp++] % n1[slot]);
for (uint i=p1[slot][o];t1[slot][i] != '|';i++) s[p++] = t1[slot][i];
| 77,732
|
61
|
// Forward funds to wallet address
|
vault.close();
|
vault.close();
| 77,393
|
7
|
// Redeems asset tokens from the yield source./redeemAmount The amount of yield-bearing tokens to be redeemed/ return The actual amount of tokens that were redeemed.
|
function _redeem(uint256 redeemAmount) internal override returns (uint256) {
return redeemAmount;
}
|
function _redeem(uint256 redeemAmount) internal override returns (uint256) {
return redeemAmount;
}
| 38,582
|
10
|
// Transfer ownership of an article./Lets you to transfer ownership of an article. This is useful when you want to change owner account without withdrawing and resubmitting./_articleStorageAddress The address of article in the storage./_newOwner The new owner of the article which resides in the storage address, provided by the previous parameter.
|
function transferOwnership(uint80 _articleStorageAddress, address payable _newOwner) external virtual;
|
function transferOwnership(uint80 _articleStorageAddress, address payable _newOwner) external virtual;
| 24,703
|
104
|
// Used for percentage maths /
|
uint256 public constant BASE = 10**18;
|
uint256 public constant BASE = 10**18;
| 13,428
|
31
|
// calculateSecondarySaleFee// Utility function for calculating the secondary sale fee for given amount of wei _contractAddress address ERC721Contract address. _amount uint256 wei amount.return uint256 wei fee. /
|
function calculateSecondarySaleFee(address _contractAddress, uint256 _amount)
external
override
view
returns (uint256)
|
function calculateSecondarySaleFee(address _contractAddress, uint256 _amount)
external
override
view
returns (uint256)
| 10,847
|
4
|
// Count of partners
|
uint public partnerCount;
|
uint public partnerCount;
| 20,196
|
12
|
// ========== RESTRICTED FUNCTIONS ========== /
|
function notifyRewardAmount(uint256 reward) external onlyRewardsDistribution updateReward(address(0)) {
require(block.timestamp >= periodFinish, "cannot notify reward until period ended");
rewardRate = reward.div(rewardsDuration);
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
|
function notifyRewardAmount(uint256 reward) external onlyRewardsDistribution updateReward(address(0)) {
require(block.timestamp >= periodFinish, "cannot notify reward until period ended");
rewardRate = reward.div(rewardsDuration);
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
| 4,891
|
30
|
// IMPORTANT: The same issues {IERC20-approve} has related to transactionordering also apply here. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address.- `spender` cannot be the zero address.- `deadline` must be a timestamp in the future.- `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`over the EIP712-formatted function arguments.- the signature must use ``owner``'s current nonce (see {nonces}). For more information on the signature format, see thesection]. /
|
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
|
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
| 23,991
|
70
|
// Required Events
|
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts);
event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio);
|
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts);
event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio);
| 32,118
|
0
|
// Payment Queue Interface. /
|
interface IPaymentQueue {
/**
* @dev Retrieve the current number of payments.
* @return The current number of payments.
*/
function getNumOfPayments() external view returns (uint256);
/**
* @dev Retrieve the sum of all payments.
* @return The sum of all payments.
*/
function getPaymentsSum() external view returns (uint256);
/**
* @dev Retrieve the details of a payment.
* @param _index The index of the payment.
* @return The payment wallet address and amount.
*/
function getPayment(uint256 _index) external view returns (address, uint256);
/**
* @dev Add a new payment.
* @param _wallet The payment wallet address.
* @param _amount The payment amount.
*/
function addPayment(address _wallet, uint256 _amount) external;
/**
* @dev Update the first payment.
* @param _amount The new payment amount.
*/
function updatePayment(uint256 _amount) external;
/**
* @dev Remove the first payment.
*/
function removePayment() external;
}
|
interface IPaymentQueue {
/**
* @dev Retrieve the current number of payments.
* @return The current number of payments.
*/
function getNumOfPayments() external view returns (uint256);
/**
* @dev Retrieve the sum of all payments.
* @return The sum of all payments.
*/
function getPaymentsSum() external view returns (uint256);
/**
* @dev Retrieve the details of a payment.
* @param _index The index of the payment.
* @return The payment wallet address and amount.
*/
function getPayment(uint256 _index) external view returns (address, uint256);
/**
* @dev Add a new payment.
* @param _wallet The payment wallet address.
* @param _amount The payment amount.
*/
function addPayment(address _wallet, uint256 _amount) external;
/**
* @dev Update the first payment.
* @param _amount The new payment amount.
*/
function updatePayment(uint256 _amount) external;
/**
* @dev Remove the first payment.
*/
function removePayment() external;
}
| 14,151
|
48
|
// Gets the information of a round of a question. _arbitrationID The ID of the arbitration. _round The round to query.return paidFees The amount of fees paid for each fully funded answer.return feeRewards The amount of fees that will be used as rewards.return fundedAnswers IDs of fully funded answers. /
|
function getRoundInfo(uint256 _arbitrationID, uint256 _round)
external
view
returns (
uint256[] memory paidFees,
uint256 feeRewards,
uint256[] memory fundedAnswers
)
|
function getRoundInfo(uint256 _arbitrationID, uint256 _round)
external
view
returns (
uint256[] memory paidFees,
uint256 feeRewards,
uint256[] memory fundedAnswers
)
| 53,299
|
228
|
// allow the curator to change their fee/_fee the new fee
|
function updateFee(uint256 _fee) external {
require(msg.sender == curator, "update:not curator");
require(_fee <= ISettings(settings).maxCuratorFee(), "update:cannot increase fee this high");
_claimFees();
fee = _fee;
}
|
function updateFee(uint256 _fee) external {
require(msg.sender == curator, "update:not curator");
require(_fee <= ISettings(settings).maxCuratorFee(), "update:cannot increase fee this high");
_claimFees();
fee = _fee;
}
| 65,502
|
10
|
// Confirm a transaction by providing just the hash. We use the previous transactions map,txs, in order to determine the body of the transaction from the hash provided. _h The transaction hash to approve. /
|
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
if (txs[_h].to != 0) {
assert(txs[_h].to.call.value(txs[_h].value)(txs[_h].data));
MultiTransact(msg.sender, _h, txs[_h].value, txs[_h].to, txs[_h].data);
delete txs[_h];
return true;
}
}
|
function confirm(bytes32 _h) onlymanyowners(_h) returns (bool) {
if (txs[_h].to != 0) {
assert(txs[_h].to.call.value(txs[_h].value)(txs[_h].data));
MultiTransact(msg.sender, _h, txs[_h].value, txs[_h].to, txs[_h].data);
delete txs[_h];
return true;
}
}
| 29,621
|
32
|
// 把合约余额转出
|
function sendleftmoney(address _to, uint _value) public onlyadmin{
_transfer(this, _to, _value);
}
|
function sendleftmoney(address _to, uint _value) public onlyadmin{
_transfer(this, _to, _value);
}
| 7,904
|
3
|
// only log donations larger than 1 szabo to prevent spam
|
if(msg.value > 1 szabo) {
emit Deposit(msg.sender, msg.value);
}
|
if(msg.value > 1 szabo) {
emit Deposit(msg.sender, msg.value);
}
| 28,252
|
69
|
// set the costManager for all future calls to produce()/
|
function setCostManager(address costManager_) public onlyOwner {
costManager = costManager_;
}
|
function setCostManager(address costManager_) public onlyOwner {
costManager = costManager_;
}
| 23,764
|
206
|
// PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position virtual unit. Takes a real unit and converts it to virtual before committing. /
|
function editExternalPositionUnit(
address _component,
address _positionModule,
int256 _realUnit
)
external
onlyModule
whenLockedOnlyLocker
|
function editExternalPositionUnit(
address _component,
address _positionModule,
int256 _realUnit
)
external
onlyModule
whenLockedOnlyLocker
| 39,203
|
646
|
// solhint-disable // Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to naturalexponentiation and logarithm (where the base is Euler's number).Fernando Martinelli - @fernandomartinelli Sergio Yuhjtman - @sergioyuhjtman Daniel Fernandez - @dmf7z /
|
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
|
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
_require(x < 2**255, Errors.X_OUT_OF_BOUNDS);
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
_require(y < MILD_EXPONENT_BOUND, Errors.Y_OUT_OF_BOUNDS);
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
_require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
Errors.PRODUCT_OUT_OF_BOUNDS
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
_require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, Errors.INVALID_EXPONENT);
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
_require(a > 0, Errors.OUT_OF_BOUNDS);
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
| 5,170
|
17
|
// The total deposits and winnings for each user. /
|
mapping (address => uint256) balances;
|
mapping (address => uint256) balances;
| 27,248
|
63
|
// Get the internal balance of the contract return The internal balance of the contract in Wei/
|
function getContractBalance() public view onlyOwner returns(uint) {
return address(this).balance;
}
|
function getContractBalance() public view onlyOwner returns(uint) {
return address(this).balance;
}
| 29,312
|
105
|
// DemeterCrowdsale construction. _startTime beginning of crowdsale. _endTime end of crowdsale. _whiteListRegistrationEndTime time until which whitelist registration is still possible. _whiteListEndTime time until which only whitelist purchases are accepted. _rate how many tokens per ether in case of no whitelist or referral bonuses. _cap crowdsale hard cap in wei. _goal minimum crowdsale goal in wei; if not reached, causes refunds to be available. _wallet where the raised ethers are transferred in case of successful crowdsale. /
|
function DemeterCrowdsale(
|
function DemeterCrowdsale(
| 25,769
|
66
|
// transfer ownership of the token to the owner of the presale contract
|
function transferTokenContractOwnership(address _address) public onlyOwner {
token.transferOwnership(_address);
}
|
function transferTokenContractOwnership(address _address) public onlyOwner {
token.transferOwnership(_address);
}
| 62,971
|
39
|
// src/osm.sol/ pragma solidity >=0.5.10; // import "ds-value/value.sol"; /
|
contract LibNote {
event LogNote(
bytes4 indexed sig,
address indexed usr,
bytes32 indexed arg1,
bytes32 indexed arg2,
bytes data
) anonymous;
modifier note {
_;
assembly {
// log an 'anonymous' event with a constant 6 words of calldata
// and four indexed topics: selector, caller, arg1 and arg2
let mark := msize // end of memory ensures zero
mstore(0x40, add(mark, 288)) // update free memory pointer
mstore(mark, 0x20) // bytes type data offset
mstore(add(mark, 0x20), 224) // bytes size (padded)
calldatacopy(add(mark, 0x40), 0, 224) // bytes payload
log4(mark, 288, // calldata
shl(224, shr(224, calldataload(0))), // msg.sig
caller, // msg.sender
calldataload(4), // arg1
calldataload(36) // arg2
)
}
}
}
|
contract LibNote {
event LogNote(
bytes4 indexed sig,
address indexed usr,
bytes32 indexed arg1,
bytes32 indexed arg2,
bytes data
) anonymous;
modifier note {
_;
assembly {
// log an 'anonymous' event with a constant 6 words of calldata
// and four indexed topics: selector, caller, arg1 and arg2
let mark := msize // end of memory ensures zero
mstore(0x40, add(mark, 288)) // update free memory pointer
mstore(mark, 0x20) // bytes type data offset
mstore(add(mark, 0x20), 224) // bytes size (padded)
calldatacopy(add(mark, 0x40), 0, 224) // bytes payload
log4(mark, 288, // calldata
shl(224, shr(224, calldataload(0))), // msg.sig
caller, // msg.sender
calldataload(4), // arg1
calldataload(36) // arg2
)
}
}
}
| 31,539
|
117
|
// Delegate call to get balance who Address to get balance forreturn balance of account /
|
function delegateBalanceOf(address who) public view returns (uint256) {
return balanceOf(who);
}
|
function delegateBalanceOf(address who) public view returns (uint256) {
return balanceOf(who);
}
| 11,615
|
223
|
// ------------------------------------------------------------------------------ [BondOperation contract] The BondOperation contract increases / decreases the total coin supply by redeeming / issuing bonds. The bond budget is updated by the ACB every epoch. Permission: Except public getters, only the ACB can call the methods.------------------------------------------------------------------------------
|
contract BondOperation_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public BOND_PRICE;
uint public BOND_REDEMPTION_PRICE;
uint public BOND_REDEMPTION_PERIOD;
uint public BOND_REDEEMABLE_PERIOD;
// Attributes. See the comment in initialize().
JohnLawBond public bond_;
int public bond_budget_;
JohnLawBond_v2 public bond_v2_;
int public bond_budget_v2_;
// Events.
event IncreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint issued_bonds, uint redemption_epoch);
event DecreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event UpdateBondBudgetEvent(uint indexed epoch_id, int delta,
int bond_budget, uint mint);
function upgrade(JohnLawBond_v2 bond)
public onlyOwner {
bond_v2_ = bond;
bond_budget_v2_ = bond_budget_;
bond_v2_.upgrade();
}
// Deprecate the contract.
function deprecate()
public onlyOwner {
bond_v2_.transferOwnership(msg.sender);
}
// Increase the total bond supply by issuing bonds.
//
// Parameters
// ----------------
// |count|: The number of bonds to be issued.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// The redemption epoch of the issued bonds if it succeeds. 0 otherwise.
function increaseBondSupply(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
return increaseBondSupply_v2(sender, count, epoch_id, coin);
}
function increaseBondSupply_v2(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
require(count > 0, "BondOperation: You must purchase at least one bond.");
require(bond_budget_v2_ >= count.toInt256(),
"BondOperation: The bond budget is not enough.");
uint amount = BOND_PRICE * count;
require(coin.balanceOf(sender) >= amount,
"BondOperation: Your coin balance is not enough.");
// Set the redemption epoch of the bonds.
uint redemption_epoch = epoch_id + BOND_REDEMPTION_PERIOD;
// Issue new bonds.
bond_v2_.mint(sender, redemption_epoch, count);
bond_budget_v2_ -= count.toInt256();
require(bond_budget_v2_ >= 0, "pb1");
require(bond_v2_.balanceOf(sender, redemption_epoch) > 0, "pb2");
// Burn the corresponding coins.
coin.burn(sender, amount);
bond_budget_ = bond_budget_v2_;
emit IncreaseBondSupplyEvent(sender, epoch_id, count, redemption_epoch);
return redemption_epoch;
}
// Decrease the total bond supply by redeeming bonds.
//
// Parameters
// ----------------
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - The number of redeemed bonds.
// - The number of expired bonds.
function decreaseBondSupply(address sender, uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
return decreaseBondSupply_v2(sender, redemption_epochs, epoch_id, coin);
}
function decreaseBondSupply_v2(address sender,
uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
uint redeemed_bonds = 0;
uint expired_bonds = 0;
for (uint i = 0; i < redemption_epochs.length; i++) {
uint redemption_epoch = redemption_epochs[i];
uint count = bond_v2_.balanceOf(sender, redemption_epoch);
if (epoch_id < redemption_epoch) {
// If the bonds have not yet hit their redemption epoch, the
// BondOperation accepts the redemption as long as |bond_budget_| is
// negative.
if (bond_budget_v2_ >= 0) {
continue;
}
if (count > (-bond_budget_v2_).toUint256()) {
count = (-bond_budget_v2_).toUint256();
}
bond_budget_v2_ += count.toInt256();
}
if (epoch_id < redemption_epoch + BOND_REDEEMABLE_PERIOD) {
// If the bonds are not expired, mint the corresponding coins to the
// sender account.
uint amount = count * BOND_REDEMPTION_PRICE;
coin.mint(sender, amount);
redeemed_bonds += count;
} else {
expired_bonds += count;
}
// Burn the redeemed / expired bonds.
bond_v2_.burn(sender, redemption_epoch, count);
}
bond_budget_ = bond_budget_v2_;
emit DecreaseBondSupplyEvent(sender, epoch_id,
redeemed_bonds, expired_bonds);
return (redeemed_bonds, expired_bonds);
}
// Update the bond budget to increase or decrease the total coin supply.
//
// Parameters
// ----------------
// |delta|: The target increase or decrease of the total coin supply.
// |epoch_id|: The current epoch ID.
//
// Returns
// ----------------
// The amount of coins that cannot be increased by adjusting the bond budget
// and thus need to be newly minted.
function updateBondBudget(int delta, uint epoch_id)
public onlyOwner returns (uint) {
return updateBondBudget_v2(delta, epoch_id);
}
function updateBondBudget_v2(int delta, uint epoch_id)
public onlyOwner returns (uint) {
uint mint = 0;
uint bond_supply = validBondSupply(epoch_id);
if (delta == 0) {
// No change in the total coin supply.
bond_budget_v2_ = 0;
} else if (delta > 0) {
// Increase the total coin supply.
uint count = delta.toUint256() / BOND_REDEMPTION_PRICE;
if (count <= bond_supply) {
// If there are sufficient bonds to redeem, increase the total coin
// supply by redeeming the bonds.
bond_budget_v2_ = -count.toInt256();
} else {
// Otherwise, redeem all the issued bonds.
bond_budget_v2_ = -bond_supply.toInt256();
// The remaining coins need to be newly minted.
mint = (count - bond_supply) * BOND_REDEMPTION_PRICE;
}
require(bond_budget_v2_ <= 0, "cs1");
} else {
// Issue new bonds to decrease the total coin supply.
bond_budget_v2_ = -delta / BOND_PRICE.toInt256();
require(bond_budget_v2_ >= 0, "cs2");
}
bond_budget_ = bond_budget_v2_;
require(bond_supply.toInt256() + bond_budget_v2_ >= 0, "cs3");
emit UpdateBondBudgetEvent(epoch_id, delta, bond_budget_v2_, mint);
return mint;
}
// Public getter: Return the valid bond supply; i.e., the total supply of
// not-yet-expired bonds.
function validBondSupply(uint epoch_id)
public view returns (uint) {
return validBondSupply_v2(epoch_id);
}
function validBondSupply_v2(uint epoch_id)
public view returns (uint) {
uint count = 0;
for (uint redemption_epoch =
(epoch_id > BOND_REDEEMABLE_PERIOD ?
epoch_id - BOND_REDEEMABLE_PERIOD + 1 : 0);
// The previous versions of the smart contract might have used a larger
// BOND_REDEMPTION_PERIOD. Add 20 to look up all the redemption
// epochs that might have set in the previous versions.
redemption_epoch <= epoch_id + BOND_REDEMPTION_PERIOD + 20;
redemption_epoch++) {
count += bond_v2_.bondSupplyAt(redemption_epoch);
}
return count;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
return revokeOwnership_v2(coin);
}
function revokeOwnership_v2(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
}
|
contract BondOperation_v2 is OwnableUpgradeable {
using SafeCast for uint;
using SafeCast for int;
// Constants. The values are defined in initialize(). The values never change
// during the contract execution but use 'public' (instead of 'constant')
// because tests want to override the values.
uint public BOND_PRICE;
uint public BOND_REDEMPTION_PRICE;
uint public BOND_REDEMPTION_PERIOD;
uint public BOND_REDEEMABLE_PERIOD;
// Attributes. See the comment in initialize().
JohnLawBond public bond_;
int public bond_budget_;
JohnLawBond_v2 public bond_v2_;
int public bond_budget_v2_;
// Events.
event IncreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint issued_bonds, uint redemption_epoch);
event DecreaseBondSupplyEvent(address indexed sender, uint indexed epoch_id,
uint redeemed_bonds, uint expired_bonds);
event UpdateBondBudgetEvent(uint indexed epoch_id, int delta,
int bond_budget, uint mint);
function upgrade(JohnLawBond_v2 bond)
public onlyOwner {
bond_v2_ = bond;
bond_budget_v2_ = bond_budget_;
bond_v2_.upgrade();
}
// Deprecate the contract.
function deprecate()
public onlyOwner {
bond_v2_.transferOwnership(msg.sender);
}
// Increase the total bond supply by issuing bonds.
//
// Parameters
// ----------------
// |count|: The number of bonds to be issued.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// The redemption epoch of the issued bonds if it succeeds. 0 otherwise.
function increaseBondSupply(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
return increaseBondSupply_v2(sender, count, epoch_id, coin);
}
function increaseBondSupply_v2(address sender, uint count,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint) {
require(count > 0, "BondOperation: You must purchase at least one bond.");
require(bond_budget_v2_ >= count.toInt256(),
"BondOperation: The bond budget is not enough.");
uint amount = BOND_PRICE * count;
require(coin.balanceOf(sender) >= amount,
"BondOperation: Your coin balance is not enough.");
// Set the redemption epoch of the bonds.
uint redemption_epoch = epoch_id + BOND_REDEMPTION_PERIOD;
// Issue new bonds.
bond_v2_.mint(sender, redemption_epoch, count);
bond_budget_v2_ -= count.toInt256();
require(bond_budget_v2_ >= 0, "pb1");
require(bond_v2_.balanceOf(sender, redemption_epoch) > 0, "pb2");
// Burn the corresponding coins.
coin.burn(sender, amount);
bond_budget_ = bond_budget_v2_;
emit IncreaseBondSupplyEvent(sender, epoch_id, count, redemption_epoch);
return redemption_epoch;
}
// Decrease the total bond supply by redeeming bonds.
//
// Parameters
// ----------------
// |redemption_epochs|: An array of bonds to be redeemed. The bonds are
// identified by their redemption epochs.
// |epoch_id|: The current epoch ID.
// |coin|: The JohnLawCoin contract. The ownership needs to be transferred to
// this contract.
//
// Returns
// ----------------
// A tuple of two values:
// - The number of redeemed bonds.
// - The number of expired bonds.
function decreaseBondSupply(address sender, uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
return decreaseBondSupply_v2(sender, redemption_epochs, epoch_id, coin);
}
function decreaseBondSupply_v2(address sender,
uint[] memory redemption_epochs,
uint epoch_id, JohnLawCoin_v2 coin)
public onlyOwner returns (uint, uint) {
uint redeemed_bonds = 0;
uint expired_bonds = 0;
for (uint i = 0; i < redemption_epochs.length; i++) {
uint redemption_epoch = redemption_epochs[i];
uint count = bond_v2_.balanceOf(sender, redemption_epoch);
if (epoch_id < redemption_epoch) {
// If the bonds have not yet hit their redemption epoch, the
// BondOperation accepts the redemption as long as |bond_budget_| is
// negative.
if (bond_budget_v2_ >= 0) {
continue;
}
if (count > (-bond_budget_v2_).toUint256()) {
count = (-bond_budget_v2_).toUint256();
}
bond_budget_v2_ += count.toInt256();
}
if (epoch_id < redemption_epoch + BOND_REDEEMABLE_PERIOD) {
// If the bonds are not expired, mint the corresponding coins to the
// sender account.
uint amount = count * BOND_REDEMPTION_PRICE;
coin.mint(sender, amount);
redeemed_bonds += count;
} else {
expired_bonds += count;
}
// Burn the redeemed / expired bonds.
bond_v2_.burn(sender, redemption_epoch, count);
}
bond_budget_ = bond_budget_v2_;
emit DecreaseBondSupplyEvent(sender, epoch_id,
redeemed_bonds, expired_bonds);
return (redeemed_bonds, expired_bonds);
}
// Update the bond budget to increase or decrease the total coin supply.
//
// Parameters
// ----------------
// |delta|: The target increase or decrease of the total coin supply.
// |epoch_id|: The current epoch ID.
//
// Returns
// ----------------
// The amount of coins that cannot be increased by adjusting the bond budget
// and thus need to be newly minted.
function updateBondBudget(int delta, uint epoch_id)
public onlyOwner returns (uint) {
return updateBondBudget_v2(delta, epoch_id);
}
function updateBondBudget_v2(int delta, uint epoch_id)
public onlyOwner returns (uint) {
uint mint = 0;
uint bond_supply = validBondSupply(epoch_id);
if (delta == 0) {
// No change in the total coin supply.
bond_budget_v2_ = 0;
} else if (delta > 0) {
// Increase the total coin supply.
uint count = delta.toUint256() / BOND_REDEMPTION_PRICE;
if (count <= bond_supply) {
// If there are sufficient bonds to redeem, increase the total coin
// supply by redeeming the bonds.
bond_budget_v2_ = -count.toInt256();
} else {
// Otherwise, redeem all the issued bonds.
bond_budget_v2_ = -bond_supply.toInt256();
// The remaining coins need to be newly minted.
mint = (count - bond_supply) * BOND_REDEMPTION_PRICE;
}
require(bond_budget_v2_ <= 0, "cs1");
} else {
// Issue new bonds to decrease the total coin supply.
bond_budget_v2_ = -delta / BOND_PRICE.toInt256();
require(bond_budget_v2_ >= 0, "cs2");
}
bond_budget_ = bond_budget_v2_;
require(bond_supply.toInt256() + bond_budget_v2_ >= 0, "cs3");
emit UpdateBondBudgetEvent(epoch_id, delta, bond_budget_v2_, mint);
return mint;
}
// Public getter: Return the valid bond supply; i.e., the total supply of
// not-yet-expired bonds.
function validBondSupply(uint epoch_id)
public view returns (uint) {
return validBondSupply_v2(epoch_id);
}
function validBondSupply_v2(uint epoch_id)
public view returns (uint) {
uint count = 0;
for (uint redemption_epoch =
(epoch_id > BOND_REDEEMABLE_PERIOD ?
epoch_id - BOND_REDEEMABLE_PERIOD + 1 : 0);
// The previous versions of the smart contract might have used a larger
// BOND_REDEMPTION_PERIOD. Add 20 to look up all the redemption
// epochs that might have set in the previous versions.
redemption_epoch <= epoch_id + BOND_REDEMPTION_PERIOD + 20;
redemption_epoch++) {
count += bond_v2_.bondSupplyAt(redemption_epoch);
}
return count;
}
// Return the ownership of the JohnLawCoin contract to the ACB.
//
// Parameters
// ----------------
// |coin|: The JohnLawCoin contract.
//
// Returns
// ----------------
// None.
function revokeOwnership(JohnLawCoin_v2 coin)
public onlyOwner {
return revokeOwnership_v2(coin);
}
function revokeOwnership_v2(JohnLawCoin_v2 coin)
public onlyOwner {
coin.transferOwnership(msg.sender);
}
}
| 20,881
|
50
|
// https:etherscan.io/address/0x07Fa3744FeC271F80c2EA97679823F65c13CCDf4
|
address internal constant WBTC_INTEREST_RATE_STRATEGY =
0x07Fa3744FeC271F80c2EA97679823F65c13CCDf4;
|
address internal constant WBTC_INTEREST_RATE_STRATEGY =
0x07Fa3744FeC271F80c2EA97679823F65c13CCDf4;
| 15,747
|
133
|
// workaround for a solidity bug
|
function _myEthBalance() private view returns(uint256) {
address self = address(this);
return self.balance;
}
|
function _myEthBalance() private view returns(uint256) {
address self = address(this);
return self.balance;
}
| 38,844
|
26
|
// Show proof of stake, and mint a token. First an off-chain validation of staking must be made, and signed by the notary wallet. proof Signature made by the notary wallet, proving validity of stake. tokens The total number of tokens staked by wallet. tokenId The id of token to mint. tokenData The complete data for the minted token. verification A signature for the tokenId and tokenData, made by a wallet authorized by Identity /
|
function proofOfStakeAndMint (Verification calldata proof, uint256 tokens, uint256 tokenId, TokenData[] calldata tokenData, Verification calldata verification) public payable {
require(block.timestamp >= _tier2, "CXIP: too early to stake");
require(msg.value >= _tokenStakePrice, "CXIP: payment amount is too low");
require(!ISNUFFY500(_tokenContract).exists(tokenId), "CXIP: token snatched");
require(_exists(tokenId), "CXIP: token not for sale");
bytes memory encoded = abi.encodePacked(msg.sender, tokens);
require(Signature.Valid(
_notary,
proof.r,
proof.s,
proof.v,
encoded
), "CXIP: invalid signature");
if (!_reserveLifted) {
require(_purchasedTokens[msg.sender] < _maxPurchases, "CXIP: max allowance reached");
}
_purchasedTokens[msg.sender] = _purchasedTokens[msg.sender] + 1;
ISNUFFY500(_tokenContract).mint(0, tokenId, tokenData, _admin, verification, msg.sender);
_removeTokenFromAllTokensEnumeration(tokenId);
if (_autoWithdraw) {
_moveEth();
}
}
|
function proofOfStakeAndMint (Verification calldata proof, uint256 tokens, uint256 tokenId, TokenData[] calldata tokenData, Verification calldata verification) public payable {
require(block.timestamp >= _tier2, "CXIP: too early to stake");
require(msg.value >= _tokenStakePrice, "CXIP: payment amount is too low");
require(!ISNUFFY500(_tokenContract).exists(tokenId), "CXIP: token snatched");
require(_exists(tokenId), "CXIP: token not for sale");
bytes memory encoded = abi.encodePacked(msg.sender, tokens);
require(Signature.Valid(
_notary,
proof.r,
proof.s,
proof.v,
encoded
), "CXIP: invalid signature");
if (!_reserveLifted) {
require(_purchasedTokens[msg.sender] < _maxPurchases, "CXIP: max allowance reached");
}
_purchasedTokens[msg.sender] = _purchasedTokens[msg.sender] + 1;
ISNUFFY500(_tokenContract).mint(0, tokenId, tokenData, _admin, verification, msg.sender);
_removeTokenFromAllTokensEnumeration(tokenId);
if (_autoWithdraw) {
_moveEth();
}
}
| 28,312
|
49
|
// Get all NFT collection addresses supported by this contract
|
function getNftAddresses() external view returns (address[] memory) {
return nftAddresses;
}
|
function getNftAddresses() external view returns (address[] memory) {
return nftAddresses;
}
| 32,967
|
32
|
// 2) Mutiply our dollar value by that to get our value in wei:
|
uint256 valueInWei = oneUSDInWei * _value;
|
uint256 valueInWei = oneUSDInWei * _value;
| 3,272
|
66
|
// Allow now actual store to deposit
|
if (!Token(_tokenGet).approve(_store, totalValue)) {
revert();
}
|
if (!Token(_tokenGet).approve(_store, totalValue)) {
revert();
}
| 31,068
|
97
|
// Same as a standards-compliant ERC20.approve() that never reverts (returns false).Note that this makes an external call to the token./
|
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
|
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
| 6,215
|
11
|
// Function to claim a token _to The address that will receive the minted tokens./
|
function claim(
address _to
|
function claim(
address _to
| 11,162
|
12
|
// allows a user to withdraw their unlocked tokens amount the uint256 amount of native token being withdrawn /
|
function withdraw(uint256 amount) external override {
if(!shutdown){
require(_unlockTimes[msg.sender] < block.number, "Tokens not unlocked yet");
}
require(
_stakedBalances[msg.sender] >= amount,
"Insufficient staked balance"
);
require(totalStakedBalance >= amount, "insufficient funds in contract");
// Send unlocked tokens back to user
totalStakedBalance -= amount;
_stakedBalances[msg.sender] -= amount;
IERC20 tokenContract = IERC20(tokenAddress);
require(tokenContract.transfer(msg.sender, amount), "withdraw failed");
}
|
function withdraw(uint256 amount) external override {
if(!shutdown){
require(_unlockTimes[msg.sender] < block.number, "Tokens not unlocked yet");
}
require(
_stakedBalances[msg.sender] >= amount,
"Insufficient staked balance"
);
require(totalStakedBalance >= amount, "insufficient funds in contract");
// Send unlocked tokens back to user
totalStakedBalance -= amount;
_stakedBalances[msg.sender] -= amount;
IERC20 tokenContract = IERC20(tokenAddress);
require(tokenContract.transfer(msg.sender, amount), "withdraw failed");
}
| 25,593
|
83
|
// File: contracts/gluon/AppGovernance.sol
|
pragma solidity 0.7.1;
|
pragma solidity 0.7.1;
| 5,551
|
1
|
// `SignatureMint1155` is an ERC 1155 contract. It lets anyone mint NFTs by producing a mint request and a signature (produced by an account with MINTER_ROLE, signing the mint request). /
|
interface ISignatureMintERC1155 is IERC1155Upgradeable, ISignatureMintWithParams {
struct MintRequestWithParams {
BaseMintRequest baseMintRequest;
uint256 tokenId;
uint256 pricePerToken;
address currency;
bytes param;
}
/// @dev Emitted when tokens are minted.
event TokensMintedWithSignature(
address indexed signer,
address indexed mintedTo,
uint256 indexed tokenIdMinted,
MintRequestWithParams mintRequestWithParams
);
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokensMinted(address indexed mintedTo, uint256 indexed tokenIdMinted, string uri, uint256 quantityMinted);
/**
* @notice Lets an account with MINTER_ROLE mint an NFT.
*
* @param to The address to mint the NFT to.
* @param tokenId The tokenId of the NFTs to mint
* @param amount The number of copies of the NFT to mint.
*
*/
function mintTo(
address to,
uint256 tokenId,
uint256 amount
) external;
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequestWithParams calldata req, bytes calldata signature) external payable;
}
|
interface ISignatureMintERC1155 is IERC1155Upgradeable, ISignatureMintWithParams {
struct MintRequestWithParams {
BaseMintRequest baseMintRequest;
uint256 tokenId;
uint256 pricePerToken;
address currency;
bytes param;
}
/// @dev Emitted when tokens are minted.
event TokensMintedWithSignature(
address indexed signer,
address indexed mintedTo,
uint256 indexed tokenIdMinted,
MintRequestWithParams mintRequestWithParams
);
/// @dev Emitted when an account with MINTER_ROLE mints an NFT.
event TokensMinted(address indexed mintedTo, uint256 indexed tokenIdMinted, string uri, uint256 quantityMinted);
/**
* @notice Lets an account with MINTER_ROLE mint an NFT.
*
* @param to The address to mint the NFT to.
* @param tokenId The tokenId of the NFTs to mint
* @param amount The number of copies of the NFT to mint.
*
*/
function mintTo(
address to,
uint256 tokenId,
uint256 amount
) external;
/**
* @notice Mints an NFT according to the provided mint request.
*
* @param req The mint request.
* @param signature he signature produced by an account signing the mint request.
*/
function mintWithSignature(MintRequestWithParams calldata req, bytes calldata signature) external payable;
}
| 23,888
|
44
|
// Artwork
|
struct Artwork {
// owner
address owner;
// nftcontract address
address nftcontract;
// tokenId
uint256 tokenId;
ArtState status;
// time artwork start register or start auction
uint256 started;
// last vote time
uint256 update;
// weighted votes
// newpower = (update - start)/(now -start) * power + newvotes
uint256 power;
// the total number of votes the artwork had
uint256 votes;
// the minimum price owner can accept units in ETH
uint256 price;
}
|
struct Artwork {
// owner
address owner;
// nftcontract address
address nftcontract;
// tokenId
uint256 tokenId;
ArtState status;
// time artwork start register or start auction
uint256 started;
// last vote time
uint256 update;
// weighted votes
// newpower = (update - start)/(now -start) * power + newvotes
uint256 power;
// the total number of votes the artwork had
uint256 votes;
// the minimum price owner can accept units in ETH
uint256 price;
}
| 28,191
|
129
|
// Indexed
|
assetSymbol
);
return nonce;
|
assetSymbol
);
return nonce;
| 43,711
|
200
|
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once SUSHI is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
|
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 2;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
}));
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 2;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
}));
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
| 39,947
|
24
|
// Last block number when cumulative funding rate was recorded
|
uint256 private _cumuFundingRateBlock;
|
uint256 private _cumuFundingRateBlock;
| 48,718
|
42
|
// Allows merchant or Monetha to initiate exchange of funds by withdrawing funds to deposit address of the exchange /
|
function withdrawToExchange(address depositAccount, uint amount) external onlyMerchantOrMonetha whenNotPaused {
doWithdrawal(depositAccount, amount);
}
|
function withdrawToExchange(address depositAccount, uint amount) external onlyMerchantOrMonetha whenNotPaused {
doWithdrawal(depositAccount, amount);
}
| 61,345
|
147
|
// adapted from t-nicci solution https:ethereum.stackexchange.com/a/31470
|
function subString(string memory str, uint startIndex, uint endIndex) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
|
function subString(string memory str, uint startIndex, uint endIndex) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
| 39,709
|
42
|
// Constructor that sends msg.sender the initial token supply /
|
constructor(
address _wallet
|
constructor(
address _wallet
| 21,385
|
141
|
// Retrieves an object from the container. _index Index of the particular object to access.return 32 byte object value. /
|
function get(uint256 _index) external view returns (bytes32);
|
function get(uint256 _index) external view returns (bytes32);
| 18,377
|
28
|
// keccak256("ProxyAdmin");
|
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
|
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
| 30,700
|
10
|
// Returns boolean indicating if voting is enabled. _vault - The target vault.return true if voting is enabled, else returns false. /
|
function votingEnabled(address _vault) external view returns (bool);
|
function votingEnabled(address _vault) external view returns (bool);
| 27,175
|
12
|
// 0 TO 100 DRAGONS : 0.01 100 TO 1.000 DRAGONS : 0.1 1.000 TO 10.000 DRAGONS : 1 10.000 TO 100.000 DRAGONS : 10 >100.000 DRAGONS : 100
|
return _createRandomDragonEgg(msg.sender);
|
return _createRandomDragonEgg(msg.sender);
| 20,055
|
226
|
// activating contact events
|
function setPresaleLive(bool live) external onlyOwner {
presaleLive = live;
}
|
function setPresaleLive(bool live) external onlyOwner {
presaleLive = live;
}
| 40,636
|
223
|
// get vault short otoken if available
|
if (vaultDetails.hasShort) {
OtokenInterface short = OtokenInterface(_vault.shortOtokens[0]);
(
vaultDetails.shortCollateralAsset,
vaultDetails.shortUnderlyingAsset,
vaultDetails.shortStrikeAsset,
vaultDetails.shortStrikePrice,
vaultDetails.shortExpiryTimestamp,
vaultDetails.isShortPut
) = _getOtokenDetails(address(short));
|
if (vaultDetails.hasShort) {
OtokenInterface short = OtokenInterface(_vault.shortOtokens[0]);
(
vaultDetails.shortCollateralAsset,
vaultDetails.shortUnderlyingAsset,
vaultDetails.shortStrikeAsset,
vaultDetails.shortStrikePrice,
vaultDetails.shortExpiryTimestamp,
vaultDetails.isShortPut
) = _getOtokenDetails(address(short));
| 22,661
|
172
|
// get token amount which has a max price impact according to MAGIC_NUMBER for sells !!IMPORTANT!! => Any functions using return value from this MUST call `sync` on the pair before calling this function!
|
function getMaxSwappableAmount() public view returns (uint) {
uint tokensAvailable = IERC20(trustedRewardTokenAddress).balanceOf(trustedDepositTokenAddress);
uint maxSwappableAmount = tokensAvailable.mul(MAGIC_NUMBER).div(1e18);
return maxSwappableAmount;
}
|
function getMaxSwappableAmount() public view returns (uint) {
uint tokensAvailable = IERC20(trustedRewardTokenAddress).balanceOf(trustedDepositTokenAddress);
uint maxSwappableAmount = tokensAvailable.mul(MAGIC_NUMBER).div(1e18);
return maxSwappableAmount;
}
| 57,550
|
10
|
// Convert WETH to ETH
|
IWETH(WETH).withdraw(decoded.repayAmount);
|
IWETH(WETH).withdraw(decoded.repayAmount);
| 13,395
|
42
|
// Settings in RP which the DAO will have full control over This settings contract enables storage using setting paths with namespaces, rather than explicit set methods
|
abstract contract RocketDAONodeTrustedSettings is RocketBase, RocketDAONodeTrustedSettingsInterface {
// The namespace for a particular group of settings
bytes32 settingNameSpace;
// Only allow updating from the DAO proposals contract
modifier onlyDAONodeTrustedProposal() {
// If this contract has been initialised, only allow access from the proposals contract
if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAONodeTrustedProposals") == msg.sender, "Only DAO Node Trusted Proposals contract can update a setting");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) {
// Apply the setting namespace
settingNameSpace = keccak256(abi.encodePacked("dao.trustednodes.setting.", _settingNameSpace));
}
/*** Uints ****************/
// A general method to return any setting given the setting path is correct, only accepts uints
function getSettingUint(string memory _settingPath) public view override returns (uint256) {
return getUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a Uint setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingUint(string memory _settingPath, uint256 _value) virtual public override onlyDAONodeTrustedProposal {
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Bools ****************/
// A general method to return any setting given the setting path is correct, only accepts bools
function getSettingBool(string memory _settingPath) public view override returns (bool) {
return getBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingBool(string memory _settingPath, bool _value) virtual public override onlyDAONodeTrustedProposal {
// Update setting now
setBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
}
|
abstract contract RocketDAONodeTrustedSettings is RocketBase, RocketDAONodeTrustedSettingsInterface {
// The namespace for a particular group of settings
bytes32 settingNameSpace;
// Only allow updating from the DAO proposals contract
modifier onlyDAONodeTrustedProposal() {
// If this contract has been initialised, only allow access from the proposals contract
if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAONodeTrustedProposals") == msg.sender, "Only DAO Node Trusted Proposals contract can update a setting");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) {
// Apply the setting namespace
settingNameSpace = keccak256(abi.encodePacked("dao.trustednodes.setting.", _settingNameSpace));
}
/*** Uints ****************/
// A general method to return any setting given the setting path is correct, only accepts uints
function getSettingUint(string memory _settingPath) public view override returns (uint256) {
return getUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a Uint setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingUint(string memory _settingPath, uint256 _value) virtual public override onlyDAONodeTrustedProposal {
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Bools ****************/
// A general method to return any setting given the setting path is correct, only accepts bools
function getSettingBool(string memory _settingPath) public view override returns (bool) {
return getBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingBool(string memory _settingPath, bool _value) virtual public override onlyDAONodeTrustedProposal {
// Update setting now
setBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
}
| 29,830
|
9
|
// Returns the bin step of the Liquidity Book Pair The bin step is the increase in price between two consecutive bins, in basis points.For example, a bin step of 1 means that the price of the next bin is 0.01% higher than the price of the previous bin.return binStep The bin step of the Liquidity Book Pair, in 10_000th /
|
function getBinStep() external pure override returns (uint16) {
return _binStep();
}
|
function getBinStep() external pure override returns (uint16) {
return _binStep();
}
| 12,843
|
161
|
// Fail if borrow not allowed // Verify market's block number equals current block number // Fail gracefully if protocol has insufficient underlying cash //We calculate the new borrower and total borrow balances, failing on overflow: accountBorrowsNew = accountBorrows + borrowAmount totalBorrowsNew = totalBorrows + borrowAmount /
|
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
|
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
| 10,699
|
621
|
// Address of the known and trusted Margin contract on the blockchain
|
address public DYDX_MARGIN;
|
address public DYDX_MARGIN;
| 72,432
|
0
|
// Gets the tokenId of the next NFT minted. /
|
function getNextTokenId() public view returns (uint256) {
return nextTokenId;
}
|
function getNextTokenId() public view returns (uint256) {
return nextTokenId;
}
| 24,953
|
583
|
// Set joetroller's oracle to newOracle
|
oracle = newOracle;
|
oracle = newOracle;
| 33,364
|
0
|
// ==================================================================================================================== STRUCTS and ENUMS===================================================================================================================== / Configuation options for this primary sale module.
|
struct PublicMintConfig {
uint256 phaseMaxSupply;
uint256 phaseStart;
uint256 phaseEnd;
uint256 metadropPerMintFee;
uint256 metadropPrimaryShareInBasisPoints;
uint256 publicPrice;
uint256 maxPublicQuantity;
bool reservedAllocationPhase;
}
|
struct PublicMintConfig {
uint256 phaseMaxSupply;
uint256 phaseStart;
uint256 phaseEnd;
uint256 metadropPerMintFee;
uint256 metadropPrimaryShareInBasisPoints;
uint256 publicPrice;
uint256 maxPublicQuantity;
bool reservedAllocationPhase;
}
| 40,970
|
2
|
// balances in the lock-ups
|
mapping(address => uint256) public balances;
|
mapping(address => uint256) public balances;
| 5,764
|
8
|
// Standard SafeMath, stripped down to just add/sub/mul/div /
|
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
|
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
| 7,229
|
99
|
// returnaddress: The address of the creator of this project./
|
function creator() external view returns(address);
|
function creator() external view returns(address);
| 1,670
|
371
|
// Events
|
event SaleActivation(bool isActive);
event HolderSaleActivation(bool isActive);
|
event SaleActivation(bool isActive);
event HolderSaleActivation(bool isActive);
| 4,688
|
49
|
// Returns an address of a given node. /
|
function getNodeAddress(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (address)
|
function getNodeAddress(uint nodeIndex)
external
view
override
checkNodeExists(nodeIndex)
returns (address)
| 9,982
|
177
|
// Function that lets a seller get their deposited day tokens (minBalanceToSell) back, if no buyer turns up. Allowed only after expiryBlockNumber Throws if any other state other than EXPIRED/
|
function refundFailedAuctionAmount() onlyContributor(idOf[msg.sender]) public returns(bool){
uint id = idOf[msg.sender];
if(block.number > contributors[id].expiryBlockNumber && contributors[id].status == sellingStatus.ONSALE)
{
contributors[id].status = sellingStatus.EXPIRED;
}
require(contributors[id].status == sellingStatus.EXPIRED);
// reset selling status
contributors[id].status = sellingStatus.NOTONSALE;
balances[this] = safeSub(balances[this], minBalanceToSell);
// update balance of seller address before refunding
updateBalanceOf(id);
balances[msg.sender] = safeAdd(balances[msg.sender], minBalanceToSell);
contributors[id].minPriceInDay = 0;
contributors[id].expiryBlockNumber = 0;
Transfer(this, msg.sender, minBalanceToSell);
return true;
}
|
function refundFailedAuctionAmount() onlyContributor(idOf[msg.sender]) public returns(bool){
uint id = idOf[msg.sender];
if(block.number > contributors[id].expiryBlockNumber && contributors[id].status == sellingStatus.ONSALE)
{
contributors[id].status = sellingStatus.EXPIRED;
}
require(contributors[id].status == sellingStatus.EXPIRED);
// reset selling status
contributors[id].status = sellingStatus.NOTONSALE;
balances[this] = safeSub(balances[this], minBalanceToSell);
// update balance of seller address before refunding
updateBalanceOf(id);
balances[msg.sender] = safeAdd(balances[msg.sender], minBalanceToSell);
contributors[id].minPriceInDay = 0;
contributors[id].expiryBlockNumber = 0;
Transfer(this, msg.sender, minBalanceToSell);
return true;
}
| 14,703
|
36
|
// Stores the oracle address to use when looking for the price of a given token/oracles are keyed by the pair of underlyingToken-priceToken, so for a BTCUSD oracle/ returning a price of $14_000, the pair would be the addresses corresponding to WBTC and USDC
|
mapping(address => mapping(address => address)) internal oracles;
|
mapping(address => mapping(address => address)) internal oracles;
| 32,505
|
104
|
// Update dividend trackers
|
payoutsTo_[_customerAddress] -= (int256) (profitPerDivToken * _amountOfDivTokens);
payoutsTo_[_toAddress] += (int256) (profitPerDivToken * _amountOfDivTokens);
gamePayoutsTo_[_customerAddress] -= (int256) (gameProfitPerDivToken * _amountOfDivTokens);
gamePayoutsTo_[_toAddress] += (int256) (gameProfitPerDivToken * _amountOfDivTokens);
|
payoutsTo_[_customerAddress] -= (int256) (profitPerDivToken * _amountOfDivTokens);
payoutsTo_[_toAddress] += (int256) (profitPerDivToken * _amountOfDivTokens);
gamePayoutsTo_[_customerAddress] -= (int256) (gameProfitPerDivToken * _amountOfDivTokens);
gamePayoutsTo_[_toAddress] += (int256) (gameProfitPerDivToken * _amountOfDivTokens);
| 36,386
|
48
|
// Read /
|
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
|
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
| 25,874
|
78
|
// retorna o saldo remanescente permitidoallowance(_owner, from);
|
transferFrom(from, to, valor);
|
transferFrom(from, to, valor);
| 35,009
|
63
|
// Perform call, placing first word of return data in scratch space.
|
success := call(gas(), conduit, 0, callDataOffset, callDataSize, 0, OneWord)
|
success := call(gas(), conduit, 0, callDataOffset, callDataSize, 0, OneWord)
| 17,062
|
13
|
// TODO: ADD a _birthNewDragon here
|
return
createNewDragon(
_motherGender,
_fatherColor,
_motherGeneration,
_motherId,
_fatherId,
_motherGenes,
_motherGenes,
_fatherGenes,
|
return
createNewDragon(
_motherGender,
_fatherColor,
_motherGeneration,
_motherId,
_fatherId,
_motherGenes,
_motherGenes,
_fatherGenes,
| 726
|
36
|
// May enable/disable transfers on Neumark
|
bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19;
|
bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19;
| 18,739
|
6
|
// Campaign configuration
|
mapping(uint256 => CampaignConfig) public campaignConfigs;
|
mapping(uint256 => CampaignConfig) public campaignConfigs;
| 44,563
|
348
|
// the fixed interest accrued on this swap
|
uint256 protocol0VariableInterestAccrued = _calculateVariableInterestAccrued(_swap.notional, protocol0, _swap.underlierProtocol0BorrowIndex);
|
uint256 protocol0VariableInterestAccrued = _calculateVariableInterestAccrued(_swap.notional, protocol0, _swap.underlierProtocol0BorrowIndex);
| 75,782
|
23
|
// encode a uint112 as a UQ112x112
|
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
|
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
| 10,581
|
246
|
// Cap at newSupply
|
newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable;
|
newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable;
| 4,815
|
16
|
// == Governor
|
function governor() external override view returns (address) {
return _governor;
}
|
function governor() external override view returns (address) {
return _governor;
}
| 2,215
|
26
|
// Only allow access to strategist or owner /
|
function _onlyStrategistOrOwner() internal view {
require(hasRole(STRATEGIST, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized");
}
|
function _onlyStrategistOrOwner() internal view {
require(hasRole(STRATEGIST, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized");
}
| 17,190
|
165
|
// Units up for cooldown
|
uint88 cooldownUnits;
|
uint88 cooldownUnits;
| 23,759
|
84
|
// add y^08(20! / 08!)
|
z = (z * y) / FIXED_1;
res += z * 0x00000618fee9f800;
|
z = (z * y) / FIXED_1;
res += z * 0x00000618fee9f800;
| 31,297
|
34
|
// Input validation
|
require(tab > 0, "Clipper/zero-tab");
require(lot > 0, "Clipper/zero-lot");
require(usr != address(0), "Clipper/zero-usr");
id = ++kicks;
require(id > 0, "Clipper/overflow");
active.push(id);
sales[id].pos = active.length - 1;
|
require(tab > 0, "Clipper/zero-tab");
require(lot > 0, "Clipper/zero-lot");
require(usr != address(0), "Clipper/zero-usr");
id = ++kicks;
require(id > 0, "Clipper/overflow");
active.push(id);
sales[id].pos = active.length - 1;
| 8,631
|
0
|
// Iterable map of (address => Proposal) index = ordinals[a]-1 keys[index].maker = a
|
using map for ProposalMap;
|
using map for ProposalMap;
| 27,465
|
5
|
// Allows only the (immutable) owner to call a function.
|
modifier onlyOwner() virtual {
if (msg.sender != owner) {
LibOwnableRichErrorsV06.OnlyOwnerError(
msg.sender,
owner
).rrevert();
}
_;
}
|
modifier onlyOwner() virtual {
if (msg.sender != owner) {
LibOwnableRichErrorsV06.OnlyOwnerError(
msg.sender,
owner
).rrevert();
}
_;
}
| 47,880
|
5,740
|
// 2871
|
entry "gonadectomized" : ENG_ADJECTIVE
|
entry "gonadectomized" : ENG_ADJECTIVE
| 19,483
|
12
|
// ------------------------------------------------------------------------ Implementation of basic token interface ------------------------------------------------------------------------
|
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping(address => uint256) public balances;
// ------------------------------------------------------------------------
// Get balance of user
// ------------------------------------------------------------------------
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer tokens
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// ------------------------------------------------------------------------
// Create tokens by adding to total supply and crediting the admin/owner
// ------------------------------------------------------------------------
function mintToken(address _target, uint256 _mintedAmount) public returns(bool){
balances[_target] = balances[_target].add(_mintedAmount);
totalSupply = totalSupply.add(_mintedAmount);
emit Minted(_target, _mintedAmount);
emit Transfer(address(0), address(this), _mintedAmount);
emit Transfer(address(this), _target, _mintedAmount);
return true;
}
// ------------------------------------------------------------------------
// Burn token by sending to to burn address & removing it from total supply
// ------------------------------------------------------------------------
function burn(uint256 _burnAmount) public {
address burner = msg.sender;
balances[burner] = balances[burner].sub(_burnAmount);
totalSupply = totalSupply.sub(_burnAmount);
emit Burned(burner, _burnAmount);
emit Transfer(burner, burnAddress, _burnAmount);
}
}
|
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping(address => uint256) public balances;
// ------------------------------------------------------------------------
// Get balance of user
// ------------------------------------------------------------------------
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer tokens
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// ------------------------------------------------------------------------
// Create tokens by adding to total supply and crediting the admin/owner
// ------------------------------------------------------------------------
function mintToken(address _target, uint256 _mintedAmount) public returns(bool){
balances[_target] = balances[_target].add(_mintedAmount);
totalSupply = totalSupply.add(_mintedAmount);
emit Minted(_target, _mintedAmount);
emit Transfer(address(0), address(this), _mintedAmount);
emit Transfer(address(this), _target, _mintedAmount);
return true;
}
// ------------------------------------------------------------------------
// Burn token by sending to to burn address & removing it from total supply
// ------------------------------------------------------------------------
function burn(uint256 _burnAmount) public {
address burner = msg.sender;
balances[burner] = balances[burner].sub(_burnAmount);
totalSupply = totalSupply.sub(_burnAmount);
emit Burned(burner, _burnAmount);
emit Transfer(burner, burnAddress, _burnAmount);
}
}
| 17,135
|
7
|
// Fixed window oracle that recomputes the average price for the entire period once every period/Oracle/note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
|
contract Oracle is Debouncable, Timeboundable, IOracle, ReentrancyGuard {
using FixedPoint for *;
IUniswapV2Pair public immutable override pair;
address public immutable override token0;
address public immutable override token1;
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
/// Creates an Oracle
/// @param _factory UniswapV2 factory address.
/// @param _tokenA 1st token address.
/// @param _tokenB 2nd token address.
/// @param _period Price average period in seconds.
/// @param _start Start (block timestamp).
constructor(
address _factory,
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _start
) public Debouncable(_period) Timeboundable(_start, 0) {
IUniswapV2Pair _pair =
IUniswapV2Pair(
UniswapV2Library.pairFor(_factory, _tokenA, _tokenB)
);
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(
reserve0 != 0 && reserve1 != 0,
"Oracle: No reserves in the uniswap pool"
); // ensure that there's liquidity in the pair
}
/// Updates oracle price
/// @dev Works only once in a period, other times reverts
function update()
external
override
debounce()
inTimeBounds()
nonReentrant()
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint256 timeElapsed = block.timestamp - lastCalled;
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(
uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)
);
price1Average = FixedPoint.uq112x112(
uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)
);
emit Updated(
price0CumulativeLast,
price0Cumulative,
price1CumulativeLast,
price1Cumulative
);
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
/// Get the price of token.
/// @param token The address of one of two tokens (the one to get the price for)
/// @param amountIn The amount of token to estimate
/// @return amountOut The amount of other token equivalent
/// @dev This will always return 0 before update has been called successfully for the first time.
function consult(address token, uint256 amountIn)
external
view
override
inTimeBounds()
returns (uint256 amountOut)
{
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, "Oracle: Invalid token address");
amountOut = price1Average.mul(amountIn).decode144();
}
}
event Updated(
uint256 price0CumulativeBefore,
uint256 price0CumulativeAfter,
uint256 price1CumulativeBefore,
uint256 price1CumulativeAfter
);
}
|
contract Oracle is Debouncable, Timeboundable, IOracle, ReentrancyGuard {
using FixedPoint for *;
IUniswapV2Pair public immutable override pair;
address public immutable override token0;
address public immutable override token1;
uint256 public price0CumulativeLast;
uint256 public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
/// Creates an Oracle
/// @param _factory UniswapV2 factory address.
/// @param _tokenA 1st token address.
/// @param _tokenB 2nd token address.
/// @param _period Price average period in seconds.
/// @param _start Start (block timestamp).
constructor(
address _factory,
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _start
) public Debouncable(_period) Timeboundable(_start, 0) {
IUniswapV2Pair _pair =
IUniswapV2Pair(
UniswapV2Library.pairFor(_factory, _tokenA, _tokenB)
);
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(
reserve0 != 0 && reserve1 != 0,
"Oracle: No reserves in the uniswap pool"
); // ensure that there's liquidity in the pair
}
/// Updates oracle price
/// @dev Works only once in a period, other times reverts
function update()
external
override
debounce()
inTimeBounds()
nonReentrant()
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint256 timeElapsed = block.timestamp - lastCalled;
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(
uint224((price0Cumulative - price0CumulativeLast) / timeElapsed)
);
price1Average = FixedPoint.uq112x112(
uint224((price1Cumulative - price1CumulativeLast) / timeElapsed)
);
emit Updated(
price0CumulativeLast,
price0Cumulative,
price1CumulativeLast,
price1Cumulative
);
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
/// Get the price of token.
/// @param token The address of one of two tokens (the one to get the price for)
/// @param amountIn The amount of token to estimate
/// @return amountOut The amount of other token equivalent
/// @dev This will always return 0 before update has been called successfully for the first time.
function consult(address token, uint256 amountIn)
external
view
override
inTimeBounds()
returns (uint256 amountOut)
{
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, "Oracle: Invalid token address");
amountOut = price1Average.mul(amountIn).decode144();
}
}
event Updated(
uint256 price0CumulativeBefore,
uint256 price0CumulativeAfter,
uint256 price1CumulativeBefore,
uint256 price1CumulativeAfter
);
}
| 86,088
|
22
|
// Temporarily leave the set of collator candidates without unbonding/ @custom:selector a6485ccd
|
function goOffline() external;
|
function goOffline() external;
| 32,311
|
96
|
// Allows an owner to stop or countinue deposits./_isActive Whether the deposits are allowed.
|
function setActive(bool _isActive) public onlyOwner {
isActive = _isActive;
}
|
function setActive(bool _isActive) public onlyOwner {
isActive = _isActive;
}
| 21,264
|
82
|
// Math: since feeBasisPoints is <= BASIS_POINTS_DEN, this will never underflow.
|
_transferCurrency(beneficiary, reserve - fee);
_transferCurrency(feeCollector, fee);
|
_transferCurrency(beneficiary, reserve - fee);
_transferCurrency(feeCollector, fee);
| 4,227
|
40
|
// Seed User List
|
function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner {
for (uint i=0; i<_userAddrs.length; i++) {
setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount);
if (_transferToken) {
xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount);
}
}
}
|
function seedUserList(address[] memory _userAddrs, UserInfo[] memory _userList, bool _transferToken) public onlyOwner {
for (uint i=0; i<_userAddrs.length; i++) {
setUserInfo(_userAddrs[i], _userList[i].vestingIndex, _userList[i].depositedAmount, _userList[i].purchasedAmount, _userList[i].withdrawnAmount);
if (_transferToken) {
xGovToken.safeTransfer(_userAddrs[i], _userList[i].purchasedAmount);
}
}
}
| 66,027
|
12
|
// Minted counter for current Token and totalSupply()
|
Counters.Counter private tokenCounter;
|
Counters.Counter private tokenCounter;
| 17,568
|
5
|
// Add an allowed administrator_allowedAdministrator address/
|
function addAllowedModifier(address _allowedAdministrator)
public
onlyOwner
nonEmptyAddress(_allowedAdministrator)
|
function addAllowedModifier(address _allowedAdministrator)
public
onlyOwner
nonEmptyAddress(_allowedAdministrator)
| 31,994
|
8
|
// keccak256("MultiSigTransaction(address destination,uint256 value,bytes data,uint256 nonce,address txOrigin)")
|
bytes32 constant TXTYPE_HASH = 0x81336c6b66e18c614f29c0c96edcbcbc5f8e9221f35377412f0ea5d6f428918e;
|
bytes32 constant TXTYPE_HASH = 0x81336c6b66e18c614f29c0c96edcbcbc5f8e9221f35377412f0ea5d6f428918e;
| 4,913
|
43
|
// Aggregating total wETH debt from protocols
|
totalDebt_ =
assets_.aaveV2.wETH +
assets_.aaveV3.wETH +
assets_.compoundV3.wETH +
assets_.morphoAaveV2.wETH +
assets_.euler.wETH;
netAssets_ = totalAssets_ - totalDebt_ - revenue; // Assuming wETH 1:1 stETH
aggregatedRatio_ = totalAssets_ == 0
? 0
|
totalDebt_ =
assets_.aaveV2.wETH +
assets_.aaveV3.wETH +
assets_.compoundV3.wETH +
assets_.morphoAaveV2.wETH +
assets_.euler.wETH;
netAssets_ = totalAssets_ - totalDebt_ - revenue; // Assuming wETH 1:1 stETH
aggregatedRatio_ = totalAssets_ == 0
? 0
| 12,807
|
3
|
// duration of a slice period for the vesting in seconds.
|
uint256 public immutable vestingSlicePeriod;
|
uint256 public immutable vestingSlicePeriod;
| 6,322
|
31
|
// Royalty /
|
function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {
super.setApprovalForAll(operator, approved);
}
|
function setApprovalForAll(address operator, bool approved) public override onlyAllowedOperatorApproval(operator) {
super.setApprovalForAll(operator, approved);
}
| 15,296
|
25
|
// EVM assembler of runtime portion of child contract: ;; Pseudocode: if (msg.sender != 0x000000000000cb2d80a37898be43579c7b616844) { throw; } ;; suicide(msg.sender) PUSH14 0xcb2d80a37898be43579c7b616856 ;; hardcoded address of this contract CALLER XOR JUMP JUMPDEST CALLER SELFDESTRUCT Or in binary: 6dcb2d80a37898be43579c7b6168563318565b33ff Since the binary is so short (21 bytes), we can get away with a very simple initcode: PUSH21 0x6dcb2d80a37898be43579c7b6168573318565b33ff PUSH1 0 MSTORE ;; at this point, memory locations mem[10] through;; mem[30] contain the runtime portion of the child;; contract. all that's left to do is to RETURN this;; chunk of memory. PUSH1 21 ;; length PUSH1 11 ;; offset RETURN Or in binary:
|
let end := add(offset, value)
mstore(callvalue(), 0x746dcb2d80a37898be43579c7b6168563318565b33ff6000526015600bf30000)
|
let end := add(offset, value)
mstore(callvalue(), 0x746dcb2d80a37898be43579c7b6168563318565b33ff6000526015600bf30000)
| 17,177
|
14
|
// Proof of work is called by the miner when they submit the solution (proof of work and value)_nonce uint submitted by miner_requestId the apiId being mined_value of api query/
|
function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value)
public
|
function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId, uint256 _value)
public
| 13,092
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.