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
|
|---|---|---|---|---|
268
|
// ========== SETTERS ========== / These functions are useful for setting parameters of the strategy that may need to be adjusted. Set optimal token to sell harvested funds for depositing to Curve. Default is EURS, but can be set to EURT or agEUR as needed by strategist or governance.
|
function setOptimal(uint256 _optimal) external onlyAuthorized {
if (_optimal == 0) {
middleStable = address(usdc);
targetStable = address(ageur);
optimal = 0;
} else if (_optimal == 1) {
middleStable = address(usdt);
targetStable = address(eurt);
optimal = 1;
} else if (_optimal == 2) {
middleStable = address(usdc);
targetStable = address(eurs);
optimal = 2;
} else {
revert("incorrect token");
}
}
|
function setOptimal(uint256 _optimal) external onlyAuthorized {
if (_optimal == 0) {
middleStable = address(usdc);
targetStable = address(ageur);
optimal = 0;
} else if (_optimal == 1) {
middleStable = address(usdt);
targetStable = address(eurt);
optimal = 1;
} else if (_optimal == 2) {
middleStable = address(usdc);
targetStable = address(eurs);
optimal = 2;
} else {
revert("incorrect token");
}
}
| 37,514
|
14
|
// Avoid balanceOf to not compute an unnecesary require
|
uint256 landsSize;
uint256 balance = ownedTokensCount[_owner];
for (uint256 i; i < balance; i++) {
uint256 estateId = ownedTokens[_owner][i];
landsSize += estateLandIds[estateId].length;
}
|
uint256 landsSize;
uint256 balance = ownedTokensCount[_owner];
for (uint256 i; i < balance; i++) {
uint256 estateId = ownedTokens[_owner][i];
landsSize += estateLandIds[estateId].length;
}
| 36,584
|
14
|
// Check if the mintpass has been used to mint an ERC-1155
|
function checkIfRedeemed(address _contractAddress, uint256 _tokenId) view public returns(bool) {
return usedToken[_contractAddress][_tokenId];
}
|
function checkIfRedeemed(address _contractAddress, uint256 _tokenId) view public returns(bool) {
return usedToken[_contractAddress][_tokenId];
}
| 36,530
|
165
|
// Compound tokens to Arc pool.
|
function compound(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(
address(pool.lpToken) == address(arc),
"compound: not able to compound"
);
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accArcPerShare).div(1e12).sub(
user.rewardDebt
);
safeArcTransferFrom(rewardHolder, address(this), pending);
user.amount = user.amount.add(pending);
user.rewardDebt = user.amount.mul(pool.accArcPerShare).div(1e12);
emit Compound(msg.sender, _pid, pending);
}
|
function compound(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(
address(pool.lpToken) == address(arc),
"compound: not able to compound"
);
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accArcPerShare).div(1e12).sub(
user.rewardDebt
);
safeArcTransferFrom(rewardHolder, address(this), pending);
user.amount = user.amount.add(pending);
user.rewardDebt = user.amount.mul(pool.accArcPerShare).div(1e12);
emit Compound(msg.sender, _pid, pending);
}
| 53,656
|
2
|
// Comp version of the {getPastVotes} accessor, with `uint96` return type. /
|
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) {
return SafeCast.toUint96(getPastVotes(account, blockNumber));
}
|
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) {
return SafeCast.toUint96(getPastVotes(account, blockNumber));
}
| 21,742
|
156
|
// reward tokens distributed based on bonus percentage and amount staked
|
earned = earned + (pool.bonusPercentageNumerator * _periodStaked) / pool.bonusPercentageDenominator;
|
earned = earned + (pool.bonusPercentageNumerator * _periodStaked) / pool.bonusPercentageDenominator;
| 17,185
|
191
|
// Returns the base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI, or to the token ID if no specific URI is set for that token ID./
|
function baseURI() public view returns (string memory) {
return _baseURI;
}
|
function baseURI() public view returns (string memory) {
return _baseURI;
}
| 2,591
|
16
|
// Checks whether or not an ERC20 token has used its free trial of 100 drops. This is a constant function which does not alter the state of the contract and therefore does not require any gas or a signature to be executed._addressOfToken The address of the token being queried.return true if the token being queried has not used its 100 first free trial drops, falseotherwise./
|
function tokenHasFreeTrial(address _addressOfToken) public view returns(bool) {
return trialDrops[_addressOfToken] < maxTrialDrops;
}
|
function tokenHasFreeTrial(address _addressOfToken) public view returns(bool) {
return trialDrops[_addressOfToken] < maxTrialDrops;
}
| 85,643
|
14
|
// Total allocation points. Must be the sum of all allocation points in all pools.
|
uint256 public totalAllocPoint = 0;
|
uint256 public totalAllocPoint = 0;
| 15,473
|
100
|
// Player has won a two gold pyramid prize!
|
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133), 100);
category = 18;
emit TwoGoldPyramids(target, spin.blockn);
|
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 133), 100);
category = 18;
emit TwoGoldPyramids(target, spin.blockn);
| 69,998
|
55
|
// From this point forward, _sharesPerFragment is taken as the source of truth. We recalculate a new _totalSupply to be in agreement with the _sharesPerFragment conversion rate. This means our applied supplyDelta can deviate from the requested supplyDelta, but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_SHARES - _totalSupply). In the case of _totalSupply <= MAX_UINT64 (our current supply cap), this deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is ever increased, it must be re-included. NB: SilverForth will likely never reach the total supply cap as the total supply of Silver
|
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
|
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
| 32,742
|
31
|
// withdrawing Ether
|
if (address(token) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
if (address(this).balance > 0){
tokenBalance = address(this).balance;
payable(msg.sender).transfer(address(this).balance);
}
|
if (address(token) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
if (address(this).balance > 0){
tokenBalance = address(this).balance;
payable(msg.sender).transfer(address(this).balance);
}
| 16,011
|
87
|
// so that we can easily check that we don't add duplicates to our array
|
mapping (address => bool) public tokensTraded;
|
mapping (address => bool) public tokensTraded;
| 11,921
|
35
|
// This contract should not have funds at the end of each tx (except for stkAAVE), this method is just for leftovers/Emergency method/_token address of the token to transfer/value amount of `_token` to transfer/_to receiver address
|
function transferToken(
address _token,
uint256 value,
address _to
) external onlyOwner nonReentrant {
IERC20Detailed(_token).safeTransfer(_to, value);
}
|
function transferToken(
address _token,
uint256 value,
address _to
) external onlyOwner nonReentrant {
IERC20Detailed(_token).safeTransfer(_to, value);
}
| 14,919
|
252
|
// Add additional assets. Duplicates of trackedAssets are ignored.
|
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
|
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
| 18,589
|
32
|
// Revert with an error if supplied signed feeBps is greater than the maximum specified, or less than the minimum. /
|
error InvalidSignedFeeBps(uint256 got, uint256 minimumOrMaximum);
|
error InvalidSignedFeeBps(uint256 got, uint256 minimumOrMaximum);
| 12,718
|
8
|
// Also stakes in vault, no fees
|
require(uint(msg.value) > MIN_AMT, "INPUT_TOO_LOW");
(address vaultWant,) = IVaultChef(vaultChefAddress).poolInfo(vaultPid);
require(vaultWant == _to, "Wrong wantAddress for vault pid");
|
require(uint(msg.value) > MIN_AMT, "INPUT_TOO_LOW");
(address vaultWant,) = IVaultChef(vaultChefAddress).poolInfo(vaultPid);
require(vaultWant == _to, "Wrong wantAddress for vault pid");
| 18,753
|
62
|
// Removes a liquidity gauge from gauge controller. Only governance can remove a plus token. _gauge The liquidity gauge to remove from gauge controller. /
|
function removeGauge(address _gauge) external onlyGovernance {
require(_gauge != address(0x0), "gauge not set");
require(gaugeData[_gauge].isSupported, "gauge not exist");
uint256 _gaugeSize = gauges.length;
uint256 _gaugeIndex = _gaugeSize;
for (uint256 i = 0; i < _gaugeSize; i++) {
if (gauges[i] == _gauge) {
_gaugeIndex = i;
break;
}
}
// We must have found the gauge!
assert(_gaugeIndex < _gaugeSize);
gauges[_gaugeIndex] = gauges[_gaugeSize - 1];
gauges.pop();
delete gaugeData[_gauge];
// Need to checkpoint with the token removed!
checkpoint();
emit GaugeRemoved(_gauge);
}
|
function removeGauge(address _gauge) external onlyGovernance {
require(_gauge != address(0x0), "gauge not set");
require(gaugeData[_gauge].isSupported, "gauge not exist");
uint256 _gaugeSize = gauges.length;
uint256 _gaugeIndex = _gaugeSize;
for (uint256 i = 0; i < _gaugeSize; i++) {
if (gauges[i] == _gauge) {
_gaugeIndex = i;
break;
}
}
// We must have found the gauge!
assert(_gaugeIndex < _gaugeSize);
gauges[_gaugeIndex] = gauges[_gaugeSize - 1];
gauges.pop();
delete gaugeData[_gauge];
// Need to checkpoint with the token removed!
checkpoint();
emit GaugeRemoved(_gauge);
}
| 16,636
|
69
|
// If the delegator wants to reduce withdrawal value, add them to delegator list of the pool if it hasn't already done
|
_addPoolDelegator(poolId, staker);
|
_addPoolDelegator(poolId, staker);
| 22,645
|
287
|
// sdMAVOft/StakeDAO/A token that represents the Token deposited by a user into the Depositor/Minting & Burning was modified to be used by the operator
|
contract sdMAV is OFT {
error ONLY_OPERATOR();
address public operator;
constructor(string memory _name, string memory _symbol, address _lzEndpoint) OFT(_name, _symbol, _lzEndpoint) {
operator = msg.sender;
}
|
contract sdMAV is OFT {
error ONLY_OPERATOR();
address public operator;
constructor(string memory _name, string memory _symbol, address _lzEndpoint) OFT(_name, _symbol, _lzEndpoint) {
operator = msg.sender;
}
| 2,817
|
66
|
// Ensure new sanitizer is not null.
|
if (newSanitizer == address(0)) {
revert SanitizerCannotBeNullAddress();
}
|
if (newSanitizer == address(0)) {
revert SanitizerCannotBeNullAddress();
}
| 19,330
|
38
|
// - Function that allows foreground contract to spend (burn) the tokens. _from - Account to withdraw from. _value - Number of tokens to withdraw.return - A boolean that indicates if the operation was successful. /
|
function spend(address _from, uint256 _value) public returns (bool) {
require(_value > 0);
if (balances[_from] < _value || allowed[_from][msg.sender] < _value) {
return false;
}
|
function spend(address _from, uint256 _value) public returns (bool) {
require(_value > 0);
if (balances[_from] < _value || allowed[_from][msg.sender] < _value) {
return false;
}
| 41,278
|
7
|
// _amountForPoints amount of ETH to boost earnings of {loyalty, tier} points/_snapshotEthAmount exact balance that the user has in the merkle snapshot/_points EAP points that the user has in the merkle snapshot/_merkleProof array of hashes forming the merkle proof for the user
|
function wrapEthForEap(
uint256 _amount,
uint256 _amountForPoints,
uint256 _snapshotEthAmount,
uint256 _points,
bytes32[] calldata _merkleProof
) external payable whenNotPaused returns (uint256) {
if (_points == 0 || msg.value < _snapshotEthAmount || msg.value > _snapshotEthAmount * 2 || msg.value != _amount + _amountForPoints) revert InvalidEAPRollover();
membershipNFT.processDepositFromEapUser(msg.sender, _snapshotEthAmount, _points, _merkleProof);
|
function wrapEthForEap(
uint256 _amount,
uint256 _amountForPoints,
uint256 _snapshotEthAmount,
uint256 _points,
bytes32[] calldata _merkleProof
) external payable whenNotPaused returns (uint256) {
if (_points == 0 || msg.value < _snapshotEthAmount || msg.value > _snapshotEthAmount * 2 || msg.value != _amount + _amountForPoints) revert InvalidEAPRollover();
membershipNFT.processDepositFromEapUser(msg.sender, _snapshotEthAmount, _points, _merkleProof);
| 27,413
|
67
|
// Staking/Manages stake and unstake requests by users, keeps track of the total amount of ETH controlled by the/ protocol, and initiates new validators.
|
contract Staking is Initializable, AccessControlEnumerableUpgradeable, IStaking, StakingEvents, ProtocolEvents {
// Errors.
error DoesNotReceiveETH();
error InvalidConfiguration();
error MaximumValidatorDepositExceeded();
error MaximumMETHSupplyExceeded();
error MinimumStakeBoundNotSatisfied();
error MinimumUnstakeBoundNotSatisfied();
error MinimumValidatorDepositNotSatisfied();
error NotEnoughDepositETH();
error NotEnoughUnallocatedETH();
error NotReturnsAggregator();
error NotUnstakeRequestsManager();
error Paused();
error PreviouslyUsedValidator();
error ZeroAddress();
error InvalidDepositRoot(bytes32);
error StakeBelowMinimumMETHAmount(uint256 methAmount, uint256 expectedMinimum);
error UnstakeBelowMinimumETHAmount(uint256 ethAmount, uint256 expectedMinimum);
error InvalidWithdrawalCredentialsWrongLength(uint256);
error InvalidWithdrawalCredentialsNotETH1(bytes12);
error InvalidWithdrawalCredentialsWrongAddress(address);
/// @notice Role allowed trigger administrative tasks such as allocating funds to / withdrawing surplusses from the
/// UnstakeRequestsManager and setting various parameters on the contract.
bytes32 public constant STAKING_MANAGER_ROLE = keccak256("STAKING_MANAGER_ROLE");
/// @notice Role allowed to allocate funds to unstake requests manager and reserve funds to deposit into the
/// validators.
bytes32 public constant ALLOCATOR_SERVICE_ROLE = keccak256("ALLOCATER_SERVICE_ROLE");
/// @notice Role allowed to initiate new validators by sending funds from the allocatedETHForDeposits balance
/// to the beacon chain deposit contract.
bytes32 public constant INITIATOR_SERVICE_ROLE = keccak256("INITIATOR_SERVICE_ROLE");
/// @notice Role to manage the staking allowlist.
bytes32 public constant STAKING_ALLOWLIST_MANAGER_ROLE = keccak256("STAKING_ALLOWLIST_MANAGER_ROLE");
/// @notice Role allowed to stake ETH when allowlist is enabled.
bytes32 public constant STAKING_ALLOWLIST_ROLE = keccak256("STAKING_ALLOWLIST_ROLE");
/// @notice Role allowed to top up the unallocated ETH in the protocol.
bytes32 public constant TOP_UP_ROLE = keccak256("TOP_UP_ROLE");
/// @notice Payload struct submitted for validator initiation.
/// @dev See also {initiateValidatorsWithDeposits}.
struct ValidatorParams {
uint256 operatorID;
uint256 depositAmount;
bytes pubkey;
bytes withdrawalCredentials;
bytes signature;
bytes32 depositDataRoot;
}
/// @notice Keeps track of already initiated validators.
/// @dev This is tracked to ensure that we never deposit for the same validator public key twice, which is a base
/// assumption of this contract and the related off-chain accounting.
mapping(bytes pubkey => bool exists) public usedValidators;
/// @inheritdoc IStakingInitiationRead
/// @dev This is needed to account for ETH that is still in flight, i.e. that has been sent to the deposit contract
/// but has not been processed by the beacon chain yet. Once the off-chain oracle detects those deposits, they are
/// recorded as `totalDepositsProcessed` in the oracle contract to avoid double counting. See also
/// {totalControlled}.
uint256 public totalDepositedInValidators;
/// @inheritdoc IStakingInitiationRead
uint256 public numInitiatedValidators;
/// @notice The amount of ETH that is used to allocate to deposits and fill the pending unstake requests.
uint256 public unallocatedETH;
/// @notice The amount of ETH that is used deposit into validators.
uint256 public allocatedETHForDeposits;
/// @notice The minimum amount of ETH users can stake.
uint256 public minimumStakeBound;
/// @notice The minimum amount of mETH users can unstake.
uint256 public minimumUnstakeBound;
/// @notice When staking on Ethereum, validators must go through an entry queue to bring money into the system, and
/// an exit queue to bring it back out. The entry queue increases in size as more people want to stake. While the
/// money is in the entry queue, it is not earning any rewards. When a validator is active, or in the exit queue, it
/// is earning rewards. Once a validator enters the entry queue, the only way that the money can be retrieved is by
/// waiting for it to become active and then to exit it again. As of July 2023, the entry queue is approximately 40
/// days and the exit queue is 0 days (with ~6 days of processing time).
///
/// In a non-optimal scenario for the protocol, a user could stake (for example) 32 ETH to receive mETH, wait
/// until a validator enters the queue, and then request to unstake to recover their 32 ETH. Now we have 32 ETH in
/// the system which affects the exchange rate, but is not earning rewards.
///
/// In this case, the 'fair' thing to do would be to make the user wait for the queue processing to finish before
/// returning their funds. Because the tokens are fungible however, we have no way of matching 'pending' stakes to a
/// particular user. This means that in order to fulfill unstake requests quickly, we must exit a different
/// validator to return the user's funds. If we exit a validator, we can return the funds after ~5 days, but the
/// original 32 ETH will not be earning for another 35 days, leading to a small but repeatable socialised loss of
/// efficiency for the protocol. As we can only exit validators in chunks of 32 ETH, this case is also exacerbated
/// by a user unstaking smaller amounts of ETH.
///
/// To compensate for the fact that these two queues differ in length, we apply an adjustment to the exchange rate
/// to reflect the difference and mitigate its effect on the protocol. This protects the protocol from the case
/// above, and also from griefing attacks following the same principle. Essentially, when you stake you are
/// receiving a value of mETH that discounts ~35 days worth of rewards in return for being able to access your
/// money without waiting the full 40 days when unstaking. As the adjustment is applied to the exchange rate, this
/// results in a small 'improvement' to the rate for all existing stakers (i.e. it is not a fee levied by the
/// protocol itself).
///
/// As the adjustment is applied to the exchange rate, the result is reflected in any user interface which shows the
/// amount of mETH received when staking, meaning there is no surprise for users when staking or unstaking.
/// @dev The value is in basis points (1/10000).
uint16 public exchangeAdjustmentRate;
/// @dev A basis point (often denoted as bp, 1bp = 0.01%) is a unit of measure used in finance to describe
/// the percentage change in a financial instrument. This is a constant value set as 10000 which represents
/// 100% in basis point terms.
uint16 internal constant _BASIS_POINTS_DENOMINATOR = 10_000;
/// @notice The maximum amount the exchange adjustment rate (10%) that can be set by the admin.
uint16 internal constant _MAX_EXCHANGE_ADJUSTMENT_RATE = _BASIS_POINTS_DENOMINATOR / 10; // 10%
/// @notice The minimum amount of ETH that the staking contract can send to the deposit contract to initiate new
/// validators.
/// @dev This is used as an additional safeguard to prevent sending deposits that would result in non-activated
/// validators (since we don't do top-ups), that would need to be exited again to get the ETH back.
uint256 public minimumDepositAmount;
/// @notice The maximum amount of ETH that the staking contract can send to the deposit contract to initiate new
/// validators.
/// @dev This is used as an additional safeguard to prevent sending too large deposits. While this is not a critical
/// issue as any surplus >32 ETH (at the time of writing) will automatically be withdrawn again at some point, it is
/// still undesireable as it locks up not-earning ETH for the duration of the round trip decreasing the efficiency
/// of the protocol.
uint256 public maximumDepositAmount;
/// @notice The beacon chain deposit contract.
/// @dev ETH will be sent there during validator initiation.
IDepositContract public depositContract;
/// @notice The mETH token contract.
/// @dev Tokens will be minted / burned during staking / unstaking.
IMETH public mETH;
/// @notice The oracle contract.
/// @dev Tracks ETH on the beacon chain and other accounting relevant quantities.
IOracleReadRecord public oracle;
/// @notice The pauser contract.
/// @dev Keeps the pause state across the protocol.
IPauserRead public pauser;
/// @notice The contract tracking unstake requests and related allocation and claim operations.
IUnstakeRequestsManager public unstakeRequestsManager;
/// @notice The address to receive beacon chain withdrawals (i.e. validator rewards and exits).
/// @dev Changing this variable will not have an immediate effect as all exisiting validators will still have the
/// original value set.
address public withdrawalWallet;
/// @notice The address for the returns aggregator contract to push funds.
/// @dev See also {receiveReturns}.
address public returnsAggregator;
/// @notice The staking allowlist flag which, when enabled, allows staking only for addresses in allowlist.
bool public isStakingAllowlist;
/// @inheritdoc IStakingInitiationRead
/// @dev This will be used to give off-chain services a sensible point in time to start their analysis from.
uint256 public initializationBlockNumber;
/// @notice The maximum amount of mETH that can be minted during the staking process.
/// @dev This is used as an additional safeguard to create a maximum stake amount in the protocol. As the protocol
/// scales up this value will be increased to allow for more staking.
uint256 public maximumMETHSupply;
/// @notice Configuration for contract initialization.
struct Init {
address admin;
address manager;
address allocatorService;
address initiatorService;
address returnsAggregator;
address withdrawalWallet;
IMETH mETH;
IDepositContract depositContract;
IOracleReadRecord oracle;
IPauserRead pauser;
IUnstakeRequestsManager unstakeRequestsManager;
}
constructor() {
_disableInitializers();
}
/// @notice Inititalizes the contract.
/// @dev MUST be called during the contract upgrade to set up the proxies state.
function initialize(Init memory init) external initializer {
__AccessControlEnumerable_init();
_grantRole(DEFAULT_ADMIN_ROLE, init.admin);
_grantRole(STAKING_MANAGER_ROLE, init.manager);
_grantRole(ALLOCATOR_SERVICE_ROLE, init.allocatorService);
_grantRole(INITIATOR_SERVICE_ROLE, init.initiatorService);
// Intentionally does not set anyone as the TOP_UP_ROLE as it will only be granted
// in the off-chance that the top up functionality is required.
// Set up roles for the staking allowlist. Intentionally do not grant anyone the
// STAKING_ALLOWLIST_MANAGER_ROLE as it will only be granted later.
_setRoleAdmin(STAKING_ALLOWLIST_MANAGER_ROLE, STAKING_MANAGER_ROLE);
_setRoleAdmin(STAKING_ALLOWLIST_ROLE, STAKING_ALLOWLIST_MANAGER_ROLE);
mETH = init.mETH;
depositContract = init.depositContract;
oracle = init.oracle;
pauser = init.pauser;
returnsAggregator = init.returnsAggregator;
unstakeRequestsManager = init.unstakeRequestsManager;
withdrawalWallet = init.withdrawalWallet;
minimumStakeBound = 0.1 ether;
minimumUnstakeBound = 0.01 ether;
minimumDepositAmount = 32 ether;
maximumDepositAmount = 32 ether;
isStakingAllowlist = true;
initializationBlockNumber = block.number;
// Set the maximum mETH supply to some sensible amount which is expected to be changed as the
// protocol ramps up.
maximumMETHSupply = 1024 ether;
}
/// @notice Interface for users to stake their ETH with the protocol. Note: when allowlist is enabled, only users
/// with the allowlist can stake.
/// @dev Mints the corresponding amount of mETH (relative to the stake's share in the total ETH controlled by the
/// protocol) to the user.
/// @param minMETHAmount The minimum amount of mETH that the user expects to receive in return.
function stake(uint256 minMETHAmount) external payable {
if (pauser.isStakingPaused()) {
revert Paused();
}
if (isStakingAllowlist) {
_checkRole(STAKING_ALLOWLIST_ROLE);
}
if (msg.value < minimumStakeBound) {
revert MinimumStakeBoundNotSatisfied();
}
uint256 mETHMintAmount = ethToMETH(msg.value);
if (mETHMintAmount + mETH.totalSupply() > maximumMETHSupply) {
revert MaximumMETHSupplyExceeded();
}
if (mETHMintAmount < minMETHAmount) {
revert StakeBelowMinimumMETHAmount(mETHMintAmount, minMETHAmount);
}
// Increment unallocated ETH after calculating the exchange rate to ensure
// a consistent rate.
unallocatedETH += msg.value;
emit Staked(msg.sender, msg.value, mETHMintAmount);
mETH.mint(msg.sender, mETHMintAmount);
}
/// @notice Interface for users to submit a request to unstake.
/// @dev Transfers the specified amount of mETH to the staking contract and locks it there until it is burned on
/// request claim. The staking contract must therefore be approved to move the user's mETH on their behalf.
/// @param methAmount The amount of mETH to unstake.
/// @param minETHAmount The minimum amount of ETH that the user expects to receive.
/// @return The request ID.
function unstakeRequest(uint128 methAmount, uint128 minETHAmount) external returns (uint256) {
return _unstakeRequest(methAmount, minETHAmount);
}
/// @notice Interface for users to submit a request to unstake with an ERC20 permit.
/// @dev Transfers the specified amount of mETH to the staking contract and locks it there until it is burned on
/// request claim. The permit must therefore allow the staking contract to move the user's mETH on their behalf.
/// @return The request ID.
function unstakeRequestWithPermit(
uint128 methAmount,
uint128 minETHAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
SafeERC20Upgradeable.safePermit(mETH, msg.sender, address(this), methAmount, deadline, v, r, s);
return _unstakeRequest(methAmount, minETHAmount);
}
/// @notice Processes a user's request to unstake by transferring the corresponding mETH to the staking contract
/// and creating the request on the unstake requests manager.
/// @param methAmount The amount of mETH to unstake.
/// @param minETHAmount The minimum amount of ETH that the user expects to receive.
function _unstakeRequest(uint128 methAmount, uint128 minETHAmount) internal returns (uint256) {
if (pauser.isUnstakeRequestsAndClaimsPaused()) {
revert Paused();
}
if (methAmount < minimumUnstakeBound) {
revert MinimumUnstakeBoundNotSatisfied();
}
uint128 ethAmount = uint128(mETHToETH(methAmount));
if (ethAmount < minETHAmount) {
revert UnstakeBelowMinimumETHAmount(ethAmount, minETHAmount);
}
uint256 requestID =
unstakeRequestsManager.create({requester: msg.sender, mETHLocked: methAmount, ethRequested: ethAmount});
emit UnstakeRequested({id: requestID, staker: msg.sender, ethAmount: ethAmount, mETHLocked: methAmount});
SafeERC20Upgradeable.safeTransferFrom(mETH, msg.sender, address(unstakeRequestsManager), methAmount);
return requestID;
}
/// @notice Interface for users to claim their finalized and filled unstaking requests.
/// @dev See also {UnstakeRequestsManager} for a more detailed explanation of finalization and request filling.
function claimUnstakeRequest(uint256 unstakeRequestID) external {
if (pauser.isUnstakeRequestsAndClaimsPaused()) {
revert Paused();
}
emit UnstakeRequestClaimed(unstakeRequestID, msg.sender);
unstakeRequestsManager.claim(unstakeRequestID, msg.sender);
}
/// @notice Returns the status of the request whether it is finalized and how much ETH has been filled.
/// See also {UnstakeRequestsManager.requestInfo} for a more detailed explanation of finalization and request
/// filling.
/// @param unstakeRequestID The ID of the unstake request.
/// @return bool indicating if the unstake request is finalized, and the amount of ETH that has been filled.
function unstakeRequestInfo(uint256 unstakeRequestID) external view returns (bool, uint256) {
return unstakeRequestsManager.requestInfo(unstakeRequestID);
}
/// @notice Withdraws any surplus from the unstake requests manager.
/// @dev The request manager is expected to return the funds by pushing them using
/// {receiveFromUnstakeRequestsManager}.
function reclaimAllocatedETHSurplus() external onlyRole(STAKING_MANAGER_ROLE) {
// Calls the receiveFromUnstakeRequestsManager() where we perform
// the accounting.
unstakeRequestsManager.withdrawAllocatedETHSurplus();
}
/// @notice Allocates ETH from the unallocatedETH balance to the unstake requests manager to fill pending requests
/// and adds to the allocatedETHForDeposits balance that is used to initiate new validators.
function allocateETH(uint256 allocateToUnstakeRequestsManager, uint256 allocateToDeposits)
external
onlyRole(ALLOCATOR_SERVICE_ROLE)
{
if (pauser.isAllocateETHPaused()) {
revert Paused();
}
if (allocateToUnstakeRequestsManager + allocateToDeposits > unallocatedETH) {
revert NotEnoughUnallocatedETH();
}
unallocatedETH -= allocateToUnstakeRequestsManager + allocateToDeposits;
if (allocateToDeposits > 0) {
allocatedETHForDeposits += allocateToDeposits;
emit AllocatedETHToDeposits(allocateToDeposits);
}
if (allocateToUnstakeRequestsManager > 0) {
emit AllocatedETHToUnstakeRequestsManager(allocateToUnstakeRequestsManager);
unstakeRequestsManager.allocateETH{value: allocateToUnstakeRequestsManager}();
}
}
/// @notice Initiates new validators by sending ETH to the beacon chain deposit contract.
/// @dev Cannot initiate the same validator (public key) twice. Since BLS signatures cannot be feasibly verified on
/// the EVM, the caller must carefully make sure that the sent payloads (public keys + signatures) are correct,
/// otherwise the sent ETH will be lost.
function initiateValidatorsWithDeposits(ValidatorParams[] calldata validators, bytes32 expectedDepositRoot)
external
onlyRole(INITIATOR_SERVICE_ROLE)
{
if (pauser.isInitiateValidatorsPaused()) {
revert Paused();
}
if (validators.length == 0) {
return;
}
// Check that the deposit root matches the given value. This ensures that the deposit contract state
// has not changed since the transaction was submitted, which means that a rogue node operator cannot
// front-run deposit transactions.
bytes32 actualRoot = depositContract.get_deposit_root();
if (expectedDepositRoot != actualRoot) {
revert InvalidDepositRoot(actualRoot);
}
// First loop is to check that all validators are valid according to our constraints and we record the
// validators and how much we have deposited.
uint256 amountDeposited = 0;
for (uint256 i = 0; i < validators.length; ++i) {
ValidatorParams calldata validator = validators[i];
if (usedValidators[validator.pubkey]) {
revert PreviouslyUsedValidator();
}
if (validator.depositAmount < minimumDepositAmount) {
revert MinimumValidatorDepositNotSatisfied();
}
if (validator.depositAmount > maximumDepositAmount) {
revert MaximumValidatorDepositExceeded();
}
_requireProtocolWithdrawalAccount(validator.withdrawalCredentials);
usedValidators[validator.pubkey] = true;
amountDeposited += validator.depositAmount;
emit ValidatorInitiated({
id: keccak256(validator.pubkey),
operatorID: validator.operatorID,
pubkey: validator.pubkey,
amountDeposited: validator.depositAmount
});
}
if (amountDeposited > allocatedETHForDeposits) {
revert NotEnoughDepositETH();
}
allocatedETHForDeposits -= amountDeposited;
totalDepositedInValidators += amountDeposited;
numInitiatedValidators += validators.length;
// Second loop is to send the deposits to the deposit contract. Keeps external calls to the deposit contract
// separate from state changes.
for (uint256 i = 0; i < validators.length; ++i) {
ValidatorParams calldata validator = validators[i];
depositContract.deposit{value: validator.depositAmount}({
pubkey: validator.pubkey,
withdrawal_credentials: validator.withdrawalCredentials,
signature: validator.signature,
deposit_data_root: validator.depositDataRoot
});
}
}
|
contract Staking is Initializable, AccessControlEnumerableUpgradeable, IStaking, StakingEvents, ProtocolEvents {
// Errors.
error DoesNotReceiveETH();
error InvalidConfiguration();
error MaximumValidatorDepositExceeded();
error MaximumMETHSupplyExceeded();
error MinimumStakeBoundNotSatisfied();
error MinimumUnstakeBoundNotSatisfied();
error MinimumValidatorDepositNotSatisfied();
error NotEnoughDepositETH();
error NotEnoughUnallocatedETH();
error NotReturnsAggregator();
error NotUnstakeRequestsManager();
error Paused();
error PreviouslyUsedValidator();
error ZeroAddress();
error InvalidDepositRoot(bytes32);
error StakeBelowMinimumMETHAmount(uint256 methAmount, uint256 expectedMinimum);
error UnstakeBelowMinimumETHAmount(uint256 ethAmount, uint256 expectedMinimum);
error InvalidWithdrawalCredentialsWrongLength(uint256);
error InvalidWithdrawalCredentialsNotETH1(bytes12);
error InvalidWithdrawalCredentialsWrongAddress(address);
/// @notice Role allowed trigger administrative tasks such as allocating funds to / withdrawing surplusses from the
/// UnstakeRequestsManager and setting various parameters on the contract.
bytes32 public constant STAKING_MANAGER_ROLE = keccak256("STAKING_MANAGER_ROLE");
/// @notice Role allowed to allocate funds to unstake requests manager and reserve funds to deposit into the
/// validators.
bytes32 public constant ALLOCATOR_SERVICE_ROLE = keccak256("ALLOCATER_SERVICE_ROLE");
/// @notice Role allowed to initiate new validators by sending funds from the allocatedETHForDeposits balance
/// to the beacon chain deposit contract.
bytes32 public constant INITIATOR_SERVICE_ROLE = keccak256("INITIATOR_SERVICE_ROLE");
/// @notice Role to manage the staking allowlist.
bytes32 public constant STAKING_ALLOWLIST_MANAGER_ROLE = keccak256("STAKING_ALLOWLIST_MANAGER_ROLE");
/// @notice Role allowed to stake ETH when allowlist is enabled.
bytes32 public constant STAKING_ALLOWLIST_ROLE = keccak256("STAKING_ALLOWLIST_ROLE");
/// @notice Role allowed to top up the unallocated ETH in the protocol.
bytes32 public constant TOP_UP_ROLE = keccak256("TOP_UP_ROLE");
/// @notice Payload struct submitted for validator initiation.
/// @dev See also {initiateValidatorsWithDeposits}.
struct ValidatorParams {
uint256 operatorID;
uint256 depositAmount;
bytes pubkey;
bytes withdrawalCredentials;
bytes signature;
bytes32 depositDataRoot;
}
/// @notice Keeps track of already initiated validators.
/// @dev This is tracked to ensure that we never deposit for the same validator public key twice, which is a base
/// assumption of this contract and the related off-chain accounting.
mapping(bytes pubkey => bool exists) public usedValidators;
/// @inheritdoc IStakingInitiationRead
/// @dev This is needed to account for ETH that is still in flight, i.e. that has been sent to the deposit contract
/// but has not been processed by the beacon chain yet. Once the off-chain oracle detects those deposits, they are
/// recorded as `totalDepositsProcessed` in the oracle contract to avoid double counting. See also
/// {totalControlled}.
uint256 public totalDepositedInValidators;
/// @inheritdoc IStakingInitiationRead
uint256 public numInitiatedValidators;
/// @notice The amount of ETH that is used to allocate to deposits and fill the pending unstake requests.
uint256 public unallocatedETH;
/// @notice The amount of ETH that is used deposit into validators.
uint256 public allocatedETHForDeposits;
/// @notice The minimum amount of ETH users can stake.
uint256 public minimumStakeBound;
/// @notice The minimum amount of mETH users can unstake.
uint256 public minimumUnstakeBound;
/// @notice When staking on Ethereum, validators must go through an entry queue to bring money into the system, and
/// an exit queue to bring it back out. The entry queue increases in size as more people want to stake. While the
/// money is in the entry queue, it is not earning any rewards. When a validator is active, or in the exit queue, it
/// is earning rewards. Once a validator enters the entry queue, the only way that the money can be retrieved is by
/// waiting for it to become active and then to exit it again. As of July 2023, the entry queue is approximately 40
/// days and the exit queue is 0 days (with ~6 days of processing time).
///
/// In a non-optimal scenario for the protocol, a user could stake (for example) 32 ETH to receive mETH, wait
/// until a validator enters the queue, and then request to unstake to recover their 32 ETH. Now we have 32 ETH in
/// the system which affects the exchange rate, but is not earning rewards.
///
/// In this case, the 'fair' thing to do would be to make the user wait for the queue processing to finish before
/// returning their funds. Because the tokens are fungible however, we have no way of matching 'pending' stakes to a
/// particular user. This means that in order to fulfill unstake requests quickly, we must exit a different
/// validator to return the user's funds. If we exit a validator, we can return the funds after ~5 days, but the
/// original 32 ETH will not be earning for another 35 days, leading to a small but repeatable socialised loss of
/// efficiency for the protocol. As we can only exit validators in chunks of 32 ETH, this case is also exacerbated
/// by a user unstaking smaller amounts of ETH.
///
/// To compensate for the fact that these two queues differ in length, we apply an adjustment to the exchange rate
/// to reflect the difference and mitigate its effect on the protocol. This protects the protocol from the case
/// above, and also from griefing attacks following the same principle. Essentially, when you stake you are
/// receiving a value of mETH that discounts ~35 days worth of rewards in return for being able to access your
/// money without waiting the full 40 days when unstaking. As the adjustment is applied to the exchange rate, this
/// results in a small 'improvement' to the rate for all existing stakers (i.e. it is not a fee levied by the
/// protocol itself).
///
/// As the adjustment is applied to the exchange rate, the result is reflected in any user interface which shows the
/// amount of mETH received when staking, meaning there is no surprise for users when staking or unstaking.
/// @dev The value is in basis points (1/10000).
uint16 public exchangeAdjustmentRate;
/// @dev A basis point (often denoted as bp, 1bp = 0.01%) is a unit of measure used in finance to describe
/// the percentage change in a financial instrument. This is a constant value set as 10000 which represents
/// 100% in basis point terms.
uint16 internal constant _BASIS_POINTS_DENOMINATOR = 10_000;
/// @notice The maximum amount the exchange adjustment rate (10%) that can be set by the admin.
uint16 internal constant _MAX_EXCHANGE_ADJUSTMENT_RATE = _BASIS_POINTS_DENOMINATOR / 10; // 10%
/// @notice The minimum amount of ETH that the staking contract can send to the deposit contract to initiate new
/// validators.
/// @dev This is used as an additional safeguard to prevent sending deposits that would result in non-activated
/// validators (since we don't do top-ups), that would need to be exited again to get the ETH back.
uint256 public minimumDepositAmount;
/// @notice The maximum amount of ETH that the staking contract can send to the deposit contract to initiate new
/// validators.
/// @dev This is used as an additional safeguard to prevent sending too large deposits. While this is not a critical
/// issue as any surplus >32 ETH (at the time of writing) will automatically be withdrawn again at some point, it is
/// still undesireable as it locks up not-earning ETH for the duration of the round trip decreasing the efficiency
/// of the protocol.
uint256 public maximumDepositAmount;
/// @notice The beacon chain deposit contract.
/// @dev ETH will be sent there during validator initiation.
IDepositContract public depositContract;
/// @notice The mETH token contract.
/// @dev Tokens will be minted / burned during staking / unstaking.
IMETH public mETH;
/// @notice The oracle contract.
/// @dev Tracks ETH on the beacon chain and other accounting relevant quantities.
IOracleReadRecord public oracle;
/// @notice The pauser contract.
/// @dev Keeps the pause state across the protocol.
IPauserRead public pauser;
/// @notice The contract tracking unstake requests and related allocation and claim operations.
IUnstakeRequestsManager public unstakeRequestsManager;
/// @notice The address to receive beacon chain withdrawals (i.e. validator rewards and exits).
/// @dev Changing this variable will not have an immediate effect as all exisiting validators will still have the
/// original value set.
address public withdrawalWallet;
/// @notice The address for the returns aggregator contract to push funds.
/// @dev See also {receiveReturns}.
address public returnsAggregator;
/// @notice The staking allowlist flag which, when enabled, allows staking only for addresses in allowlist.
bool public isStakingAllowlist;
/// @inheritdoc IStakingInitiationRead
/// @dev This will be used to give off-chain services a sensible point in time to start their analysis from.
uint256 public initializationBlockNumber;
/// @notice The maximum amount of mETH that can be minted during the staking process.
/// @dev This is used as an additional safeguard to create a maximum stake amount in the protocol. As the protocol
/// scales up this value will be increased to allow for more staking.
uint256 public maximumMETHSupply;
/// @notice Configuration for contract initialization.
struct Init {
address admin;
address manager;
address allocatorService;
address initiatorService;
address returnsAggregator;
address withdrawalWallet;
IMETH mETH;
IDepositContract depositContract;
IOracleReadRecord oracle;
IPauserRead pauser;
IUnstakeRequestsManager unstakeRequestsManager;
}
constructor() {
_disableInitializers();
}
/// @notice Inititalizes the contract.
/// @dev MUST be called during the contract upgrade to set up the proxies state.
function initialize(Init memory init) external initializer {
__AccessControlEnumerable_init();
_grantRole(DEFAULT_ADMIN_ROLE, init.admin);
_grantRole(STAKING_MANAGER_ROLE, init.manager);
_grantRole(ALLOCATOR_SERVICE_ROLE, init.allocatorService);
_grantRole(INITIATOR_SERVICE_ROLE, init.initiatorService);
// Intentionally does not set anyone as the TOP_UP_ROLE as it will only be granted
// in the off-chance that the top up functionality is required.
// Set up roles for the staking allowlist. Intentionally do not grant anyone the
// STAKING_ALLOWLIST_MANAGER_ROLE as it will only be granted later.
_setRoleAdmin(STAKING_ALLOWLIST_MANAGER_ROLE, STAKING_MANAGER_ROLE);
_setRoleAdmin(STAKING_ALLOWLIST_ROLE, STAKING_ALLOWLIST_MANAGER_ROLE);
mETH = init.mETH;
depositContract = init.depositContract;
oracle = init.oracle;
pauser = init.pauser;
returnsAggregator = init.returnsAggregator;
unstakeRequestsManager = init.unstakeRequestsManager;
withdrawalWallet = init.withdrawalWallet;
minimumStakeBound = 0.1 ether;
minimumUnstakeBound = 0.01 ether;
minimumDepositAmount = 32 ether;
maximumDepositAmount = 32 ether;
isStakingAllowlist = true;
initializationBlockNumber = block.number;
// Set the maximum mETH supply to some sensible amount which is expected to be changed as the
// protocol ramps up.
maximumMETHSupply = 1024 ether;
}
/// @notice Interface for users to stake their ETH with the protocol. Note: when allowlist is enabled, only users
/// with the allowlist can stake.
/// @dev Mints the corresponding amount of mETH (relative to the stake's share in the total ETH controlled by the
/// protocol) to the user.
/// @param minMETHAmount The minimum amount of mETH that the user expects to receive in return.
function stake(uint256 minMETHAmount) external payable {
if (pauser.isStakingPaused()) {
revert Paused();
}
if (isStakingAllowlist) {
_checkRole(STAKING_ALLOWLIST_ROLE);
}
if (msg.value < minimumStakeBound) {
revert MinimumStakeBoundNotSatisfied();
}
uint256 mETHMintAmount = ethToMETH(msg.value);
if (mETHMintAmount + mETH.totalSupply() > maximumMETHSupply) {
revert MaximumMETHSupplyExceeded();
}
if (mETHMintAmount < minMETHAmount) {
revert StakeBelowMinimumMETHAmount(mETHMintAmount, minMETHAmount);
}
// Increment unallocated ETH after calculating the exchange rate to ensure
// a consistent rate.
unallocatedETH += msg.value;
emit Staked(msg.sender, msg.value, mETHMintAmount);
mETH.mint(msg.sender, mETHMintAmount);
}
/// @notice Interface for users to submit a request to unstake.
/// @dev Transfers the specified amount of mETH to the staking contract and locks it there until it is burned on
/// request claim. The staking contract must therefore be approved to move the user's mETH on their behalf.
/// @param methAmount The amount of mETH to unstake.
/// @param minETHAmount The minimum amount of ETH that the user expects to receive.
/// @return The request ID.
function unstakeRequest(uint128 methAmount, uint128 minETHAmount) external returns (uint256) {
return _unstakeRequest(methAmount, minETHAmount);
}
/// @notice Interface for users to submit a request to unstake with an ERC20 permit.
/// @dev Transfers the specified amount of mETH to the staking contract and locks it there until it is burned on
/// request claim. The permit must therefore allow the staking contract to move the user's mETH on their behalf.
/// @return The request ID.
function unstakeRequestWithPermit(
uint128 methAmount,
uint128 minETHAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
SafeERC20Upgradeable.safePermit(mETH, msg.sender, address(this), methAmount, deadline, v, r, s);
return _unstakeRequest(methAmount, minETHAmount);
}
/// @notice Processes a user's request to unstake by transferring the corresponding mETH to the staking contract
/// and creating the request on the unstake requests manager.
/// @param methAmount The amount of mETH to unstake.
/// @param minETHAmount The minimum amount of ETH that the user expects to receive.
function _unstakeRequest(uint128 methAmount, uint128 minETHAmount) internal returns (uint256) {
if (pauser.isUnstakeRequestsAndClaimsPaused()) {
revert Paused();
}
if (methAmount < minimumUnstakeBound) {
revert MinimumUnstakeBoundNotSatisfied();
}
uint128 ethAmount = uint128(mETHToETH(methAmount));
if (ethAmount < minETHAmount) {
revert UnstakeBelowMinimumETHAmount(ethAmount, minETHAmount);
}
uint256 requestID =
unstakeRequestsManager.create({requester: msg.sender, mETHLocked: methAmount, ethRequested: ethAmount});
emit UnstakeRequested({id: requestID, staker: msg.sender, ethAmount: ethAmount, mETHLocked: methAmount});
SafeERC20Upgradeable.safeTransferFrom(mETH, msg.sender, address(unstakeRequestsManager), methAmount);
return requestID;
}
/// @notice Interface for users to claim their finalized and filled unstaking requests.
/// @dev See also {UnstakeRequestsManager} for a more detailed explanation of finalization and request filling.
function claimUnstakeRequest(uint256 unstakeRequestID) external {
if (pauser.isUnstakeRequestsAndClaimsPaused()) {
revert Paused();
}
emit UnstakeRequestClaimed(unstakeRequestID, msg.sender);
unstakeRequestsManager.claim(unstakeRequestID, msg.sender);
}
/// @notice Returns the status of the request whether it is finalized and how much ETH has been filled.
/// See also {UnstakeRequestsManager.requestInfo} for a more detailed explanation of finalization and request
/// filling.
/// @param unstakeRequestID The ID of the unstake request.
/// @return bool indicating if the unstake request is finalized, and the amount of ETH that has been filled.
function unstakeRequestInfo(uint256 unstakeRequestID) external view returns (bool, uint256) {
return unstakeRequestsManager.requestInfo(unstakeRequestID);
}
/// @notice Withdraws any surplus from the unstake requests manager.
/// @dev The request manager is expected to return the funds by pushing them using
/// {receiveFromUnstakeRequestsManager}.
function reclaimAllocatedETHSurplus() external onlyRole(STAKING_MANAGER_ROLE) {
// Calls the receiveFromUnstakeRequestsManager() where we perform
// the accounting.
unstakeRequestsManager.withdrawAllocatedETHSurplus();
}
/// @notice Allocates ETH from the unallocatedETH balance to the unstake requests manager to fill pending requests
/// and adds to the allocatedETHForDeposits balance that is used to initiate new validators.
function allocateETH(uint256 allocateToUnstakeRequestsManager, uint256 allocateToDeposits)
external
onlyRole(ALLOCATOR_SERVICE_ROLE)
{
if (pauser.isAllocateETHPaused()) {
revert Paused();
}
if (allocateToUnstakeRequestsManager + allocateToDeposits > unallocatedETH) {
revert NotEnoughUnallocatedETH();
}
unallocatedETH -= allocateToUnstakeRequestsManager + allocateToDeposits;
if (allocateToDeposits > 0) {
allocatedETHForDeposits += allocateToDeposits;
emit AllocatedETHToDeposits(allocateToDeposits);
}
if (allocateToUnstakeRequestsManager > 0) {
emit AllocatedETHToUnstakeRequestsManager(allocateToUnstakeRequestsManager);
unstakeRequestsManager.allocateETH{value: allocateToUnstakeRequestsManager}();
}
}
/// @notice Initiates new validators by sending ETH to the beacon chain deposit contract.
/// @dev Cannot initiate the same validator (public key) twice. Since BLS signatures cannot be feasibly verified on
/// the EVM, the caller must carefully make sure that the sent payloads (public keys + signatures) are correct,
/// otherwise the sent ETH will be lost.
function initiateValidatorsWithDeposits(ValidatorParams[] calldata validators, bytes32 expectedDepositRoot)
external
onlyRole(INITIATOR_SERVICE_ROLE)
{
if (pauser.isInitiateValidatorsPaused()) {
revert Paused();
}
if (validators.length == 0) {
return;
}
// Check that the deposit root matches the given value. This ensures that the deposit contract state
// has not changed since the transaction was submitted, which means that a rogue node operator cannot
// front-run deposit transactions.
bytes32 actualRoot = depositContract.get_deposit_root();
if (expectedDepositRoot != actualRoot) {
revert InvalidDepositRoot(actualRoot);
}
// First loop is to check that all validators are valid according to our constraints and we record the
// validators and how much we have deposited.
uint256 amountDeposited = 0;
for (uint256 i = 0; i < validators.length; ++i) {
ValidatorParams calldata validator = validators[i];
if (usedValidators[validator.pubkey]) {
revert PreviouslyUsedValidator();
}
if (validator.depositAmount < minimumDepositAmount) {
revert MinimumValidatorDepositNotSatisfied();
}
if (validator.depositAmount > maximumDepositAmount) {
revert MaximumValidatorDepositExceeded();
}
_requireProtocolWithdrawalAccount(validator.withdrawalCredentials);
usedValidators[validator.pubkey] = true;
amountDeposited += validator.depositAmount;
emit ValidatorInitiated({
id: keccak256(validator.pubkey),
operatorID: validator.operatorID,
pubkey: validator.pubkey,
amountDeposited: validator.depositAmount
});
}
if (amountDeposited > allocatedETHForDeposits) {
revert NotEnoughDepositETH();
}
allocatedETHForDeposits -= amountDeposited;
totalDepositedInValidators += amountDeposited;
numInitiatedValidators += validators.length;
// Second loop is to send the deposits to the deposit contract. Keeps external calls to the deposit contract
// separate from state changes.
for (uint256 i = 0; i < validators.length; ++i) {
ValidatorParams calldata validator = validators[i];
depositContract.deposit{value: validator.depositAmount}({
pubkey: validator.pubkey,
withdrawal_credentials: validator.withdrawalCredentials,
signature: validator.signature,
deposit_data_root: validator.depositDataRoot
});
}
}
| 32,762
|
89
|
// If currentPeriod > anchorPeriod:Set anchors[asset] = (currentPeriod, price)The new anchor is if we're in a new period or we had a pending anchor, then we become the new anchor
|
if (localVars.currentPeriod > localVars.anchorPeriod) {
anchors[asset] = Anchor({period : localVars.currentPeriod, priceMantissa : localVars.price.mantissa});
|
if (localVars.currentPeriod > localVars.anchorPeriod) {
anchors[asset] = Anchor({period : localVars.currentPeriod, priceMantissa : localVars.price.mantissa});
| 33,962
|
1
|
// Overallocate memory
|
nstr = new string(MAX_UINT256_STRING_LENGTH);
uint256 k = MAX_UINT256_STRING_LENGTH;
|
nstr = new string(MAX_UINT256_STRING_LENGTH);
uint256 k = MAX_UINT256_STRING_LENGTH;
| 22,797
|
66
|
// Depool Debot v1 (with debot interfaces).
|
contract DepoolDebot is Debot, Upgradable, Transferable {
address m_depool;
uint128 m_balance;
address m_wallet;
uint128 m_walletBalance;
uint128 m_stake;
uint128 m_instantStake;
/*
Storage
*/
struct DepoolInfo {
bool poolClosed;
uint64 minStake;
uint64 validatorAssurance;
uint8 participantRewardFraction;
uint8 validatorRewardFraction;
uint64 balanceThreshold;
address validatorWallet;
address[] proxies;
uint64 stakeFee;
uint64 retOrReinvFee;
uint64 proxyFee;
}
struct StakeData {
uint64 stake;
bool reinvest;
address beneficiary;
uint32 total;
uint32 withdrawal;
}
struct Participant {
uint64 total;
uint64 withdrawValue;
bool reinvest;
uint64 reward;
mapping (uint64 => uint64) stakes;
mapping (uint64 => InvestParams) vestings;
mapping (uint64 => InvestParams) locks;
address vestingDonor;
address lockDonor;
}
// target depool rounds
mapping(uint64 => RoundsBase.TruncatedRound) m_rounds;
// tartarget depool participants list
address[] m_participants;
// target depool global parameters
DepoolInfo m_info;
// arguments for depositing stake
StakeData m_stakeData;
// participant address
address m_participant;
// staking details about m_participant
Participant m_participantInfo;
string m_icon;
bool m_invoked;
// Default constructor
function setIcon(string icon) public {
require(msg.pubkey() == tvm.pubkey(), 100);
tvm.accept();
m_icon = icon;
}
function start() public override {
_start();
}
/// @notice Returns Metadata about DeBot.
function getDebotInfo() public functionID(0xDEB) override view returns(
string name, string version, string publisher, string caption, string author,
address support, string hello, string language, string dabi, bytes icon
) {
name = "DePool";
version = "1.3.0";
publisher = "TON Labs";
caption = "DeBot that helps you manage your stakes";
author = "TON Labs";
support = address.makeAddrStd(0, 0x66e01d6df5a8d7677d9ab2daf7f258f1e2a7fe73da5320300395f99e01dc3b5f);
hello = "Hi, I can help you manage your stakes in Depool. I am in development now.";
language = "en";
dabi = m_debotAbi.get();
icon = m_icon;
}
function getRequiredInterfaces() public view override returns (uint256[] interfaces) {
return [ Terminal.ID, AmountInput.ID, Menu.ID, ConfirmInput.ID, AddressInput.ID ];
}
function _start() private {
AddressInput.get(tvm.functionId(setDepool), "Which DePool are you interested in?");
}
function setDepool(address value) public {
m_depool = value;
gotoDePoolChecks();
}
function gotoDePoolChecks() public {
Sdk.getAccountType(tvm.functionId(checkStatus), m_depool);
}
function checkStatus(int8 acc_type) public {
if (!_checkActiveStatus(acc_type, "DePool")) {
_start();
return;
}
Sdk.getAccountCodeHash(tvm.functionId(checkDepoolHash), m_depool);
}
function checkDepoolHash(uint256 code_hash) public {
if (code_hash != 0x14e20e304f53e6da152eb95fffc993dbd28245a775d847eed043f7c78a503885) {
Terminal.print(tvm.functionId(Debot.start), "This is not a DePool v3. Enter another address.");
return;
}
_getRounds(tvm.functionId(setRounds));
_getDePoolInfo(tvm.functionId(setDepoolInfo));
_getParticipants(tvm.functionId(setParticipants));
Sdk.getBalance(tvm.functionId(setBalance), m_depool);
if (m_invoked) {
this.invoke2();
} else {
this.preMain();
}
}
function setBalance(uint128 nanotokens) public {
m_balance = nanotokens;
}
function preMain() public {
uint64 totalStake = totalParticipantFunds();
string totStakeStr = tokensToStr(totalStake);
string valAssuranceStr = tokensToStr(m_info.validatorAssurance);
string minStakeStr = tokensToStr(m_info.minStake);
string result = format("DePool information:\nReward fee: {}%\nLock-up period: {} hours\nParticipants: {}\nBalance: {}\nAssurance: {}\nMin. stake: {}",
m_info.validatorRewardFraction, uint32(54),
m_participants.length, totStakeStr, valAssuranceStr, minStakeStr);
Terminal.print(tvm.functionId(mainMenu), result);
}
function selectWallet() public {
AddressInput.get(tvm.functionId(checkWallet), "What wallet to use to make a stake?");
}
function checkWallet(address value) public {
m_wallet = value;
Sdk.getAccountType(tvm.functionId(checkWallet2), m_wallet);
Sdk.getBalance(tvm.functionId(setWalletBalance), m_wallet);
}
function checkWallet2(int8 acc_type) public {
if (!_checkActiveStatus(acc_type, "Wallet")) return;
if (m_invoked) {
this.invoke1();
} else {
this.checkStake();
}
}
function checkStake() public {
bool exist = _findParticipant(m_wallet);
if (!exist) {
Terminal.print(tvm.functionId(showStakeMenu), "You don't have a stake in this DePool yet.");
} else {
_getParticipantInfo(m_wallet, tvm.functionId(setParticipantInfo));
}
}
function mainMenu() public {
_mainMenu();
}
function backToMain(uint32 index) public {
index;
_mainMenu();
}
function setWalletBalance(uint128 nanotokens) public {
m_walletBalance = nanotokens;
}
function _mainMenu() private {
MenuItem[] items = [
MenuItem("Stake", "", tvm.functionId(stakeMore)),
MenuItem("View rounds", "", tvm.functionId(showRounds))
];
Menu.select("What would you like to do next?", "", items);
}
function showRounds(uint32 index) public {
index;
for ((uint64 id, RoundsBase.TruncatedRound round): m_rounds) {
RoundStep step = round.step;
string stepDesc;
if (step != RoundStep.PrePooling) {
if (step == RoundStep.Pooling) {
stepDesc = "receiving stakes from participants";
}
if (step == RoundStep.WaitingValidatorRequest) {
stepDesc = "waiting for election request from validator";
}
if (step == RoundStep.WaitingIfStakeAccepted) {
stepDesc = "waiting for answer from elector";
}
if (step == RoundStep.WaitingValidationStart) {
stepDesc = "checking elections result";
}
if (step == RoundStep.WaitingIfValidatorWinElections) {
stepDesc = "checking elections result";
}
if (step == RoundStep.WaitingUnfreeze) {
if (round.completionReason == CompletionReason.Undefined) {
stepDesc = "elections won, validating";
} else {
stepDesc = "elections lost, awaiting the end of the validation period";
}
}
if (step == RoundStep.WaitingReward) {
stepDesc = "requesting for reward";
}
if (step == RoundStep.Completing) {
stepDesc = "completing";
}
if (step == RoundStep.Completed) {
stepDesc = "completed";
}
Terminal.print(0, format("Round {}\nStatus: {}\nStake: {}\nMembers: {}\n",
id, stepDesc, tokensToStr(round.stake), round.participantQty));
}
}
_mainMenu();
}
function stakeMore(uint32 index) public {
index = index;
selectWallet();
}
function showStakeMenu() public {
MenuItem[] items;
items.push( MenuItem("Deposit ordinary stake", "", tvm.functionId(stake)) );
if (m_participantInfo.total != 0) {
items.push( MenuItem("Withdraw stake", "", tvm.functionId(unstake)) );
}
Menu.select("Staking options:", "", items);
}
function stake(uint32 index) public {
index = index;
if (m_walletBalance < m_info.minStake + m_info.stakeFee) {
Terminal.print(0, "Wallet balance is less then required minimal stake.");
gotoDePoolChecks();
return;
}
AmountInput.get(tvm.functionId(setAmount), "How many tokens to stake?", 9, m_info.minStake + m_info.stakeFee, m_walletBalance);
}
function unstake(uint32 index) public {
index = index;
m_instantStake = 0;
if (m_participantInfo.total != 0) {
for ((uint64 id, RoundsBase.TruncatedRound round): m_rounds) {
if (round.step == RoundStep.Pooling) {
optional(uint64) optStake = m_participantInfo.stakes.fetch(id);
if (optStake.hasValue()) {
m_instantStake = optStake.get();
}
}
}
Terminal.print(0, format("Tokens to withdraw: {}\nInstant withdraw: {}\nAlready requested to withdraw: {}",
tokensToStr(m_participantInfo.total), tokensToStr(m_instantStake), tokensToStr(m_participantInfo.withdrawValue)));
Terminal.print(0, "Requested stake will be returned to the wallet after the end of lock-up period.\nBut instant withdrawal will be completed in a couple of seconds.");
ConfirmInput.get(tvm.functionId(unstake2), "Ready to withdraw?");
}
}
function unstake2(bool value) public {
if (!value) {
gotoDePoolChecks();
return;
}
AmountInput.get(tvm.functionId(unstake3), "How many tokens to withdraw?", 9, m_info.minStake, m_participantInfo.total);
}
function unstake3(uint128 value) public view {
optional(uint256) pubkey = 0;
TvmCell payload;
if (value <= m_instantStake) {
payload = tvm.encodeBody(IDepool.withdrawFromPoolingRound, uint64(value));
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_depool, m_info.retOrReinvFee, true, false, payload);
} else {
payload = tvm.encodeBody(IDepool.withdrawPart, uint64(value));
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_depool, m_info.retOrReinvFee, true, false, payload);
}
}
function onSuccess(uint64 transId) public {
transId;
Terminal.print(tvm.functionId(gotoDePoolChecks), "Succeded.");
}
function onError(uint32 sdkError, uint32 exitCode) public {
sdkError = sdkError;
exitCode = exitCode;
Terminal.print(tvm.functionId(gotoDePoolChecks), format("Operation failed."));
}
function setAmount(uint128 value) public {
m_stake = value;
ConfirmInput.get(tvm.functionId(sendStake), format("Stake details.\nAmount: {} (with 0.5 fee tokens).\nConfirm?", tokensToStr(m_stake)));
}
function sendStake(bool value) public {
if (!value) {
_start();
return;
}
optional(uint256) pubkey = 0;
TvmCell body = tvm.encodeBody(IDepool.addOrdinaryStake, uint64(m_stake - m_info.stakeFee));
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_depool, m_stake, true, false, body);
}
function _checkActiveStatus(int8 acc_type, string obj) private returns (bool) {
if (acc_type == -1) {
Terminal.print(0, obj + " is inactive");
return false;
}
if (acc_type == 0) {
Terminal.print(0, obj + " is uninitialized");
return false;
}
if (acc_type == 2) {
Terminal.print(0, obj + " is frozen");
return false;
}
return true;
}
function tokens(uint128 nanotokens) private pure returns (uint64, uint64) {
uint64 decimal = uint64(nanotokens / 1e9);
uint64 float = uint64(nanotokens - (decimal * 1e9));
return (decimal, float);
}
function tokensToStr(uint128 nanotokens) private pure returns (string) {
if (nanotokens == 0) return "0";
(uint64 dec, uint64 float) = tokens(nanotokens);
string floatStr = format("{}", float);
while (floatStr.byteLength() < 9) {
floatStr = "0" + floatStr;
}
string result = format("{}.{}", dec, floatStr);
return result;
}
function _getRounds(uint32 answerId) private view {
RoundsBase(m_depool).getRounds{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getDePoolInfo(uint32 answerId) private view {
IDepool(m_depool).getDePoolInfo{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getParticipants(uint32 answerId) private view {
IDepool(m_depool).getParticipants{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getParticipantInfo(address addr, uint32 answerId) private view {
IDepool(m_depool).getParticipantInfo{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}(addr);
}
function setRounds(mapping(uint64 => RoundsBase.TruncatedRound) rounds) public {
m_rounds = rounds;
}
function setDepoolInfo(
bool poolClosed,
uint64 minStake,
uint64 validatorAssurance,
uint8 participantRewardFraction,
uint8 validatorRewardFraction,
uint64 balanceThreshold,
address validatorWallet,
address[] proxies,
uint64 stakeFee,
uint64 retOrReinvFee,
uint64 proxyFee
) public {
m_info = DepoolInfo(
poolClosed,
minStake,
validatorAssurance,
participantRewardFraction,
validatorRewardFraction,
balanceThreshold,
validatorWallet,
proxies,
stakeFee,
retOrReinvFee,
proxyFee
);
}
function setParticipants(address[] participants) public {
m_participants = participants;
}
function setParticipantInfo(
uint64 total,
uint64 withdrawValue,
bool reinvest,
uint64 reward,
mapping (uint64 => uint64) stakes,
mapping (uint64 => InvestParams) vestings,
mapping (uint64 => InvestParams) locks,
address vestingDonor,
address lockDonor
) public {
m_participantInfo = Participant(total, withdrawValue, reinvest, reward, vestingDonor, lockDonor);
m_participantInfo.stakes = stakes;
m_participantInfo.vestings = vestings;
m_participantInfo.locks = locks;
string roundsDesc;
uint8 count = 0;
string descStr;
for ((uint64 id, uint64 funds) : m_participantInfo.stakes) {
if (funds != 0) {
count += 1;
roundsDesc.append(format("Round #{}: {} tokens.\n", id, tokensToStr(funds)));
}
}
descStr = format("You staked {} tokens in {} round(s):\n{}Your reward is {} tokens.\nReinvestment enabled: {}.",
tokensToStr(total), count, roundsDesc, tokensToStr(reward), reinvest ? "yes" : "no");
Terminal.print(tvm.functionId(showStakeMenu), descStr);
}
function totalParticipantFunds() private view returns (uint64) {
uint64 stakes = 0;
for ((, RoundsBase.TruncatedRound round): m_rounds) {
RoundStep step = round.step;
if (step != RoundStep.Completed) {
stakes += round.stake;
}
}
return stakes;
}
function _findParticipant(address addr) private view returns (bool) {
uint len = m_participants.length;
for(uint i = 0; i < len; i++) {
if (m_participants[i] == addr) {
return true;
}
}
return false;
}
function onCodeUpgrade() internal override {
tvm.resetStorage();
}
//
// Functions for external or internal invoke.
//
function invokeOrdinaryStake(address sender, address depool, uint128 amount) public {
m_stake = amount;
m_wallet = sender;
m_depool = depool;
m_invoked = true;
ConfirmInput.get(tvm.functionId(setInvokeConfirm),
format("I will stake {} TON to DePool {}. Continue?", tokensToStr(amount), depool));
}
function setInvokeConfirm(bool value) public {
if (!value) {
_start();
return;
}
if (m_wallet == address(0)) {
this.selectWallet();
} else {
this.checkWallet(m_wallet);
}
}
function invoke1() public pure {
this.gotoDePoolChecks();
}
function invoke2() public {
if (m_stake < m_info.minStake + m_info.stakeFee) {
Terminal.print(tvm.functionId(Debot.start), "Stake value is less then minimal required stake for this DePool.");
return;
}
this.sendStake(true);
}
//
// Getters
//
function getOrdinaryStakeMessage(address sender, address depool, uint128 amount) public pure
returns(TvmCell message) {
TvmCell body = tvm.encodeBody(this.invokeOrdinaryStake, sender, depool, amount);
TvmBuilder message_;
message_.store(false, true, true, false, address(0), address(this));
message_.storeTons(0);
message_.storeUnsigned(0, 1);
message_.storeTons(0);
message_.storeTons(0);
message_.store(uint64(0));
message_.store(uint32(0));
message_.storeUnsigned(0, 1); //init: nothing$0
message_.storeUnsigned(1, 1); //body: right$1
message_.store(body);
message = message_.toCell();
}
}
|
contract DepoolDebot is Debot, Upgradable, Transferable {
address m_depool;
uint128 m_balance;
address m_wallet;
uint128 m_walletBalance;
uint128 m_stake;
uint128 m_instantStake;
/*
Storage
*/
struct DepoolInfo {
bool poolClosed;
uint64 minStake;
uint64 validatorAssurance;
uint8 participantRewardFraction;
uint8 validatorRewardFraction;
uint64 balanceThreshold;
address validatorWallet;
address[] proxies;
uint64 stakeFee;
uint64 retOrReinvFee;
uint64 proxyFee;
}
struct StakeData {
uint64 stake;
bool reinvest;
address beneficiary;
uint32 total;
uint32 withdrawal;
}
struct Participant {
uint64 total;
uint64 withdrawValue;
bool reinvest;
uint64 reward;
mapping (uint64 => uint64) stakes;
mapping (uint64 => InvestParams) vestings;
mapping (uint64 => InvestParams) locks;
address vestingDonor;
address lockDonor;
}
// target depool rounds
mapping(uint64 => RoundsBase.TruncatedRound) m_rounds;
// tartarget depool participants list
address[] m_participants;
// target depool global parameters
DepoolInfo m_info;
// arguments for depositing stake
StakeData m_stakeData;
// participant address
address m_participant;
// staking details about m_participant
Participant m_participantInfo;
string m_icon;
bool m_invoked;
// Default constructor
function setIcon(string icon) public {
require(msg.pubkey() == tvm.pubkey(), 100);
tvm.accept();
m_icon = icon;
}
function start() public override {
_start();
}
/// @notice Returns Metadata about DeBot.
function getDebotInfo() public functionID(0xDEB) override view returns(
string name, string version, string publisher, string caption, string author,
address support, string hello, string language, string dabi, bytes icon
) {
name = "DePool";
version = "1.3.0";
publisher = "TON Labs";
caption = "DeBot that helps you manage your stakes";
author = "TON Labs";
support = address.makeAddrStd(0, 0x66e01d6df5a8d7677d9ab2daf7f258f1e2a7fe73da5320300395f99e01dc3b5f);
hello = "Hi, I can help you manage your stakes in Depool. I am in development now.";
language = "en";
dabi = m_debotAbi.get();
icon = m_icon;
}
function getRequiredInterfaces() public view override returns (uint256[] interfaces) {
return [ Terminal.ID, AmountInput.ID, Menu.ID, ConfirmInput.ID, AddressInput.ID ];
}
function _start() private {
AddressInput.get(tvm.functionId(setDepool), "Which DePool are you interested in?");
}
function setDepool(address value) public {
m_depool = value;
gotoDePoolChecks();
}
function gotoDePoolChecks() public {
Sdk.getAccountType(tvm.functionId(checkStatus), m_depool);
}
function checkStatus(int8 acc_type) public {
if (!_checkActiveStatus(acc_type, "DePool")) {
_start();
return;
}
Sdk.getAccountCodeHash(tvm.functionId(checkDepoolHash), m_depool);
}
function checkDepoolHash(uint256 code_hash) public {
if (code_hash != 0x14e20e304f53e6da152eb95fffc993dbd28245a775d847eed043f7c78a503885) {
Terminal.print(tvm.functionId(Debot.start), "This is not a DePool v3. Enter another address.");
return;
}
_getRounds(tvm.functionId(setRounds));
_getDePoolInfo(tvm.functionId(setDepoolInfo));
_getParticipants(tvm.functionId(setParticipants));
Sdk.getBalance(tvm.functionId(setBalance), m_depool);
if (m_invoked) {
this.invoke2();
} else {
this.preMain();
}
}
function setBalance(uint128 nanotokens) public {
m_balance = nanotokens;
}
function preMain() public {
uint64 totalStake = totalParticipantFunds();
string totStakeStr = tokensToStr(totalStake);
string valAssuranceStr = tokensToStr(m_info.validatorAssurance);
string minStakeStr = tokensToStr(m_info.minStake);
string result = format("DePool information:\nReward fee: {}%\nLock-up period: {} hours\nParticipants: {}\nBalance: {}\nAssurance: {}\nMin. stake: {}",
m_info.validatorRewardFraction, uint32(54),
m_participants.length, totStakeStr, valAssuranceStr, minStakeStr);
Terminal.print(tvm.functionId(mainMenu), result);
}
function selectWallet() public {
AddressInput.get(tvm.functionId(checkWallet), "What wallet to use to make a stake?");
}
function checkWallet(address value) public {
m_wallet = value;
Sdk.getAccountType(tvm.functionId(checkWallet2), m_wallet);
Sdk.getBalance(tvm.functionId(setWalletBalance), m_wallet);
}
function checkWallet2(int8 acc_type) public {
if (!_checkActiveStatus(acc_type, "Wallet")) return;
if (m_invoked) {
this.invoke1();
} else {
this.checkStake();
}
}
function checkStake() public {
bool exist = _findParticipant(m_wallet);
if (!exist) {
Terminal.print(tvm.functionId(showStakeMenu), "You don't have a stake in this DePool yet.");
} else {
_getParticipantInfo(m_wallet, tvm.functionId(setParticipantInfo));
}
}
function mainMenu() public {
_mainMenu();
}
function backToMain(uint32 index) public {
index;
_mainMenu();
}
function setWalletBalance(uint128 nanotokens) public {
m_walletBalance = nanotokens;
}
function _mainMenu() private {
MenuItem[] items = [
MenuItem("Stake", "", tvm.functionId(stakeMore)),
MenuItem("View rounds", "", tvm.functionId(showRounds))
];
Menu.select("What would you like to do next?", "", items);
}
function showRounds(uint32 index) public {
index;
for ((uint64 id, RoundsBase.TruncatedRound round): m_rounds) {
RoundStep step = round.step;
string stepDesc;
if (step != RoundStep.PrePooling) {
if (step == RoundStep.Pooling) {
stepDesc = "receiving stakes from participants";
}
if (step == RoundStep.WaitingValidatorRequest) {
stepDesc = "waiting for election request from validator";
}
if (step == RoundStep.WaitingIfStakeAccepted) {
stepDesc = "waiting for answer from elector";
}
if (step == RoundStep.WaitingValidationStart) {
stepDesc = "checking elections result";
}
if (step == RoundStep.WaitingIfValidatorWinElections) {
stepDesc = "checking elections result";
}
if (step == RoundStep.WaitingUnfreeze) {
if (round.completionReason == CompletionReason.Undefined) {
stepDesc = "elections won, validating";
} else {
stepDesc = "elections lost, awaiting the end of the validation period";
}
}
if (step == RoundStep.WaitingReward) {
stepDesc = "requesting for reward";
}
if (step == RoundStep.Completing) {
stepDesc = "completing";
}
if (step == RoundStep.Completed) {
stepDesc = "completed";
}
Terminal.print(0, format("Round {}\nStatus: {}\nStake: {}\nMembers: {}\n",
id, stepDesc, tokensToStr(round.stake), round.participantQty));
}
}
_mainMenu();
}
function stakeMore(uint32 index) public {
index = index;
selectWallet();
}
function showStakeMenu() public {
MenuItem[] items;
items.push( MenuItem("Deposit ordinary stake", "", tvm.functionId(stake)) );
if (m_participantInfo.total != 0) {
items.push( MenuItem("Withdraw stake", "", tvm.functionId(unstake)) );
}
Menu.select("Staking options:", "", items);
}
function stake(uint32 index) public {
index = index;
if (m_walletBalance < m_info.minStake + m_info.stakeFee) {
Terminal.print(0, "Wallet balance is less then required minimal stake.");
gotoDePoolChecks();
return;
}
AmountInput.get(tvm.functionId(setAmount), "How many tokens to stake?", 9, m_info.minStake + m_info.stakeFee, m_walletBalance);
}
function unstake(uint32 index) public {
index = index;
m_instantStake = 0;
if (m_participantInfo.total != 0) {
for ((uint64 id, RoundsBase.TruncatedRound round): m_rounds) {
if (round.step == RoundStep.Pooling) {
optional(uint64) optStake = m_participantInfo.stakes.fetch(id);
if (optStake.hasValue()) {
m_instantStake = optStake.get();
}
}
}
Terminal.print(0, format("Tokens to withdraw: {}\nInstant withdraw: {}\nAlready requested to withdraw: {}",
tokensToStr(m_participantInfo.total), tokensToStr(m_instantStake), tokensToStr(m_participantInfo.withdrawValue)));
Terminal.print(0, "Requested stake will be returned to the wallet after the end of lock-up period.\nBut instant withdrawal will be completed in a couple of seconds.");
ConfirmInput.get(tvm.functionId(unstake2), "Ready to withdraw?");
}
}
function unstake2(bool value) public {
if (!value) {
gotoDePoolChecks();
return;
}
AmountInput.get(tvm.functionId(unstake3), "How many tokens to withdraw?", 9, m_info.minStake, m_participantInfo.total);
}
function unstake3(uint128 value) public view {
optional(uint256) pubkey = 0;
TvmCell payload;
if (value <= m_instantStake) {
payload = tvm.encodeBody(IDepool.withdrawFromPoolingRound, uint64(value));
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_depool, m_info.retOrReinvFee, true, false, payload);
} else {
payload = tvm.encodeBody(IDepool.withdrawPart, uint64(value));
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_depool, m_info.retOrReinvFee, true, false, payload);
}
}
function onSuccess(uint64 transId) public {
transId;
Terminal.print(tvm.functionId(gotoDePoolChecks), "Succeded.");
}
function onError(uint32 sdkError, uint32 exitCode) public {
sdkError = sdkError;
exitCode = exitCode;
Terminal.print(tvm.functionId(gotoDePoolChecks), format("Operation failed."));
}
function setAmount(uint128 value) public {
m_stake = value;
ConfirmInput.get(tvm.functionId(sendStake), format("Stake details.\nAmount: {} (with 0.5 fee tokens).\nConfirm?", tokensToStr(m_stake)));
}
function sendStake(bool value) public {
if (!value) {
_start();
return;
}
optional(uint256) pubkey = 0;
TvmCell body = tvm.encodeBody(IDepool.addOrdinaryStake, uint64(m_stake - m_info.stakeFee));
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_depool, m_stake, true, false, body);
}
function _checkActiveStatus(int8 acc_type, string obj) private returns (bool) {
if (acc_type == -1) {
Terminal.print(0, obj + " is inactive");
return false;
}
if (acc_type == 0) {
Terminal.print(0, obj + " is uninitialized");
return false;
}
if (acc_type == 2) {
Terminal.print(0, obj + " is frozen");
return false;
}
return true;
}
function tokens(uint128 nanotokens) private pure returns (uint64, uint64) {
uint64 decimal = uint64(nanotokens / 1e9);
uint64 float = uint64(nanotokens - (decimal * 1e9));
return (decimal, float);
}
function tokensToStr(uint128 nanotokens) private pure returns (string) {
if (nanotokens == 0) return "0";
(uint64 dec, uint64 float) = tokens(nanotokens);
string floatStr = format("{}", float);
while (floatStr.byteLength() < 9) {
floatStr = "0" + floatStr;
}
string result = format("{}.{}", dec, floatStr);
return result;
}
function _getRounds(uint32 answerId) private view {
RoundsBase(m_depool).getRounds{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getDePoolInfo(uint32 answerId) private view {
IDepool(m_depool).getDePoolInfo{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getParticipants(uint32 answerId) private view {
IDepool(m_depool).getParticipants{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getParticipantInfo(address addr, uint32 answerId) private view {
IDepool(m_depool).getParticipantInfo{
abiVer: 2,
extMsg: true,
sign: false,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}(addr);
}
function setRounds(mapping(uint64 => RoundsBase.TruncatedRound) rounds) public {
m_rounds = rounds;
}
function setDepoolInfo(
bool poolClosed,
uint64 minStake,
uint64 validatorAssurance,
uint8 participantRewardFraction,
uint8 validatorRewardFraction,
uint64 balanceThreshold,
address validatorWallet,
address[] proxies,
uint64 stakeFee,
uint64 retOrReinvFee,
uint64 proxyFee
) public {
m_info = DepoolInfo(
poolClosed,
minStake,
validatorAssurance,
participantRewardFraction,
validatorRewardFraction,
balanceThreshold,
validatorWallet,
proxies,
stakeFee,
retOrReinvFee,
proxyFee
);
}
function setParticipants(address[] participants) public {
m_participants = participants;
}
function setParticipantInfo(
uint64 total,
uint64 withdrawValue,
bool reinvest,
uint64 reward,
mapping (uint64 => uint64) stakes,
mapping (uint64 => InvestParams) vestings,
mapping (uint64 => InvestParams) locks,
address vestingDonor,
address lockDonor
) public {
m_participantInfo = Participant(total, withdrawValue, reinvest, reward, vestingDonor, lockDonor);
m_participantInfo.stakes = stakes;
m_participantInfo.vestings = vestings;
m_participantInfo.locks = locks;
string roundsDesc;
uint8 count = 0;
string descStr;
for ((uint64 id, uint64 funds) : m_participantInfo.stakes) {
if (funds != 0) {
count += 1;
roundsDesc.append(format("Round #{}: {} tokens.\n", id, tokensToStr(funds)));
}
}
descStr = format("You staked {} tokens in {} round(s):\n{}Your reward is {} tokens.\nReinvestment enabled: {}.",
tokensToStr(total), count, roundsDesc, tokensToStr(reward), reinvest ? "yes" : "no");
Terminal.print(tvm.functionId(showStakeMenu), descStr);
}
function totalParticipantFunds() private view returns (uint64) {
uint64 stakes = 0;
for ((, RoundsBase.TruncatedRound round): m_rounds) {
RoundStep step = round.step;
if (step != RoundStep.Completed) {
stakes += round.stake;
}
}
return stakes;
}
function _findParticipant(address addr) private view returns (bool) {
uint len = m_participants.length;
for(uint i = 0; i < len; i++) {
if (m_participants[i] == addr) {
return true;
}
}
return false;
}
function onCodeUpgrade() internal override {
tvm.resetStorage();
}
//
// Functions for external or internal invoke.
//
function invokeOrdinaryStake(address sender, address depool, uint128 amount) public {
m_stake = amount;
m_wallet = sender;
m_depool = depool;
m_invoked = true;
ConfirmInput.get(tvm.functionId(setInvokeConfirm),
format("I will stake {} TON to DePool {}. Continue?", tokensToStr(amount), depool));
}
function setInvokeConfirm(bool value) public {
if (!value) {
_start();
return;
}
if (m_wallet == address(0)) {
this.selectWallet();
} else {
this.checkWallet(m_wallet);
}
}
function invoke1() public pure {
this.gotoDePoolChecks();
}
function invoke2() public {
if (m_stake < m_info.minStake + m_info.stakeFee) {
Terminal.print(tvm.functionId(Debot.start), "Stake value is less then minimal required stake for this DePool.");
return;
}
this.sendStake(true);
}
//
// Getters
//
function getOrdinaryStakeMessage(address sender, address depool, uint128 amount) public pure
returns(TvmCell message) {
TvmCell body = tvm.encodeBody(this.invokeOrdinaryStake, sender, depool, amount);
TvmBuilder message_;
message_.store(false, true, true, false, address(0), address(this));
message_.storeTons(0);
message_.storeUnsigned(0, 1);
message_.storeTons(0);
message_.storeTons(0);
message_.store(uint64(0));
message_.store(uint32(0));
message_.storeUnsigned(0, 1); //init: nothing$0
message_.storeUnsigned(1, 1); //body: right$1
message_.store(body);
message = message_.toCell();
}
}
| 5,758
|
6
|
// enable voting
|
uint256 mask = 1 << 3;
uint256 currentData = VoterData[_address];
VoterData[_address] = currentData | mask;
|
uint256 mask = 1 << 3;
uint256 currentData = VoterData[_address];
VoterData[_address] = currentData | mask;
| 5,418
|
18
|
// 获取课件的上传信息
|
function getCourseUploadInfo(uint256 _id) public view returns (string[] memory, string[] memory){
string[] memory names = Filenames[_id];
uint sum = 0;
for (uint i = 0; i < names.length; i++) {
string memory filename = names[i];
if (Files[_id][filename].enable) {
sum++;
}
}
string[] memory paths = new string[](sum);
uint j = 0;
for (uint i = 0; i < names.length; i++) {
string memory filename = names[i];
if (Files[_id][filename].enable) {
paths[j] = Files[_id][filename].Path;
j++;
}
}
return (paths, names);
}
|
function getCourseUploadInfo(uint256 _id) public view returns (string[] memory, string[] memory){
string[] memory names = Filenames[_id];
uint sum = 0;
for (uint i = 0; i < names.length; i++) {
string memory filename = names[i];
if (Files[_id][filename].enable) {
sum++;
}
}
string[] memory paths = new string[](sum);
uint j = 0;
for (uint i = 0; i < names.length; i++) {
string memory filename = names[i];
if (Files[_id][filename].enable) {
paths[j] = Files[_id][filename].Path;
j++;
}
}
return (paths, names);
}
| 24,409
|
281
|
// Gets the price for `identifier` and `time` if it has already been requested and resolved. If the price is not available, the method reverts. identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. time unix timestamp for the price request.return int256 representing the resolved price for the given identifier and timestamp. /
|
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
|
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
| 26,779
|
14
|
// ensure that the signature is on the proper updater
|
require(
Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater),
"!current updater"
);
|
require(
Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater),
"!current updater"
);
| 19,094
|
4
|
// Distribution Model Parameter editer
|
event SetRewardParams(uint256 rewardPerBlock, uint256 decrementUnitPerBlock);
event RegisterRewardParams(uint256 atBlockNumber, uint256 rewardPerBlock, uint256 decrementUnitPerBlock);
event DeleteRegisterRewardParams(uint256 index, uint256 atBlockNumber, uint256 rewardPerBlock, uint256 decrementUnitPerBlock, uint256 arrayLen);
|
event SetRewardParams(uint256 rewardPerBlock, uint256 decrementUnitPerBlock);
event RegisterRewardParams(uint256 atBlockNumber, uint256 rewardPerBlock, uint256 decrementUnitPerBlock);
event DeleteRegisterRewardParams(uint256 index, uint256 atBlockNumber, uint256 rewardPerBlock, uint256 decrementUnitPerBlock, uint256 arrayLen);
| 13,987
|
61
|
// Trade Dai for Ether using reserves.
|
totalDaiSold = _tradeDaiForEther(
daiAmountFromReserves, quotedEtherAmount, deadline, true
);
|
totalDaiSold = _tradeDaiForEther(
daiAmountFromReserves, quotedEtherAmount, deadline, true
);
| 19,367
|
2
|
// NOLINTNEXTLINE: low-level-calls.
|
(bool success, bytes memory returndata) = tokenAddress.call(callData);
require(success, string(returndata));
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED");
}
|
(bool success, bytes memory returndata) = tokenAddress.call(callData);
require(success, string(returndata));
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED");
}
| 18,348
|
22
|
// update
|
guardian = newGuardian;
|
guardian = newGuardian;
| 48,090
|
80
|
// ability for controller to step down
|
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
|
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
| 6,588
|
20
|
// Check that the auction endTime has not already passed.
|
require(
idToMarketItem[tokenId].endTime > block.timestamp,
"This auction has ended."
);
|
require(
idToMarketItem[tokenId].endTime > block.timestamp,
"This auction has ended."
);
| 33,096
|
12
|
// Transfer all eth in this contract address to another address _to The eth will be send to this address/
|
function msReclaimEther(address _to) external onlyOwner returns(bool success) {
_initOrSignOwnerAction("msReclaimEther");
if (ownerAction.approveSigs > 1) {
_to.transfer(address(this).balance);
emit ActionExecuted("msReclaimEther");
_deleteOwnerActon();
return true;
}
}
|
function msReclaimEther(address _to) external onlyOwner returns(bool success) {
_initOrSignOwnerAction("msReclaimEther");
if (ownerAction.approveSigs > 1) {
_to.transfer(address(this).balance);
emit ActionExecuted("msReclaimEther");
_deleteOwnerActon();
return true;
}
}
| 27,273
|
21
|
// ------------------------------------------------------------------------ Transfer the balance from token owner's account to to account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
|
function transfer(address _to, uint _tokens) public afterFrozenDeadline returns (bool success) {
require(now > frozenAccountByOwner[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender], _tokens);
balances[_to] = safeAdd(balances[_to], _tokens);
emit Transfer(msg.sender, _to, _tokens);
return true;
}
|
function transfer(address _to, uint _tokens) public afterFrozenDeadline returns (bool success) {
require(now > frozenAccountByOwner[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender], _tokens);
balances[_to] = safeAdd(balances[_to], _tokens);
emit Transfer(msg.sender, _to, _tokens);
return true;
}
| 33,419
|
4
|
// Minor adaptation on `factory` and `WETH` to help conform to compiler bump.
|
interface IUniswapV2Router01x {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
|
interface IUniswapV2Router01x {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
| 33,452
|
49
|
// Initial distribution
|
uint96 pixTreasuryDist = 20000 * 1e18;
uint96 dflectTreasuryDist = 15000 * 1e18;
|
uint96 pixTreasuryDist = 20000 * 1e18;
uint96 dflectTreasuryDist = 15000 * 1e18;
| 24,605
|
50
|
// Cannot safely transfer to a contract that does not implement theERC721Receiver interface. /
|
error TransferToNonERC721ReceiverImplementer();
|
error TransferToNonERC721ReceiverImplementer();
| 1,025
|
95
|
// Clear the stake state for a wallet and a rarity./
|
function _clearStake(address wallet, address _erc20Token, uint256 _tokenRarity) internal {
stakingsMap[wallet][_erc20Token][_tokenRarity].endDate = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].tokenImage = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].tokenBackground = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].alohaAmount = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].erc20Amount = 0;
}
|
function _clearStake(address wallet, address _erc20Token, uint256 _tokenRarity) internal {
stakingsMap[wallet][_erc20Token][_tokenRarity].endDate = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].tokenImage = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].tokenBackground = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].alohaAmount = 0;
stakingsMap[wallet][_erc20Token][_tokenRarity].erc20Amount = 0;
}
| 38,144
|
512
|
// Save current value for inclusion in log
|
address oldBorrowCapGuardian = borrowCapGuardian;
|
address oldBorrowCapGuardian = borrowCapGuardian;
| 1,038
|
22
|
// the structure to track all the members in the DAO
|
uint256 flags; // flags to track the state of the member: exists, etc
|
uint256 flags; // flags to track the state of the member: exists, etc
| 31,406
|
0
|
// IFakeERC173Facet/Martin Wawrusch for Roji Inc./Exposes an ERC173 ownership facet. The actual ownership is handled differently, this is only used for OpenSea and similar indexers
|
interface IFakeERC173Facet {
/// @dev This emits when ownership of a contract changes.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice Get the address of the owner
/// @return The address of the owner.
function owner() view external returns(address);
/// @notice Set the address of the new owner of the contract
/// @dev Set _newOwner to address(0) to renounce any ownership.
/// @param _newOwner The address of the new owner of the contract
function transferOwnership(address _newOwner) external;
}
|
interface IFakeERC173Facet {
/// @dev This emits when ownership of a contract changes.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice Get the address of the owner
/// @return The address of the owner.
function owner() view external returns(address);
/// @notice Set the address of the new owner of the contract
/// @dev Set _newOwner to address(0) to renounce any ownership.
/// @param _newOwner The address of the new owner of the contract
function transferOwnership(address _newOwner) external;
}
| 15,153
|
55
|
// uint256 constant public REFERRAL_PERCENTS = 1e11;
|
uint256 public REFERRAL_PERCENTS = 1e11;
uint256 constant public TIME_STEP = 1 days ; //days
uint256 constant public BASE_AMOUNT_DALIY = 1e11; // 10w USDT
uint256 constant public START_POINT = 1606828881; // Singapore time at: 2020-11-11 11:11:11
uint256 constant public PERCENT_INVEST = 10; // increase percent pre Invest
uint256 constant public PERCENT_WITHDRAW = 15; // decreased percent pre Withdraw
uint256 public presentPercent = 1e12;
|
uint256 public REFERRAL_PERCENTS = 1e11;
uint256 constant public TIME_STEP = 1 days ; //days
uint256 constant public BASE_AMOUNT_DALIY = 1e11; // 10w USDT
uint256 constant public START_POINT = 1606828881; // Singapore time at: 2020-11-11 11:11:11
uint256 constant public PERCENT_INVEST = 10; // increase percent pre Invest
uint256 constant public PERCENT_WITHDRAW = 15; // decreased percent pre Withdraw
uint256 public presentPercent = 1e12;
| 77,907
|
149
|
// stake into LiquidityGauge
|
uint lpBal = IERC20(LP).balanceOf(address(this));
if (lpBal > 0) {
IERC20(LP).safeApprove(GAUGE, 0);
IERC20(LP).safeApprove(GAUGE, lpBal);
LiquidityGauge(GAUGE).deposit(lpBal);
}
|
uint lpBal = IERC20(LP).balanceOf(address(this));
if (lpBal > 0) {
IERC20(LP).safeApprove(GAUGE, 0);
IERC20(LP).safeApprove(GAUGE, lpBal);
LiquidityGauge(GAUGE).deposit(lpBal);
}
| 15,633
|
15
|
// This shouldn't fail.
|
require(
block.timestamp - lastObservation.timestamp >= MIN_TWAP_TIME,
"UniswapV2PriceOracle: Bad TWAP time."
);
uint256 px0Cumulative = price0Cumulative(pair);
unchecked {
|
require(
block.timestamp - lastObservation.timestamp >= MIN_TWAP_TIME,
"UniswapV2PriceOracle: Bad TWAP time."
);
uint256 px0Cumulative = price0Cumulative(pair);
unchecked {
| 32,420
|
7
|
// Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. /
|
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
|
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
| 9,826
|
17
|
// Transfers Governance of the contract to a new account (`newGovernor`).Can only be called by the current Governor. Must be claimed for this to complete _newGovernor Address of the new Governor /
|
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
|
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
| 28,300
|
42
|
// Arrays of 31 bytes or less have an even value in their slot, while longer arrays have an odd value. The actual length is the slot divided by two for odd values, and the lowest order byte divided by two for even values. If the slot is even, bitwise and the slot with 255 and divide by two to get the length. If the slot is odd, bitwise and the slot with -1 and divide by two.
|
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
|
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
| 28,535
|
103
|
// validates reserve weight
|
modifier validReserveWeight(uint32 _weight) {
_validReserveWeight(_weight);
_;
}
|
modifier validReserveWeight(uint32 _weight) {
_validReserveWeight(_weight);
_;
}
| 36,801
|
178
|
// Assets supported by the Vault, i.e. Stablecoins
|
struct Asset {
bool isSupported;
}
|
struct Asset {
bool isSupported;
}
| 75,086
|
118
|
// Future proof storage
|
mapping(bytes32 => AdditionalStorage) additionalStorage;
|
mapping(bytes32 => AdditionalStorage) additionalStorage;
| 1,207
|
16
|
// Fetching all market items.
|
function fetchMarketItems() public view returns (MarketItem[] memory) {
uint256 itemCount = _itemIds.current();
uint256 unsoldItemCount = _itemIds.current() - _itemsSold.current();
uint256 currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for (uint256 i = 0; i < itemCount; i++) {
if (idToMarketItem[i + 1].owner == address(0)) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
|
function fetchMarketItems() public view returns (MarketItem[] memory) {
uint256 itemCount = _itemIds.current();
uint256 unsoldItemCount = _itemIds.current() - _itemsSold.current();
uint256 currentIndex = 0;
MarketItem[] memory items = new MarketItem[](unsoldItemCount);
for (uint256 i = 0; i < itemCount; i++) {
if (idToMarketItem[i + 1].owner == address(0)) {
uint256 currentId = idToMarketItem[i + 1].itemId;
MarketItem storage currentItem = idToMarketItem[currentId];
items[currentIndex] = currentItem;
currentIndex += 1;
}
}
return items;
}
| 37,691
|
247
|
// internal function that transfers ETH Calling conditions: - Only the owner of the smart contract i.e Unicus platform transfer ETH bidder_ Address where the ETH will be transfered amount_ amount of the ETH that will be transfered /
|
function _transferETH(address bidder_, uint256 amount_) private onlyOwner {
require(amount_ > 0, "Amount to transfer should not be zero.");
(bool success,bytes memory data ) = payable(bidder_).call{value:amount_,gas:_GAS_LIMIT}("");
emit EthPaymentSuccess(success,data,address(this), bidder_, amount_);
require(success, "Transfer failed.");
}
|
function _transferETH(address bidder_, uint256 amount_) private onlyOwner {
require(amount_ > 0, "Amount to transfer should not be zero.");
(bool success,bytes memory data ) = payable(bidder_).call{value:amount_,gas:_GAS_LIMIT}("");
emit EthPaymentSuccess(success,data,address(this), bidder_, amount_);
require(success, "Transfer failed.");
}
| 11,981
|
6
|
// ProofPresale ProofPresale allows investors to maketoken purchases and assigns them tokens basedon a token per ETH rate. Funds collected are forwarded to a wallet as they arrive. /
|
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
| 5,806
|
34
|
// `balances` is the map that tracks the balance of each address, in thiscontract when the balance changes the block number that the changeoccurred is also included in the map
|
mapping (address => Checkpoint[]) balances;
|
mapping (address => Checkpoint[]) balances;
| 19,871
|
28
|
// Ensure Issuer contract can suspend issuance - see SIP-165;
|
systemstatus_i.updateAccessControl("Issuance", new_Issuer_contract, true, false);
|
systemstatus_i.updateAccessControl("Issuance", new_Issuer_contract, true, false);
| 30,000
|
26
|
// Encodes calldata for startBridgeTokensViaCBridgeNativePacked/transactionId Custom transaction ID for tracking/receiver Receiving wallet address/destinationChainId Receiving chain/nonce A number input to guarantee uniqueness of transferId./maxSlippage Destination swap minimal accepted amount
|
function encode_startBridgeTokensViaCBridgeNativePacked(
bytes32 transactionId,
address receiver,
uint64 destinationChainId,
uint64 nonce,
uint32 maxSlippage
|
function encode_startBridgeTokensViaCBridgeNativePacked(
bytes32 transactionId,
address receiver,
uint64 destinationChainId,
uint64 nonce,
uint32 maxSlippage
| 11,688
|
7
|
// tracking events
|
event newOraclizeQuery(string description);
event newPriceTicker(uint price);
event Deposit(address _from, uint256 _value, bytes32 _horse, uint256 _date);
event Withdraw(address _to, uint256 _value);
|
event newOraclizeQuery(string description);
event newPriceTicker(uint price);
event Deposit(address _from, uint256 _value, bytes32 _horse, uint256 _date);
event Withdraw(address _to, uint256 _value);
| 14,082
|
70
|
// Returns the multiplication of two signed integers, reverting onoverflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow. /
|
function mul(int256 a, int256 b) internal pure returns (int256) {
return a * b;
}
|
function mul(int256 a, int256 b) internal pure returns (int256) {
return a * b;
}
| 39,833
|
4
|
// Deposits `amount` of `token` into the specified `DelegationShare`, with the resultant shares credited to `depositor` delegationShare is the specified shares record where investment is to be made, token is the ERC20 token in which the investment is to be made, amount is the amount of token to be invested in the delegationShare by the depositor /
|
function depositInto(IDelegationShare delegationShare, IERC20 token, uint256 amount)
external
returns (uint256);
|
function depositInto(IDelegationShare delegationShare, IERC20 token, uint256 amount)
external
returns (uint256);
| 4,035
|
26
|
// Get the current mint fee. Returns the current transfer amount required to minta new token. /
|
function mintFee() public view returns (uint) {
return _mintFee;
}
|
function mintFee() public view returns (uint) {
return _mintFee;
}
| 80,469
|
104
|
// if round has ended.but round end has not been run (so contract has not distributed winnings)
|
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
|
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
| 7,651
|
3
|
// limit our copy to 256 bytes
|
_toCopy := returndatasize()
if gt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
|
_toCopy := returndatasize()
if gt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
| 361
|
159
|
// Get current balance of the deposit token before withdrawal
|
uint256 depositTokenBalanceBeforeWithdrawal = ERC20Wrapper.balanceOf(depositTokenAddress, address(this));
|
uint256 depositTokenBalanceBeforeWithdrawal = ERC20Wrapper.balanceOf(depositTokenAddress, address(this));
| 47,609
|
227
|
// get the actual weapon class and greatness
|
uint256 rand = random(string(abi.encodePacked("WEAPON", toString(tokenId))));
string memory output = sourceArray[rand % sourceArray.length];
uint256 greatness = rand % 21;
uint256 stat;
if (keccak256(abi.encodePacked((output))) == keccak256(abi.encodePacked(("Warhammer")))) {
stat = getScore(bases[0][baseIndex], tokenId, keyPrefix);
} else if (keccak256(abi.encodePacked((output))) == keccak256(abi.encodePacked(("Quarterstaff")))) {
|
uint256 rand = random(string(abi.encodePacked("WEAPON", toString(tokenId))));
string memory output = sourceArray[rand % sourceArray.length];
uint256 greatness = rand % 21;
uint256 stat;
if (keccak256(abi.encodePacked((output))) == keccak256(abi.encodePacked(("Warhammer")))) {
stat = getScore(bases[0][baseIndex], tokenId, keyPrefix);
} else if (keccak256(abi.encodePacked((output))) == keccak256(abi.encodePacked(("Quarterstaff")))) {
| 37,048
|
13
|
// Setup has to complete successfully or transaction fails.
|
require(executeDelegateCall(to, data, gasleft()), 'Could not finish initialization');
|
require(executeDelegateCall(to, data, gasleft()), 'Could not finish initialization');
| 30,928
|
60
|
// get owner addressreturn address owner /
|
function getOwner() external override view returns (address) {
return owner();
}
|
function getOwner() external override view returns (address) {
return owner();
}
| 12,159
|
7
|
// Add a value to a set. O(1). Returns true if the value was added to the set, that is if it was notalready present. /
|
function approve(address spender, uint256 tokens)
public
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success);
|
function approve(address spender, uint256 tokens)
public
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) public returns (bool success);
| 48,739
|
118
|
// Transfer tax rate in basis points. (default 5%)
|
uint16 public transferTaxRate = 500;
|
uint16 public transferTaxRate = 500;
| 17,722
|
2
|
// Solidity only automatically asserts when dividing by 0
|
require(b > 0);
uint256 c = a / b;
|
require(b > 0);
uint256 c = a / b;
| 23,459
|
26
|
// Total amount of tokens
|
uint256 private totalTokens;
|
uint256 private totalTokens;
| 82,240
|
15
|
// Final amount of tokens returned to issuer
|
uint256 public finalAmountReturned;
|
uint256 public finalAmountReturned;
| 25,473
|
38
|
// Token being sold
|
ERC20 public constant TOKEN = ERC20(TOKEN_ADDRESS);
|
ERC20 public constant TOKEN = ERC20(TOKEN_ADDRESS);
| 19,232
|
10
|
// internal approve functionality. needed, so we can check the payloadsize if called externally, but smaller payload allowed internally /
|
function _approve(address _spender, uint _value) internal returns(bool success) {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowance[msg.sender][_spender] == 0));
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
|
function _approve(address _spender, uint _value) internal returns(bool success) {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowance[msg.sender][_spender] == 0));
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
| 3,014
|
312
|
// Uniswap V2 ============================================
|
// {
// uint256 total_frax_reserves;
// (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves());
// if (frax_is_token0) total_frax_reserves = reserve0;
// else total_frax_reserves = reserve1;
// frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply();
// }
|
// {
// uint256 total_frax_reserves;
// (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves());
// if (frax_is_token0) total_frax_reserves = reserve0;
// else total_frax_reserves = reserve1;
// frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply();
// }
| 50,462
|
79
|
// The traditional divUp formula is: divUp(x, y) := (x + y - 1) / y To avoid intermediate overflow in the addition, we distribute the division and get: divUp(x, y) := (x - 1) / y + 1 Note that this requires x != 0, which we already tested for.
|
return ((product - 1) / ONE) + 1;
|
return ((product - 1) / ONE) + 1;
| 13,330
|
2
|
// Deploy the proposal contract for a campaign. _manager The campaign manager address. Can only be called by an existing campaign contract. /
|
function deployProposalContract(address _manager) external;
|
function deployProposalContract(address _manager) external;
| 38,963
|
50
|
// An external method that get infomation of the fighter/_tokenId The ID of the fighter.
|
function getFighter(uint _tokenId) external view returns (uint32) {
RabbitData storage rbt = rabbits[_tokenId];
uint32 strength = uint32(rbt.explosive + rbt.endurance + rbt.nimble);
return strength;
}
|
function getFighter(uint _tokenId) external view returns (uint32) {
RabbitData storage rbt = rabbits[_tokenId];
uint32 strength = uint32(rbt.explosive + rbt.endurance + rbt.nimble);
return strength;
}
| 24,981
|
94
|
// Permits this contract to spend on a users behalf, and deposits into the prize pool./The Dai permit params match the Daipermit function, but it expects the `spender` to be/ the address of this contract./holder The address spending the tokens/nonce The nonce of the tx.Should be retrieved from the Dai token/expiry The timestamp at which the sig expires/allowed If true, then the spender is approving holder the max allowance.False makes the allowance zero./v The `v` portion of the signature./r The `r` portion of the signature./s The `s` portion of the signature./prizePool The prize pool to deposit into/to The address that will
|
function permitAndDepositTo(
|
function permitAndDepositTo(
| 67,220
|
370
|
// Change delegation for `delegator` to `delegatee`.
|
* Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
|
* Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
| 32,213
|
22
|
// If `_token` is a zero address then the order will treat it as being WETH./_bidder Address that placed the bid./_tokenContractAddress The ERC721 asset contract address./_tokenId ID of the desired ERC721 asset./_expiration Time of order expiration defined as a UNIX timestamp./_offer The offered amount in wei for the given ERC721 asset./_token Alternative ERC20 asset used for payment.
|
function exerciseBuyOrder(
address payable _bidder,
address _tokenContractAddress,
uint256 _tokenId,
uint256 _expiration,
uint256 _offer,
address _token
) external payable;
|
function exerciseBuyOrder(
address payable _bidder,
address _tokenContractAddress,
uint256 _tokenId,
uint256 _expiration,
uint256 _offer,
address _token
) external payable;
| 26,742
|
64
|
// Termination of the pool // Exit a terminated pool _user the user to exit from the pool only pt are required as therearen't any new FYTs /
|
function exitTerminatedFuture(address _user) external nonReentrant onlyController {
require(terminated, "FutureVault: ERR_NOT_TERMINATED");
uint256 amount = pt.balanceOf(_user);
require(amount > 0, "FutureVault: ERR_PT_BALANCE");
_withdraw(_user, amount);
emit FundsWithdrawn(_user, amount);
}
|
function exitTerminatedFuture(address _user) external nonReentrant onlyController {
require(terminated, "FutureVault: ERR_NOT_TERMINATED");
uint256 amount = pt.balanceOf(_user);
require(amount > 0, "FutureVault: ERR_PT_BALANCE");
_withdraw(_user, amount);
emit FundsWithdrawn(_user, amount);
}
| 20,495
|
118
|
// calculate the amount of tokens the customer receives over his purchase
|
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
|
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
| 15,865
|
134
|
// Empty donations are disallowed.
|
uint balance = state.balanceOf(sender);
require(balance != 0);
|
uint balance = state.balanceOf(sender);
require(balance != 0);
| 25,600
|
6
|
// transfer funds to owner
|
items[index].owner.transfer(msg.value);
|
items[index].owner.transfer(msg.value);
| 12,423
|
37
|
// start and end timestamps where investments are allowed (both inclusive)
|
uint256 public startTime;
uint256 public endTime;
|
uint256 public startTime;
uint256 public endTime;
| 7,850
|
2
|
// check if a hash is in the merkle tree for rootHash rootHash the merkle root index the index of the node to check hash the hash to check proofHashes the proof, i.e. the sequence of siblings from the node to root /
|
function validProof(
bytes32 rootHash,
uint256 index,
bytes32 hash,
bytes32[] memory proofHashes
|
function validProof(
bytes32 rootHash,
uint256 index,
bytes32 hash,
bytes32[] memory proofHashes
| 27,660
|
10
|
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.:// ETH OPERATIONS //.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Sends `amount` (in wei) ETH to `to`./ Reverts upon failure.
|
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and check if it succeeded or not.
if iszero(call(gas(), to, amount, 0, 0, 0, 0)) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
|
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and check if it succeeded or not.
if iszero(call(gas(), to, amount, 0, 0, 0, 0)) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
| 5,515
|
38
|
// Withdraw ethereum for a specified address _to The address to transfer to _value The amount to be transferred /
|
function withdraw(address _to, uint256 _value) onlyOwner public returns (bool) {
require(_to != address(0));
require(_value <= address(this).balance);
_to.transfer(_value);
return true;
}
|
function withdraw(address _to, uint256 _value) onlyOwner public returns (bool) {
require(_to != address(0));
require(_value <= address(this).balance);
_to.transfer(_value);
return true;
}
| 66,819
|
16
|
// MAINNET ADDRESSES The contracts in this list should correspond to MCD core contracts, verify against the current release list at: https:changelog.makerdao.com/releases/mainnet/1.1.0/contracts.json
|
address constant MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address constant MCD_VOW = 0xA950524441892A31ebddF91d3cEEFa04Bf454466;
address constant MCD_ADM = 0x9eF05f7F6deB616fd37aC3c959a2dDD25A54E4F5;
address constant MCD_END = 0xaB14d3CE3F733CACB76eC2AbE7d2fcb00c99F3d5;
address constant FLIPPER_MOM = 0xc4bE7F74Ee3743bDEd8E0fA218ee5cf06397f472;
address constant MCD_CAT = 0xa5679C04fc3d9d8b0AaB1F0ab83555b301cA70Ea;
address constant MCD_CAT_OLD = 0x78F2c2AF65126834c51822F56Be0d7469D7A523E;
address constant MCD_FLIP_ETH_A = 0xF32836B9E1f47a0515c6Ec431592D5EbC276407f;
|
address constant MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address constant MCD_VOW = 0xA950524441892A31ebddF91d3cEEFa04Bf454466;
address constant MCD_ADM = 0x9eF05f7F6deB616fd37aC3c959a2dDD25A54E4F5;
address constant MCD_END = 0xaB14d3CE3F733CACB76eC2AbE7d2fcb00c99F3d5;
address constant FLIPPER_MOM = 0xc4bE7F74Ee3743bDEd8E0fA218ee5cf06397f472;
address constant MCD_CAT = 0xa5679C04fc3d9d8b0AaB1F0ab83555b301cA70Ea;
address constant MCD_CAT_OLD = 0x78F2c2AF65126834c51822F56Be0d7469D7A523E;
address constant MCD_FLIP_ETH_A = 0xF32836B9E1f47a0515c6Ec431592D5EbC276407f;
| 57,089
|
0
|
// Generate a unique ID for an execution request _to address being called (msg.sender) _value ether being sent (msg.value) _data ABI encoded call data (msg.data) /
|
function execute(address _to, uint256 _value, bytes _data)
public
whenNotPaused
returns (uint256 executionId)
|
function execute(address _to, uint256 _value, bytes _data)
public
whenNotPaused
returns (uint256 executionId)
| 28,301
|
35
|
// Add a beneficiary for the airdrop. _beneficiary The address of the beneficiary /
|
function addBeneficiary(address _beneficiary) private
|
function addBeneficiary(address _beneficiary) private
| 38,453
|
175
|
// cr / (1 - c) <= x <= b
|
uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol));
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
|
uint repayAmount = redeemAmount.mul(safeCol).div(uint(1e18).sub(safeCol));
if (repayAmount > borrowed) {
repayAmount = borrowed;
}
| 43,855
|
0
|
// Indicated the highest level of bug found in the version/
|
enum BugLevel {NONE, LOW, MEDIUM, HIGH, CRITICAL}
|
enum BugLevel {NONE, LOW, MEDIUM, HIGH, CRITICAL}
| 1,222
|
5
|
// Transfers a specific NFT (`tokenId`) from one account (`from`) toanother (`to`). Requirements:- `from`, `to` cannot be zero.- `tokenId` must be owned by `from`.- If the caller is not `from`, it must be have been allowed to move this
|
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
|
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 39,805
|
29
|
// origin vesting contracts have different dateswe need to add 2 weeks to get end of period (by default, it's start)
|
if (adjustedDate != date) {
date = adjustedDate + TWO_WEEKS;
}
|
if (adjustedDate != date) {
date = adjustedDate + TWO_WEEKS;
}
| 19,227
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.