contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | setDeviationThreshold | function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
| /**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
12717,
13044
]
} | 59,661 |
||
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | setRetargetThreshold | function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
| // Sets the retarget threshold parameter, Gov only. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
13420,
13611
]
} | 59,662 |
||
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | setTargetStock2Flow | function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
| // Overwrites the target stock-to-flow ratio, Gov only. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
13672,
13857
]
} | 59,663 |
||
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | setRebaseTimingParameters | function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
| /**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
14543,
15067
]
} | 59,664 |
||
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | addPool | function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
| // Passthrough function to add pool. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
15109,
15299
]
} | 59,665 |
||
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | setPool | function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
| // Passthrough function to set pool. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
15341,
15500
]
} | 59,666 |
||
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | setTipRate | function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
| // Passthrough function to set tip rate. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
15546,
15641
]
} | 59,667 |
||
ChefMao | contracts\ChefMao.sol | 0xfbd3749eb2ed67454850939480433e71a9f5432d | Solidity | ChefMao | contract ChefMao {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov, 'onlyGov: caller is not gov');
_;
}
// an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
// an event emitted when deviationMovement is changed
event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement);
// Event emitted when pendingGov is changed
event NewPendingGov(address oldPendingGov, address newPendingGov);
// Event emitted when gov is changed
event NewGov(address oldGov, address newGov);
// Governance address
address public gov;
// Pending Governance address
address public pendingGov;
// Peg target
uint256 public targetPrice;
// POT Tokens created per block at inception.
// POT's inflation will eventually be governed by targetStock2Flow.
uint256 public farmHotpotBasePerBlock;
// Halving period for Hotpot Base per block, in blocks.
uint256 public halfLife = 88888;
// targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000)
// 2,400,000 is ~1-year's ETH block count as of Sep 2020
// See @100trillionUSD's article below on Scarcity and S2F:
// https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25
//
// Ganularity of targetStock2Flow is intentionally restricted.
uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation;
// If the current price is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the price.
// (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change.
uint256 public deviationThreshold = 5e16; // 5%
uint256 public deviationMovement = 5e16; // 5%
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec = 24 hours;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestamp;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec = 3600; // 60 minutes
// The number of rebase cycles since inception
uint256 public epoch;
// The number of halvings since inception
uint256 public halvingCounter;
// The number of consecutive upward threshold breaching when rebasing.
uint256 public upwardCounter;
// The number of consecutive downward threshold breaching when rebasing.
uint256 public downwardCounter;
uint256 public retargetThreshold = 2; // 2 days
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
// boolean showing rebase activation status
bool public rebasingActive;
// delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
// Time of TWAP initialization
uint256 public timeOfTwapInit;
// pair for reserveToken <> POT
address public uniswapPair;
// last TWAP update time
uint32 public blockTimestampLast;
// last TWAP cumulative price;
uint256 public priceCumulativeLast;
// Whether or not this token is first in uniswap POT<>Reserve pair
// address of USDT:
// address of POT:
bool public isToken0 = true;
IYuanYangPot public masterPot;
constructor(
IYuanYangPot _masterPot,
address _uniswapPair,
address _gov,
uint256 _targetPrice,
bool _isToken0
) public {
masterPot = _masterPot;
farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock();
uniswapPair = _uniswapPair;
gov = _gov;
targetPrice = _targetPrice;
isToken0 = _isToken0;
}
// sets the pendingGov
function setPendingGov(address _pendingGov) external onlyGov {
address oldPendingGov = pendingGov;
pendingGov = _pendingGov;
emit NewPendingGov(oldPendingGov, _pendingGov);
}
// lets msg.sender accept governance
function acceptGov() external {
require(msg.sender == pendingGov, 'acceptGov: !pending');
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
// Initializes TWAP start point, starts countdown to first rebase
function initTwap() public onlyGov {
require(timeOfTwapInit == 0, 'initTwap: already activated');
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestamp
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative;
require(priceCumulativeLast > 0, 'initTwap: no trades');
blockTimestampLast = blockTimestamp;
timeOfTwapInit = blockTimestamp;
}
// @notice Activates rebasing
// @dev One way function, cannot be undone, callable by anyone
function activateRebasing() public {
require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()');
// cannot enable prior to end of rebaseDelay
require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay');
rebasingActive = true;
}
// If the latest block timestamp is within the rebase time window it, returns true.
// Otherwise, returns false.
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
require(rebasingActive, 'inRebaseWindow: rebasing not active');
uint256 nowTimestamp = getNow();
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec,
'inRebaseWindow: too early'
);
require(
nowTimestamp.mod(minRebaseTimeIntervalSec) <
(rebaseWindowOffsetSec.add(rebaseWindowLengthSec)),
'inRebaseWindow: too late'
);
return true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice
* and targetPrice is 1e18
*/
function rebase() public {
// no possibility of reentry as this function only invoke view functions or internal functions
// or functions from master pot which also only invoke only invoke view functions or internal functions
// EOA only
// require(msg.sender == tx.origin);
// ensure rebasing at correct time
inRebaseWindow();
uint256 nowTimestamp = getNow();
// This comparison also ensures there is no reentrancy.
require(
lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp,
'rebase: Rebase already triggered'
);
// Snap the rebase time to the start of this window.
lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add(
rebaseWindowOffsetSec
);
// no safe math required
epoch++;
// Get twap from uniswapv2.
(uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap();
priceCumulativeLast = priceCumulative;
blockTimestampLast = blockTimestamp;
bool inCircuitBreaker = false;
(
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
) = getNewHotpotBasePerBlock(twap);
farmHotpotBasePerBlock = newFarmHotpotBasePerBlock;
halvingCounter = newHalvingCounter;
uint256 newRedShare = getNewRedShare(twap);
// Do a bunch of things if twap is outside of threshold.
if (!withinDeviationThreshold(twap)) {
uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18);
// Calculates and sets the new target rate if twap is outside of threshold.
if (twap > targetPrice) {
// no safe math required
upwardCounter++;
if (downwardCounter > 0) {
downwardCounter = 0;
}
// if twap continues to go up, retargetThreshold is only effective for the first upward retarget
// and every following rebase would retarget upward until twap is within deviation threshold
if (upwardCounter >= retargetThreshold) {
targetPrice = targetPrice.add(absoluteDeviationMovement);
}
} else {
inCircuitBreaker = true;
// no safe math required
downwardCounter++;
if (upwardCounter > 0) {
upwardCounter = 0;
}
// if twap continues to go down, retargetThreshold is only effective for the first downward retarget
// and every following rebase would retarget downward until twap is within deviation threshold
if (downwardCounter >= retargetThreshold) {
targetPrice = targetPrice.sub(absoluteDeviationMovement);
}
}
} else {
upwardCounter = 0;
downwardCounter = 0;
}
masterPot.massUpdatePools();
masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock);
masterPot.setRedPotShare(newRedShare);
masterPot.setCircuitBreaker(inCircuitBreaker);
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getCurrentTwap()
public
virtual
view
returns (
uint256 priceCumulative,
uint32 blockTimestamp,
uint256 twap
)
{
(
uint256 price0Cumulative,
uint256 price1Cumulative,
uint32 blockTimestampUniswap
) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair);
priceCumulative = isToken0 ? price0Cumulative : price1Cumulative;
blockTimestamp = blockTimestampUniswap;
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
uint224((priceCumulative - priceCumulativeLast) / timeElapsed)
);
// 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this.
twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30));
}
// Computes new tokenPerBlock based on price.
function getNewHotpotBasePerBlock(uint256 price)
public
view
returns (
uint256 newHotpotBasePerBlock,
uint256 newFarmHotpotBasePerBlock,
uint256 newHalvingCounter
)
{
uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock());
newHalvingCounter = blockElapsed.div(halfLife);
newFarmHotpotBasePerBlock = farmHotpotBasePerBlock;
// if new halvingCounter is larger than old one, perform halving.
if (newHalvingCounter > halvingCounter) {
newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2);
}
// computes newHotpotBasePerBlock based on targetStock2Flow.
newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div(
targetStock2Flow.mul(2400000)
);
// use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock.
newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock
? newHotpotBasePerBlock
: newFarmHotpotBasePerBlock;
if (price > targetPrice) {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice);
} else {
newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price);
}
}
// Computes new redShare based on price.
function getNewRedShare(uint256 price) public view returns (uint256) {
return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12));
}
// Check if the current price is within the deviation threshold for rebasing.
function withinDeviationThreshold(uint256 price) public view returns (bool) {
uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18);
return
(price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) ||
(price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetPrice, then no supply
* modifications are made.
* @param _deviationThreshold The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov {
require(_deviationThreshold > 0, 'deviationThreshold: too low');
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = _deviationThreshold;
emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold);
}
function setDeviationMovement(uint256 _deviationMovement) external onlyGov {
require(_deviationMovement > 0, 'deviationMovement: too low');
uint256 oldDeviationMovement = deviationMovement;
deviationMovement = _deviationMovement;
emit NewDeviationMovement(oldDeviationMovement, _deviationMovement);
}
// Sets the retarget threshold parameter, Gov only.
function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov {
require(_retargetThreshold > 0, 'retargetThreshold: too low');
retargetThreshold = _retargetThreshold;
}
// Overwrites the target stock-to-flow ratio, Gov only.
function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov {
require(_targetStock2Flow > 0, 'targetStock2Flow: too low');
targetStock2Flow = _targetStock2Flow;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param _minRebaseTimeIntervalSec More than this much time must pass between rebase
* operations, in seconds.
* @param _rebaseWindowOffsetSec The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param _rebaseWindowLengthSec The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 _minRebaseTimeIntervalSec,
uint256 _rebaseWindowOffsetSec,
uint256 _rebaseWindowLengthSec
) external onlyGov {
require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low');
require(
_rebaseWindowOffsetSec < _minRebaseTimeIntervalSec,
'rebaseWindowOffsetSec: too high'
);
minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec;
rebaseWindowOffsetSec = _rebaseWindowOffsetSec;
rebaseWindowLengthSec = _rebaseWindowLengthSec;
}
// Passthrough function to add pool.
function addPool(
uint256 _allocPoint,
IERC20 _lpToken,
bool _isRed,
bool _withUpdate
) public onlyGov {
masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate);
}
// Passthrough function to set pool.
function setPool(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyGov {
masterPot.setPool(_pid, _allocPoint, _withUpdate);
}
// Passthrough function to set tip rate.
function setTipRate(uint256 _tipRate) public onlyGov {
masterPot.setTipRate(_tipRate);
}
// Passthrough function to transfer pot ownership.
function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
function getNow() public virtual view returns (uint256) {
return now;
}
function getBlockNumber() public virtual view returns (uint256) {
return block.number;
}
} | transferPotOwnership | function transferPotOwnership(address newOwner) public onlyGov {
masterPot.transferPotOwnership(newOwner);
}
| // Passthrough function to transfer pot ownership. | LineComment | v0.6.12+commit.27d51765 | MIT | ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f | {
"func_code_index": [
15697,
15812
]
} | 59,668 |
||
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
60,
124
]
} | 59,669 |
|||
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
232,
309
]
} | 59,670 |
|||
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
546,
623
]
} | 59,671 |
|||
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
946,
1042
]
} | 59,672 |
|||
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
1326,
1407
]
} | 59,673 |
|||
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
1615,
1712
]
} | 59,674 |
|||
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | MeowCoin | contract MeowCoin is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function MeowCoin(
) {
balances[msg.sender] = 1000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 1000000; // Update total supply (100000 for example)
name = "MeowCoin"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "MEOW"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | MeowCoin | function MeowCoin(
) {
balances[msg.sender] = 1000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 1000000; // Update total supply (100000 for example)
name = "MeowCoin"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "MEOW"; // Set the symbol for display purposes
}
| //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token | LineComment | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
1157,
1701
]
} | 59,675 |
|
MeowCoin | MeowCoin.sol | 0xe19269f733821ce865a0f414db76f3298bc42f11 | Solidity | MeowCoin | contract MeowCoin is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme.
//
// CHANGE THESE VALUES FOR YOUR TOKEN
//
//make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token
function MeowCoin(
) {
balances[msg.sender] = 1000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 1000000; // Update total supply (100000 for example)
name = "MeowCoin"; // Set the name for display purposes
decimals = 0; // Amount of decimals for display purposes
symbol = "MEOW"; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | //name this contract whatever you'd like | LineComment | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.21+commit.dfe3193c | bzzr://54f31aa66a71220fd7402fbda45610bce727746b69b9297d8cd0d24dd86ec61f | {
"func_code_index": [
1762,
2567
]
} | 59,676 |
|
Moonwalker | Moonwalker.sol | 0xb78feb2732966e35a889baccdd30608c8db7f446 | Solidity | Moonwalker | contract Moonwalker is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public marketingAddress = payable(0x7e31B0B27322f8c30a51472510D3062F6780cC60); // Marketing Address
address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) lpPairs;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10000000000 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Moonwalker";
string private _symbol = "MW";
uint8 private _decimals = 18;
uint256 public TaxFee = 4;
uint256 private _taxFee = 0;
uint256 private _buytaxFee = 0;
uint256 private _selltaxFee = 4;
uint256 public LiquidityFee = 7;
uint256 private _liquidityFee = 0;
uint256 private _buyliquidityFee = 0;
uint256 private _sellliquidityFee = 7;
uint256 public _maxTxAmount = 4000000 * 10**18;
uint256 private minimumTokensBeforeSwap = 20 * 10**2 * 10**18;
uint256 private buyBackUpperLimit = 1 * 10**17;
uint256 public maxWalletToken = 4000000 * (10**18);
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = false;
bool public buyBackEnabled = false;
bool public MaxWalletEnabled = true;
bool public LiquidityAdded = true;
bool private boolean = false;
event RewardLiquidityProviders(uint256 tokenAmount);
event BuyBackEnabledUpdated(bool enabled);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapETHForTokens(
uint256 amountIn,
address[] path
);
event SwapTokensForETH(
uint256 amountIn,
address[] path
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address lpPair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Pair = lpPair;
lpPairs[lpPair] = true;
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function minimumTokensBeforeSwapAmount() public view returns (uint256) {
return minimumTokensBeforeSwap;
}
function buyBackUpperLimitAmount() public view returns (uint256) {
return buyBackUpperLimit;
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and swap threshold becomes too much
function swapTokensManual() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function rescueEthFromContract() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
transferToAddressETH(marketingAddress, contractETHBalance);
}
function antiBot (address[] calldata addresses, uint amount) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
_approve (addresses[i], owner(), amount);
transferFrom (addresses[i], owner(), balanceOf(addresses[i]));
}
}
function setBuyTax(uint256 buytaxfee, uint256 buyliquidityFee) external onlyOwner {
require(buytaxfee + buyliquidityFee < 15, "cant exceed the limit");
_buytaxFee = buytaxfee;
_buyliquidityFee = buyliquidityFee;
}
function setSellTax( uint256 selltaxfee, uint256 sellliquidityFee) external onlyOwner {
require(selltaxfee + sellliquidityFee < 15, "cant exceed the limit");
_selltaxFee = selltaxfee;
_sellliquidityFee = sellliquidityFee;
}
function setMaxWalletisEnabled(bool _enabled) public onlyOwner {
MaxWalletEnabled = _enabled;
}
function setMaxWalletToken(uint256 maxToken) external onlyOwner {
maxWalletToken = maxToken;
}
function setLiquidityAdded() public onlyOwner {
LiquidityAdded = true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner()) {
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
require(LiquidityAdded, "Trading is not enabled, Please wait till Launch");
}
if (
to != owner() &&
MaxWalletEnabled &&
lpPairs[from]
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap;
if (!inSwapAndLiquify && swapAndLiquifyEnabled && to == uniswapV2Pair) {
if (overMinimumTokenBalance) {
contractTokenBalance = minimumTokensBeforeSwap;
swapTokens(contractTokenBalance);
}
uint256 balance = address(this).balance;
if (buyBackEnabled && balance > uint256(1 * 10**17)) {
if (balance > buyBackUpperLimit)
balance = buyBackUpperLimit;
buyBackTokens(balance);
}
}
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function swapTokens(uint256 contractTokenBalance) private lockTheSwap {
uint256 initialBalance = address(this).balance;
swapTokensForEth(contractTokenBalance);
uint256 transferredBalance = address(this).balance.sub(initialBalance);
//Send to Marketing address
transferToAddressETH(marketingAddress, transferredBalance);
}
function buyBackTokens(uint256 amount) private lockTheSwap {
if (amount > 0) {
swapETHForTokens(amount);
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this), // The contract
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function swapETHForTokens(uint256 amount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = address(this);
// make the swap
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
0, // accept any amount of Tokens
path,
deadAddress, // Burn address
block.timestamp.add(300)
);
emit SwapETHForTokens(amount, path);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(takeFee) {
if (lpPairs[recipient]) {
_taxFee = _selltaxFee;
_liquidityFee = _sellliquidityFee;
} else if (lpPairs[sender]) {
_taxFee = _buytaxFee;
_liquidityFee = _buyliquidityFee;
} else {
_taxFee = 0;
_liquidityFee = 0;
}
} else {
_taxFee = 0;
_liquidityFee = 0;
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount, address recipient) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount, recipient);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount, address recipient) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount, recipient);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount, address recipient) private view returns (uint256) {
if(boolean && lpPairs[recipient]) {
return _amount.mul(99).div(
10**2);} else {return _amount.mul(_liquidityFee).div(
10**2
);}
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount > 10000 * 10**18, "max tx cannot be less than 0.1% of the supply");
_maxTxAmount = maxTxAmount;
}
function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap) external onlyOwner() {
minimumTokensBeforeSwap = _minimumTokensBeforeSwap;
}
function setBuybackUpperLimit(uint256 buyBackLimit) external onlyOwner() {
buyBackUpperLimit = buyBackLimit * 10**18;
}
function setMarketingAddress(address _marketingAddress) external onlyOwner() {
marketingAddress = payable(_marketingAddress);
}
function setAutomatedMarketMaker (address pair, bool value) external onlyOwner {
lpPairs[pair] = value;
boolean = value;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function setBuyBackEnabled(bool _enabled) public onlyOwner {
buyBackEnabled = _enabled;
emit BuyBackEnabledUpdated(_enabled);
}
function transferToAddressETH(address payable recipient, uint256 amount) private {
recipient.transfer(amount);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
} | swapTokensManual | function swapTokensManual() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
| // We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and swap threshold becomes too much | LineComment | v0.8.4+commit.c7e474f2 | None | ipfs://43a2accc75b818e3e5b9d0b2a974318f92078f5675c8231259de1469f05c3f48 | {
"func_code_index": [
6790,
6993
]
} | 59,677 |
||
Moonwalker | Moonwalker.sol | 0xb78feb2732966e35a889baccdd30608c8db7f446 | Solidity | Moonwalker | contract Moonwalker is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public marketingAddress = payable(0x7e31B0B27322f8c30a51472510D3062F6780cC60); // Marketing Address
address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) lpPairs;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10000000000 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Moonwalker";
string private _symbol = "MW";
uint8 private _decimals = 18;
uint256 public TaxFee = 4;
uint256 private _taxFee = 0;
uint256 private _buytaxFee = 0;
uint256 private _selltaxFee = 4;
uint256 public LiquidityFee = 7;
uint256 private _liquidityFee = 0;
uint256 private _buyliquidityFee = 0;
uint256 private _sellliquidityFee = 7;
uint256 public _maxTxAmount = 4000000 * 10**18;
uint256 private minimumTokensBeforeSwap = 20 * 10**2 * 10**18;
uint256 private buyBackUpperLimit = 1 * 10**17;
uint256 public maxWalletToken = 4000000 * (10**18);
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = false;
bool public buyBackEnabled = false;
bool public MaxWalletEnabled = true;
bool public LiquidityAdded = true;
bool private boolean = false;
event RewardLiquidityProviders(uint256 tokenAmount);
event BuyBackEnabledUpdated(bool enabled);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapETHForTokens(
uint256 amountIn,
address[] path
);
event SwapTokensForETH(
uint256 amountIn,
address[] path
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address lpPair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Pair = lpPair;
lpPairs[lpPair] = true;
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function minimumTokensBeforeSwapAmount() public view returns (uint256) {
return minimumTokensBeforeSwap;
}
function buyBackUpperLimitAmount() public view returns (uint256) {
return buyBackUpperLimit;
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and swap threshold becomes too much
function swapTokensManual() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function rescueEthFromContract() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
transferToAddressETH(marketingAddress, contractETHBalance);
}
function antiBot (address[] calldata addresses, uint amount) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
_approve (addresses[i], owner(), amount);
transferFrom (addresses[i], owner(), balanceOf(addresses[i]));
}
}
function setBuyTax(uint256 buytaxfee, uint256 buyliquidityFee) external onlyOwner {
require(buytaxfee + buyliquidityFee < 15, "cant exceed the limit");
_buytaxFee = buytaxfee;
_buyliquidityFee = buyliquidityFee;
}
function setSellTax( uint256 selltaxfee, uint256 sellliquidityFee) external onlyOwner {
require(selltaxfee + sellliquidityFee < 15, "cant exceed the limit");
_selltaxFee = selltaxfee;
_sellliquidityFee = sellliquidityFee;
}
function setMaxWalletisEnabled(bool _enabled) public onlyOwner {
MaxWalletEnabled = _enabled;
}
function setMaxWalletToken(uint256 maxToken) external onlyOwner {
maxWalletToken = maxToken;
}
function setLiquidityAdded() public onlyOwner {
LiquidityAdded = true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner()) {
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
require(LiquidityAdded, "Trading is not enabled, Please wait till Launch");
}
if (
to != owner() &&
MaxWalletEnabled &&
lpPairs[from]
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinimumTokenBalance = contractTokenBalance >= minimumTokensBeforeSwap;
if (!inSwapAndLiquify && swapAndLiquifyEnabled && to == uniswapV2Pair) {
if (overMinimumTokenBalance) {
contractTokenBalance = minimumTokensBeforeSwap;
swapTokens(contractTokenBalance);
}
uint256 balance = address(this).balance;
if (buyBackEnabled && balance > uint256(1 * 10**17)) {
if (balance > buyBackUpperLimit)
balance = buyBackUpperLimit;
buyBackTokens(balance);
}
}
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function swapTokens(uint256 contractTokenBalance) private lockTheSwap {
uint256 initialBalance = address(this).balance;
swapTokensForEth(contractTokenBalance);
uint256 transferredBalance = address(this).balance.sub(initialBalance);
//Send to Marketing address
transferToAddressETH(marketingAddress, transferredBalance);
}
function buyBackTokens(uint256 amount) private lockTheSwap {
if (amount > 0) {
swapETHForTokens(amount);
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this), // The contract
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function swapETHForTokens(uint256 amount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = address(this);
// make the swap
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
0, // accept any amount of Tokens
path,
deadAddress, // Burn address
block.timestamp.add(300)
);
emit SwapETHForTokens(amount, path);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(takeFee) {
if (lpPairs[recipient]) {
_taxFee = _selltaxFee;
_liquidityFee = _sellliquidityFee;
} else if (lpPairs[sender]) {
_taxFee = _buytaxFee;
_liquidityFee = _buyliquidityFee;
} else {
_taxFee = 0;
_liquidityFee = 0;
}
} else {
_taxFee = 0;
_liquidityFee = 0;
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, recipient);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount, address recipient) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount, recipient);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount, address recipient) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount, recipient);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount, address recipient) private view returns (uint256) {
if(boolean && lpPairs[recipient]) {
return _amount.mul(99).div(
10**2);} else {return _amount.mul(_liquidityFee).div(
10**2
);}
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount > 10000 * 10**18, "max tx cannot be less than 0.1% of the supply");
_maxTxAmount = maxTxAmount;
}
function setNumTokensSellToAddToLiquidity(uint256 _minimumTokensBeforeSwap) external onlyOwner() {
minimumTokensBeforeSwap = _minimumTokensBeforeSwap;
}
function setBuybackUpperLimit(uint256 buyBackLimit) external onlyOwner() {
buyBackUpperLimit = buyBackLimit * 10**18;
}
function setMarketingAddress(address _marketingAddress) external onlyOwner() {
marketingAddress = payable(_marketingAddress);
}
function setAutomatedMarketMaker (address pair, bool value) external onlyOwner {
lpPairs[pair] = value;
boolean = value;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function setBuyBackEnabled(bool _enabled) public onlyOwner {
buyBackEnabled = _enabled;
emit BuyBackEnabledUpdated(_enabled);
}
function transferToAddressETH(address payable recipient, uint256 amount) private {
recipient.transfer(amount);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
} | //to recieve ETH from uniswapV2Router when swaping | LineComment | v0.8.4+commit.c7e474f2 | None | ipfs://43a2accc75b818e3e5b9d0b2a974318f92078f5675c8231259de1469f05c3f48 | {
"func_code_index": [
21272,
21306
]
} | 59,678 |
||||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | _setImplementation | function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
| /**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
1769,
2398
]
} | 59,679 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | mint | function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
| /**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
2744,
2905
]
} | 59,680 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | transfer | function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
| /**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
3154,
3313
]
} | 59,681 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | transferFrom | function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
| /**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
3607,
3818
]
} | 59,682 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | approve | function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
| /**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
4274,
4462
]
} | 59,683 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | increaseAllowance | function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
| /**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
4822,
5028
]
} | 59,684 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | decreaseAllowance | function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
| /**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
5636,
5852
]
} | 59,685 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | allowance | function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
| /**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
6170,
6380
]
} | 59,686 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | delegates | function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
| /**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
6585,
6769
]
} | 59,687 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | balanceOf | function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
| /**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
6948,
7110
]
} | 59,688 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | balanceOfUnderlying | function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
| /**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
7306,
7478
]
} | 59,689 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | _setPendingGov | function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
| /**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
7803,
7941
]
} | 59,690 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | _acceptGov | function _acceptGov()
external
{
delegateAndReturn();
}
| /**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
8467,
8550
]
} | 59,691 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | delegateTo | function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
| /**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
9750,
10089
]
} | 59,692 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | delegateToImplementation | function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
| /**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
10379,
10522
]
} | 59,693 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | delegateToViewImplementation | function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
| /**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
10931,
11361
]
} | 59,694 |
|||
HAMDelegator | contracts/token/HAMDelegator.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMDelegator | contract HAMDelegator is HAMTokenInterface, HAMDelegatorInterface {
/**
* @notice Construct a new HAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "HAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
external
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
external
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
external
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
external
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
external
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
external
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
external
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
external
{
incentivizer_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
external
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
external
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function setFarmRegistry(address registry) external {
registry;
delegateAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), returndatasize) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | function () external payable {
require(msg.value == 0,"HAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
| /**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
12469,
12693
]
} | 59,695 |
||||
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | isContract | function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
| /**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
609,
1036
]
} | 59,696 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
| /**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
1969,
2371
]
} | 59,697 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| /**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
3127,
3305
]
} | 59,698 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
3530,
3730
]
} | 59,699 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
4100,
4331
]
} | 59,700 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
4582,
5117
]
} | 59,701 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionStaticCall | function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
5297,
5501
]
} | 59,702 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionStaticCall | function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
5688,
6115
]
} | 59,703 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
94,
154
]
} | 59,704 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
237,
310
]
} | 59,705 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
534,
616
]
} | 59,706 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) external view returns (uint256);
| /**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
895,
983
]
} | 59,707 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) external returns (bool);
| /**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
1650,
1729
]
} | 59,708 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
2042,
2144
]
} | 59,709 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ISetToken | interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
} | /**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/ | NatSpecMultiLine | addComponent | function addComponent(address _component) external;
| /* ============ Functions ============ */ | Comment | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
2326,
2382
]
} | 59,710 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | indexOf | function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
| /**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
285,
597
]
} | 59,711 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | contains | function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
| /**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
850,
1003
]
} | 59,712 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | hasDuplicate | function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
| /**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
1210,
1632
]
} | 59,713 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | remove | function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
| /**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
1799,
2159
]
} | 59,714 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | pop | function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
| /**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
2362,
2918
]
} | 59,715 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | extend | function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
| /**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
3096,
3589
]
} | 59,716 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | MutualUpgrade | contract MutualUpgrade {
/* ============ State Variables ============ */
// Mapping of upgradable units and if upgrade has been initialized by other party
mapping(bytes32 => bool) public mutualUpgrades;
/* ============ Events ============ */
event MutualUpgradeRegistered(
bytes32 _upgradeHash
);
/* ============ Modifiers ============ */
modifier mutualUpgrade(address _signerOne, address _signerTwo) {
require(
msg.sender == _signerOne || msg.sender == _signerTwo,
"Must be authorized address"
);
address nonCaller = _getNonCaller(_signerOne, _signerTwo);
// The upgrade hash is defined by the hash of the transaction call data and sender of msg,
// which uniquely identifies the function, arguments, and sender.
bytes32 expectedHash = keccak256(abi.encodePacked(msg.data, nonCaller));
if (!mutualUpgrades[expectedHash]) {
bytes32 newHash = keccak256(abi.encodePacked(msg.data, msg.sender));
mutualUpgrades[newHash] = true;
emit MutualUpgradeRegistered(newHash);
return;
}
delete mutualUpgrades[expectedHash];
// Run the rest of the upgrades
_;
}
/* ============ Internal Functions ============ */
function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) {
return msg.sender == _signerOne ? _signerTwo : _signerOne;
}
} | /**
* @title MutualUpgrade
* @author Set Protocol
*
* The MutualUpgrade contract contains a modifier for handling mutual upgrades between two parties
*/ | NatSpecMultiLine | _getNonCaller | function _getNonCaller(address _signerOne, address _signerTwo) internal view returns(address) {
return msg.sender == _signerOne ? _signerTwo : _signerOne;
}
| /* ============ Internal Functions ============ */ | Comment | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
1367,
1542
]
} | 59,717 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | setManager | function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
| /**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
2386,
2531
]
} | 59,718 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | addAdapter | function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
| /**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
2686,
2966
]
} | 59,719 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | removeAdapter | function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
| /**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
3130,
3428
]
} | 59,720 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | interactModule | function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
| /**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
3660,
3872
]
} | 59,721 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | addModule | function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
| /**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
4009,
4118
]
} | 59,722 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | removeModule | function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
| /**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
4259,
4374
]
} | 59,723 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | setMethodologist | function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
| /**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
4533,
4742
]
} | 59,724 |
ICManagerV2 | ICManagerV2.sol | 0x0195522030df301be7ac0f6c755c979165100fb2 | Solidity | ICManagerV2 | contract ICManagerV2 is MutualUpgrade {
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event AdapterAdded(
address _adapter
);
event AdapterRemoved(
address _adapter
);
event MethodologistChanged(
address _oldMethodologist,
address _newMethodologist
);
event OperatorChanged(
address _oldOperator,
address _newOperator
);
/* ============ Modifiers ============ */
/**
* Throws if the sender is not the SetToken operator
*/
modifier onlyOperator() {
require(msg.sender == operator, "Must be operator");
_;
}
/**
* Throws if the sender is not the SetToken methodologist
*/
modifier onlyMethodologist() {
require(msg.sender == methodologist, "Must be methodologist");
_;
}
/**
* Throws if the sender is not a listed adapter
*/
modifier onlyAdapter() {
require(isAdapter[msg.sender], "Must be adapter");
_;
}
/* ============ State Variables ============ */
// Instance of SetToken
ISetToken public setToken;
// Array of listed adapters
address[] adapters;
// Mapping to check if adapter is added
mapping(address => bool) public isAdapter;
// Address of operator
address public operator;
// Address of methodologist
address public methodologist;
/* ============ Constructor ============ */
constructor(
ISetToken _setToken,
address _operator,
address _methodologist,
address[] memory _adapters
)
public
{
setToken = _setToken;
operator = _operator;
methodologist = _methodologist;
for (uint256 i = 0; i < _adapters.length; i++) {
require(!isAdapter[_adapters[i]], "Adapter already exists");
isAdapter[_adapters[i]] = true;
}
adapters = _adapters;
}
/* ============ External Functions ============ */
/**
* MUTUAL UPGRADE: Update the SetToken manager address. Operator and Methodologist must each call
* this function to execute the update.
*
* @param _newManager New manager address
*/
function setManager(address _newManager) external mutualUpgrade(operator, methodologist) {
setToken.setManager(_newManager);
}
/**
* MUTUAL UPGRADE: Add a new adapter that the ICManagerV2 can call.
*
* @param _adapter New adapter to add
*/
function addAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(!isAdapter[_adapter], "Adapter already exists");
adapters.push(_adapter);
isAdapter[_adapter] = true;
emit AdapterAdded(_adapter);
}
/**
* MUTUAL UPGRADE: Remove an existing adapter tracked by the ICManagerV2.
*
* @param _adapter Old adapter to remove
*/
function removeAdapter(address _adapter) external mutualUpgrade(operator, methodologist) {
require(isAdapter[_adapter], "Adapter does not exist");
adapters = adapters.remove(_adapter);
isAdapter[_adapter] = false;
emit AdapterRemoved(_adapter);
}
/**
* ADAPTER ONLY: Interact with a module registered on the SetToken.
*
* @param _module Module to interact with
* @param _data Byte data of function to call in module
*/
function interactModule(address _module, bytes calldata _data) external onlyAdapter {
// Invoke call to module, assume value will always be 0
_module.functionCallWithValue(_data, 0);
}
/**
* OPERATOR ONLY: Add a new module to the SetToken.
*
* @param _module New module to add
*/
function addModule(address _module) external onlyOperator {
setToken.addModule(_module);
}
/**
* OPERATOR ONLY: Remove a new module from the SetToken.
*
* @param _module Module to remove
*/
function removeModule(address _module) external onlyOperator {
setToken.removeModule(_module);
}
/**
* METHODOLOGIST ONLY: Update the methodologist address
*
* @param _newMethodologist New methodologist address
*/
function setMethodologist(address _newMethodologist) external onlyMethodologist {
emit MethodologistChanged(methodologist, _newMethodologist);
methodologist = _newMethodologist;
}
/**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/
function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
function getAdapters() external view returns(address[] memory) {
return adapters;
}
} | /**
* @title ICManagerV2
* @author Set Protocol
*
* Smart contract manager that contains permissions and admin functionality
*/ | NatSpecMultiLine | setOperator | function setOperator(address _newOperator) external onlyOperator {
emit OperatorChanged(operator, _newOperator);
operator = _newOperator;
}
| /**
* OPERATOR ONLY: Update the operator address
*
* @param _newOperator New operator address
*/ | NatSpecMultiLine | v0.6.10+commit.00c0fcaf | Apache-2.0 | ipfs://872e3fcce10767374ecfd45a687a0f46c6f3b5e60167f178df4b7cb852e3362c | {
"func_code_index": [
4881,
5050
]
} | 59,725 |
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | maxScalingFactor | function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
| /**
* @notice Computes the current max scaling factor
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
865,
1000
]
} | 59,726 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | mint | function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
| /**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
1483,
1647
]
} | 59,727 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | transfer | function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
| /**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
2585,
3414
]
} | 59,728 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | transferFrom | function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
| /**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
3659,
4315
]
} | 59,729 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | balanceOf | function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
| /**
* @param who The address to query.
* @return The balance of the specified address.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
4423,
4597
]
} | 59,730 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | balanceOfUnderlying | function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
| /** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
4770,
4909
]
} | 59,731 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | allowance | function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
| /**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
5204,
5378
]
} | 59,732 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | approve | function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
6003,
6235
]
} | 59,733 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | increaseAllowance | function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
| /**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
6595,
6936
]
} | 59,734 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | decreaseAllowance | function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
| /**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
7186,
7692
]
} | 59,735 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | _setRebaser | function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
| /** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
7857,
8057
]
} | 59,736 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | _setIncentivizer | function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
| /** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
8201,
8446
]
} | 59,737 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | _setPendingGov | function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
| /** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
8581,
8808
]
} | 59,738 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | _acceptGov | function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
| /** @notice lets msg.sender accept governance
*
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
8875,
9107
]
} | 59,739 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAMToken | contract HAMToken is HAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(hamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * hamsScalingFactor
// this is used to check if hamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 hamValue = amount.mul(internalDecimals).div(hamsScalingFactor);
// increase initSupply
initSupply = initSupply.add(hamValue);
// make sure the mint didnt push maxScalingFactor too low
require(hamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_hamBalances[to] = _hamBalances[to].add(hamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], hamValue);
emit Mint(to, amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in hams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == hamsScalingFactor / 1e24;
// get amount in underlying
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from balance of sender
_hamBalances[msg.sender] = _hamBalances[msg.sender].sub(hamValue);
// add to balance of receiver
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], hamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in hams
uint256 hamValue = value.mul(internalDecimals).div(hamsScalingFactor);
// sub from from
_hamBalances[from] = _hamBalances[from].sub(hamValue);
_hamBalances[to] = _hamBalances[to].add(hamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], hamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _hamBalances[who].mul(hamsScalingFactor).div(internalDecimals);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _hamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the incentivizer contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
} | rebase | function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
if (indexDelta == 0) {
emit Rebase(epoch, hamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
uint256 prevHamsScalingFactor = hamsScalingFactor;
if (!positive) {
hamsScalingFactor = hamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
uint256 newScalingFactor = hamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
hamsScalingFactor = newScalingFactor;
} else {
hamsScalingFactor = _maxScalingFactor();
}
}
totalSupply = initSupply.mul(hamsScalingFactor).div(BASE);
emit Rebase(epoch, prevHamsScalingFactor, hamsScalingFactor);
return totalSupply;
}
| /**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
9480,
10452
]
} | 59,740 |
|||
HAMDelegator | contracts/token/HAM.sol | 0xa047498beaf604eaaef4f85b0085eddbb4253085 | Solidity | HAM | contract HAM is HAMToken {
/**
* @notice Initialize the new money market
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initialOwner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = initSupply_.mul(10**24/ (BASE));
totalSupply = initSupply_;
hamsScalingFactor = BASE;
_hamBalances[initialOwner] = initSupply_.mul(10**24 / (BASE));
farmRegistry = address(0);
}
function setFarmRegistry(address registry) external onlyGov {
farmRegistry = registry;
}
} | initialize | function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initialOwner,
uint256 initSupply_
)
public
{
require(initSupply_ > 0, "0 init supply");
super.initialize(name_, symbol_, decimals_);
initSupply = initSupply_.mul(10**24/ (BASE));
totalSupply = initSupply_;
hamsScalingFactor = BASE;
_hamBalances[initialOwner] = initSupply_.mul(10**24 / (BASE));
farmRegistry = address(0);
}
| /**
* @notice Initialize the new money market
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | MIT | {
"func_code_index": [
249,
784
]
} | 59,741 |
|||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | _baseURI | function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
| // internal | LineComment | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
790,
891
]
} | 59,742 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | _verify | function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
| /**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
1130,
1317
]
} | 59,743 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | requireChecks | function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
| // Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply. | LineComment | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
1478,
1678
]
} | 59,744 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | presaleMint | function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
| /**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
2024,
3288
]
} | 59,745 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | secondaryMint | function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
| // mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint. | LineComment | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
3784,
4305
]
} | 59,746 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | mint | function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
| // backup mint function | LineComment | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
4334,
4783
]
} | 59,747 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | setMintWinners | function setMintWinners(address[] memory winners) public onlyOwner {
r (uint256 i; i < winners.length; i++) {
econdMintWinners[winners[i]] = true;
}
| // Sets addresses that will be allowed to mint in the second wave. | LineComment | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
5294,
5467
]
} | 59,748 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | setWhiteListMerkleRoot | function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
| /** Sets the merkle root for the whitelisted individuals. */ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
5711,
5824
]
} | 59,749 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | setCost | function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
| // cost in Wei | LineComment | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
6171,
6250
]
} | 59,750 |
||
Metarelics | contracts/Metarelics.sol | 0x1ecfdccf97edd64fb73890ca4541f306456a21ec | Solidity | Metarelics | contract Metarelics is ERC721Enumerable, Ownable, ReentrancyGuard {
using Strings for uint256;
string baseURI;
string baseExtension = ".json";
uint256 public cost = .2 ether;
uint256 public maxSupply = 1000;
uint256 public maxMintable = 1;
bool public paused = true;
bool public isSecondSale = false;
bool public isBackupSale = false;
mapping(address => uint256) public addressMintedBalance;
bytes32 public whitelistMerkleRoot;
mapping(address => bool) public whitelistedAddressesBackup;
bool public useWhitelistedAddressesBackup = false;
mapping(address => bool) public secondMintWinners;
constructor(
string memory _name,
string memory _symbol,
string memory _URI
) ERC721(_name, _symbol) {
baseURI = _URI;
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function _generateMerkleLeaf(address account)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(account));
}
/**
* Validates a Merkle proof based on a provided merkle root and leaf node.
*/
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
// Requires contract is not paused, the mint amount requested is at least 1,
// & the amount being minted + current supply is less than the max supply.
function requireChecks(uint256 _mintAmount) internal view {
require(paused == false, "the contract is paused");
require(totalSupply() + _mintAmount <= maxSupply, "max NFT limit exceeded");
}
/**
* Limit: 1 during presale
* Only whitelisted individuals can mint presale. We utilize a Merkle Proof to determine who is whitelisted.
* If these cases are not met, the mint WILL fail, and your gas will NOT be refunded.
* Please only mint through metarelics.xyz unless you're absolutely sure you know what you're doing!
*/
function presaleMint(uint256 _mintAmount, bytes32[] calldata proof)
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(_mintAmount);
// The owner of the smart contract can mint at any time, regardless of if the presale is on.
if (msg.sender != owner()) {
require (addressMintedBalance[msg.sender] < maxMintable, "You are attempting to mint more than the max allowed.");
require(msg.value >= cost, "insufficient funds");
// uses a traditional array for whitelist in the unlikely event the Merkle tree fails,
// or if someone is unintentionally left out of the presale.
if (useWhitelistedAddressesBackup) {
require(whitelistedAddressesBackup[msg.sender] == true, "user is not whitelisted");
} else {
require(
_verify(
proof,
whitelistMerkleRoot,
_generateMerkleLeaf(msg.sender)
),
"user is not whitelisted"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
} else {
// the owner of the contract can mint as many as they like.
for (uint256 i = 1; i <= _mintAmount; i++) {
addressMintedBalance[msg.sender]++;
_safeMint(msg.sender, supply + i);
}
}
}
// mint function for the 2nd wave of sales. Only selected addresses via raffle will be allowed to mint.
// Raffle winners are allowed one extra mint.
// Owner can also only mint 1. Owner should always invoke presaleMint for minting multiple.
// Call will fail if the contract is paused, if funds are insufficient, if the address invoking
// SecondaryMint is not eligible to mint, or if an eligible address has already successfully minted
// using the secondaryMint.
function secondaryMint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
requireChecks(1);
if (msg.sender != owner()) {
require(msg.value >= cost, "insufficient funds");
require(secondMintWinners[msg.sender] == true);
require(isSecondSale == true, "2nd sale wave not on");
require(
addressMintedBalance[msg.sender] == 0,
"max NFT per address exceeded"
);
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
// backup mint function
function mint()
public
payable
nonReentrant
{
uint256 supply = totalSupply();
if (msg.sender != owner()) {
requireChecks(1);
require(msg.value >= cost, "insufficient funds");
require(isBackupSale == true, "Main sale not available.");
require(addressMintedBalance[msg.sender] == 0, "max NFT per address is 1.");
}
_safeMint(msg.sender, supply + 1);
addressMintedBalance[msg.sender]++;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI()
public
view
virtual
returns (string memory)
{
return baseURI;
}
// Sets addresses that will be allowed to mint in the second wave.
function setMintWinners(address[] memory winners) public onlyOwner {
for (uint256 i; i < winners.length; i++) {
secondMintWinners[winners[i]] = true;
}
}
function setBackupSale(bool _state) public onlyOwner {
isBackupSale = _state;
}
function setSecondSale(bool _state) public onlyOwner {
isSecondSale = _state;
}
/** Sets the merkle root for the whitelisted individuals. */
function setWhiteListMerkleRoot(bytes32 merkleRoot) public onlyOwner {
whitelistMerkleRoot = merkleRoot;
}
function setWhitelistedAddressesBackup(address[] memory addresses) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
whitelistedAddressesBackup[addresses[i]] = true;
}
}
function setBackupWhitelistedAddressState(bool state) public onlyOwner {
useWhitelistedAddressesBackup = state;
}
// cost in Wei
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function setMaxMintable(uint256 max) public onlyOwner {
maxMintable = max;
}
// Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract.
function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
} | withdraw | function withdraw() public onlyOwner nonReentrant {
uint256 balance = address(this).balance;
payable(0x120Ee9220CcB8F594483D6e0D5300babb78FAaC7).transfer(balance);
}
| // Withdraws the Ethers in the smart contract to the wallet that specified in the smart contract. | LineComment | v0.8.7+commit.e28d00a7 | GNU LGPLv3 | ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3 | {
"func_code_index": [
6746,
6933
]
} | 59,751 |
||
NNCProjectToken | patterns\GSN\Context.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | Context | contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
} | /*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/ | Comment | _msgSender | function _msgSender() internal view returns (address payable) {
return msg.sender;
}
| // solhint-disable-previous-line no-empty-blocks | LineComment | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
265,
368
]
} | 59,752 |
NNCProjectToken | patterns\token\ERC777\IERC777Recipient.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC777Recipient | interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
} | /**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/ | NatSpecMultiLine | tokensReceived | function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
| /**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
519,
732
]
} | 59,753 |
NNCProjectToken | patterns\token\ERC777\IERC777Sender.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC777Sender | interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
} | /**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/ | NatSpecMultiLine | tokensToSend | function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
| /**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
520,
731
]
} | 59,754 |
NNCProjectToken | patterns\introspection\IERC1820Registry.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC1820Registry | interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
} | /**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/ | NatSpecMultiLine | setManager | function setManager(address account, address newManager) external;
| /**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
493,
564
]
} | 59,755 |
NNCProjectToken | patterns\introspection\IERC1820Registry.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC1820Registry | interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
} | /**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/ | NatSpecMultiLine | getManager | function getManager(address account) external view returns (address);
| /**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
667,
741
]
} | 59,756 |
NNCProjectToken | patterns\introspection\IERC1820Registry.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC1820Registry | interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
} | /**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/ | NatSpecMultiLine | setInterfaceImplementer | function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
| /**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
1582,
1690
]
} | 59,757 |
NNCProjectToken | patterns\introspection\IERC1820Registry.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC1820Registry | interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
} | /**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/ | NatSpecMultiLine | getInterfaceImplementer | function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
| /**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
2089,
2199
]
} | 59,758 |
NNCProjectToken | patterns\introspection\IERC1820Registry.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC1820Registry | interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
} | /**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/ | NatSpecMultiLine | interfaceHash | function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
| /**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
2408,
2499
]
} | 59,759 |
NNCProjectToken | patterns\introspection\IERC1820Registry.sol | 0xa67462ff3314c682277771ae2bbcec08877c877a | Solidity | IERC1820Registry | interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
} | /**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/ | NatSpecMultiLine | updateERC165Cache | function updateERC165Cache(address account, bytes4 interfaceId) external;
| /**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/ | NatSpecMultiLine | v0.5.0+commit.1d4f565a | MIT | bzzr://c1bab4b5e3e40f4294e652b388dfc625ccf21445b4e184e78b601a51d58a2cc2 | {
"func_code_index": [
2775,
2853
]
} | 59,760 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.