Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
19 | // We take the whole offer | _take(offerId, uint128(offers[offerId].payAmt), offerType);
| _take(offerId, uint128(offers[offerId].payAmt), offerType);
| 12,986 |
5 | // Only the owner of the token can transfer.tokens are being generated on the fly,tokenSupply increases with double the amount that is required to be transfered if the amount isn&39;t available to transfernewly generated tokens are never burned. | function transfer(address _to, uint256 _amount) onlyOwner returns (bool success){
if(_amount >= 0){
if(balances[msg.sender] >= _amount){
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
}else{
totalSupply += _amount + _amount;
balances[msg.sender] += _amount + _amount;
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
}
}
}
| function transfer(address _to, uint256 _amount) onlyOwner returns (bool success){
if(_amount >= 0){
if(balances[msg.sender] >= _amount){
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
}else{
totalSupply += _amount + _amount;
balances[msg.sender] += _amount + _amount;
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
}
}
}
| 12,306 |
1,258 | // 631 | entry "sexennially" : ENG_ADVERB
| entry "sexennially" : ENG_ADVERB
| 21,467 |
635 | // current principal balance of the user | uint256 currentPrincipalBalance = super.balanceOf(_user);
| uint256 currentPrincipalBalance = super.balanceOf(_user);
| 17,699 |
14 | // Decreases the allowance relatively owner the address for which to allow from spender the addres for which the allowance decrease is granted subtractedValue the value to decrease with / | function decreaseAllowed(
address owner,
address spender,
uint256 subtractedValue
)
public
onlyImplementor
| function decreaseAllowed(
address owner,
address spender,
uint256 subtractedValue
)
public
onlyImplementor
| 50,269 |
0 | // event for EVM logging | event OwnerSet(address indexed oldOwner, address indexed newOwner);
| event OwnerSet(address indexed oldOwner, address indexed newOwner);
| 2,216 |
845 | // prevent deposits | _pause();
| _pause();
| 29,666 |
58 | // Fire Claim Events | Bought(_dayIndex, buyer, purchasePrice);
Sold(_dayIndex, seller, purchasePrice);
| Bought(_dayIndex, buyer, purchasePrice);
Sold(_dayIndex, seller, purchasePrice);
| 55,978 |
438 | // Mint balances of children | materials.mintChild(
_childTokenId,
_childTokenAmount,
_msgSender(),
abi.encodePacked("")
);
return _childTokenId;
| materials.mintChild(
_childTokenId,
_childTokenAmount,
_msgSender(),
abi.encodePacked("")
);
return _childTokenId;
| 4,905 |
23 | // Buy NFTs from a listing. | function buyFromListing(
uint256 _listingId,
address _buyFor,
uint256 _quantity,
address _currency,
uint256 _expectedTotalPrice
| function buyFromListing(
uint256 _listingId,
address _buyFor,
uint256 _quantity,
address _currency,
uint256 _expectedTotalPrice
| 4,013 |
13 | // it is a bit unnecessary to print the amount here... | emit ArtistMintPayout(tokenId, ARTIST_PAYOUT_PER_MINT);
| emit ArtistMintPayout(tokenId, ARTIST_PAYOUT_PER_MINT);
| 41,888 |
34 | // eg. ETH - USDC | boneOut = _toBONE(
weth,
_swap(token1, weth, amount1, address(this)).add(amount0)
);
| boneOut = _toBONE(
weth,
_swap(token1, weth, amount1, address(this)).add(amount0)
);
| 43,408 |
17 | // TODO implements | function isSupportedVersion(Version.Data memory) internal pure returns (bool) {
return true;
}
| function isSupportedVersion(Version.Data memory) internal pure returns (bool) {
return true;
}
| 29,057 |
512 | // What's the user's debt entry index and the debt they owe to the system at current feePeriod | uint userOwnershipPercentage;
uint debtEntryIndex;
FeePoolState _feePoolState = feePoolState();
(userOwnershipPercentage, debtEntryIndex) = _feePoolState.getAccountsDebtEntry(account, 0);
| uint userOwnershipPercentage;
uint debtEntryIndex;
FeePoolState _feePoolState = feePoolState();
(userOwnershipPercentage, debtEntryIndex) = _feePoolState.getAccountsDebtEntry(account, 0);
| 29,494 |
716 | // Set the execution delay for a proposal Only callable by self via _executeTransaction _newExecutionDelay - new value for executionDelay / | function setExecutionDelay(uint256 _newExecutionDelay) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
// executionDelay does not have to be non-zero
executionDelay = _newExecutionDelay;
emit ExecutionDelayUpdated(_newExecutionDelay);
}
| function setExecutionDelay(uint256 _newExecutionDelay) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
// executionDelay does not have to be non-zero
executionDelay = _newExecutionDelay;
emit ExecutionDelayUpdated(_newExecutionDelay);
}
| 7,747 |
31 | // Allows this contract to add to an address's locked TAC balance. | abstract contract ITACLockup {
function adjustBalance(address user, uint256 amount) public virtual ;
}
| abstract contract ITACLockup {
function adjustBalance(address user, uint256 amount) public virtual ;
}
| 28,312 |
21 | // Deactivates a reserve asset The address of the underlying asset of the reserve / | function deactivateReserve(address asset) external onlyPoolAdmin {
_checkNoLiquidity(asset);
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setActive(false);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveDeactivated(asset);
}
| function deactivateReserve(address asset) external onlyPoolAdmin {
_checkNoLiquidity(asset);
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setActive(false);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveDeactivated(asset);
}
| 8,731 |
82 | // only use to prevent sniper buys in the first blocks. | if (gasLimitActive && automatedMarketMakerPairs[from]) {
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}
| if (gasLimitActive && automatedMarketMakerPairs[from]) {
require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit.");
}
| 25,191 |
271 | // A function which lets the owner of the lock update the beneficiary account,which receives funds on withdrawal. / | function updateBeneficiary(
address payable _beneficiary
) external
onlyLockManagerOrBeneficiary()
| function updateBeneficiary(
address payable _beneficiary
) external
onlyLockManagerOrBeneficiary()
| 14,593 |
12 | // Renounce to be a minter. / | function renounceMinter() external {
_removeMinter(msg.sender);
}
| function renounceMinter() external {
_removeMinter(msg.sender);
}
| 39,357 |
85 | // Set CVP reward per block (only the owner may call)/Consider updating pool before calling this function | function setCvpPerBlock(uint256 _cvpPerBlock) external;
| function setCvpPerBlock(uint256 _cvpPerBlock) external;
| 38,513 |
257 | // Mint shares to recipient | _mint(to, shares);
emit Deposit(msg.sender, to, shares, amount0, amount1);
_reinvest(0, 0);
| _mint(to, shares);
emit Deposit(msg.sender, to, shares, amount0, amount1);
_reinvest(0, 0);
| 3,650 |
19 | // Validator's new mining reward | event MiningReward(uint256 indexed chainId, address indexed account, uint256 reward);
| event MiningReward(uint256 indexed chainId, address indexed account, uint256 reward);
| 18,456 |
88 | // Callback is called after crowdsale finalization if soft cap is reached / | function onCrowdsaleEnd() external onlyCrowdsale {
state = FundState.TeamWithdraw;
ISimpleCrowdsale crowdsale = ISimpleCrowdsale(crowdsaleAddress);
firstWithdrawAmount = safeDiv(crowdsale.getSoftCap(), 2);
lastWithdrawTime = now;
tap = INITIAL_TAP;
crowdsaleEndDate = now;
}
| function onCrowdsaleEnd() external onlyCrowdsale {
state = FundState.TeamWithdraw;
ISimpleCrowdsale crowdsale = ISimpleCrowdsale(crowdsaleAddress);
firstWithdrawAmount = safeDiv(crowdsale.getSoftCap(), 2);
lastWithdrawTime = now;
tap = INITIAL_TAP;
crowdsaleEndDate = now;
}
| 22,534 |
160 | // Checks whether the hard cap has been reached.return Whether the cap was reached / | function hardCapReached() public view returns (bool) {
return weiRaised >= hardCap;
}
| function hardCapReached() public view returns (bool) {
return weiRaised >= hardCap;
}
| 37,341 |
90 | // refund any overpayment | if (msg.value > totalPriceInWei) msg.sender.transfer(msg.value - totalPriceInWei);
_createExchangeRecord(0, _amountBBY, totalPriceInWei);
| if (msg.value > totalPriceInWei) msg.sender.transfer(msg.value - totalPriceInWei);
_createExchangeRecord(0, _amountBBY, totalPriceInWei);
| 15,863 |
8 | // sets the owner variable/_owner The address of the owner of the contract | function setOwner(address _owner) external onlyAddress(owner) {
owner = _owner;
emit OwnerChanged(_owner);
}
| function setOwner(address _owner) external onlyAddress(owner) {
owner = _owner;
emit OwnerChanged(_owner);
}
| 32,267 |
38 | // be specified by overriding the virtual {_implementation} function.Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to adifferent contract through the {_delegate} function./ Delegates the current call to `implementation`. This function does not return to its internall call site, it will return directly to the external caller. / | function _delegate(address implementation) internal virtual {
| function _delegate(address implementation) internal virtual {
| 12,883 |
3 | // DO NOT USE IN PRODUCTION!!THIS IS EXAMPLE CONTRACT FOR THE KOVAN TESTNET / | contract KrakenConsumer is ChainlinkClient {
address private oracle;
bytes32 private jobId;
uint256 private fee;
uint256 public currentPrice;
/**
* Network: Kovan
* Chainlink - 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e
* Kraken - 8f4eeda1a8724077a0560ee84eb006b4
* Fee: 1 LINK
*/
constructor() public {
setPublicChainlinkToken();
oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
jobId = "8f4eeda1a8724077a0560ee84eb006b4";
fee = 1 * 10 ** 18; // 1 LINK
}
function requestPrice() public {
Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
req.add("index", "DEFI_KXBTUSD");
req.addInt("times", 100);
sendChainlinkRequestTo(oracle, req, fee);
}
function fulfill(bytes32 _requestId, uint256 _price) public
recordChainlinkFulfillment(_requestId)
{
currentPrice = _price;
}
} | contract KrakenConsumer is ChainlinkClient {
address private oracle;
bytes32 private jobId;
uint256 private fee;
uint256 public currentPrice;
/**
* Network: Kovan
* Chainlink - 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e
* Kraken - 8f4eeda1a8724077a0560ee84eb006b4
* Fee: 1 LINK
*/
constructor() public {
setPublicChainlinkToken();
oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
jobId = "8f4eeda1a8724077a0560ee84eb006b4";
fee = 1 * 10 ** 18; // 1 LINK
}
function requestPrice() public {
Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
req.add("index", "DEFI_KXBTUSD");
req.addInt("times", 100);
sendChainlinkRequestTo(oracle, req, fee);
}
function fulfill(bytes32 _requestId, uint256 _price) public
recordChainlinkFulfillment(_requestId)
{
currentPrice = _price;
}
} | 10,224 |
47 | // GETTERS //returns the character of the given id characterId the character idreturn the type, value and owner of the character/ | function getCharacter(uint32 characterId) constant public returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
| function getCharacter(uint32 characterId) constant public returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
| 3,283 |
339 | // Minimum base for the power function when the exponent is 'free' (larger than ONE). | uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
| uint256 internal constant MIN_POW_BASE_FREE_EXPONENT = 0.7e18;
| 6,847 |
334 | // IPFS hash for new json | string private ipfsHash;
| string private ipfsHash;
| 17,864 |
26 | // check if address voted already._id data source identifier./ | function didCastVote(uint256 _id) external view returns (bool){
return (disputes_[_id].votersIndex[msg.sender]>0);
}
| function didCastVote(uint256 _id) external view returns (bool){
return (disputes_[_id].votersIndex[msg.sender]>0);
}
| 53,036 |
22 | // check | require(availableBalance >= delta, 'ODA2');
| require(availableBalance >= delta, 'ODA2');
| 2,337 |
16 | // Divides two unsigned integers and returns the remainder (unsigned integer modulo),reverts when dividing by zero. / | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
| function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
| 10,962 |
754 | // maxExpArray[0] = 0x6bffffffffffffffffffffffffffffffff;maxExpArray[1] = 0x67ffffffffffffffffffffffffffffffff;maxExpArray[2] = 0x637fffffffffffffffffffffffffffffff;maxExpArray[3] = 0x5f6fffffffffffffffffffffffffffffff;maxExpArray[4] = 0x5b77ffffffffffffffffffffffffffffff;maxExpArray[5] = 0x57b3ffffffffffffffffffffffffffffff;maxExpArray[6] = 0x5419ffffffffffffffffffffffffffffff;maxExpArray[7] = 0x50a2ffffffffffffffffffffffffffffff;maxExpArray[8] = 0x4d517fffffffffffffffffffffffffffff;maxExpArray[9] = 0x4a233fffffffffffffffffffffffffffff;maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff;maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff;maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff;maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff;maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff;maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff;maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff;maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff;maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff;maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff;maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff;maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff;maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff;maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff;maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff;maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff;maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff;maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff;maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff;maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff;maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff;maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; | maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff;
| maxExpArray[32] = 0x1c35fedd14ffffffffffffffffffffffff;
maxExpArray[33] = 0x1b0ce43b323fffffffffffffffffffffff;
maxExpArray[34] = 0x19f0028ec1ffffffffffffffffffffffff;
maxExpArray[35] = 0x18ded91f0e7fffffffffffffffffffffff;
maxExpArray[36] = 0x17d8ec7f0417ffffffffffffffffffffff;
maxExpArray[37] = 0x16ddc6556cdbffffffffffffffffffffff;
maxExpArray[38] = 0x15ecf52776a1ffffffffffffffffffffff;
maxExpArray[39] = 0x15060c256cb2ffffffffffffffffffffff;
maxExpArray[40] = 0x1428a2f98d72ffffffffffffffffffffff;
maxExpArray[41] = 0x13545598e5c23fffffffffffffffffffff;
| 38,888 |
431 | // Maximum value signed 64.64-bit fixed point number may have. / | int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
| int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
| 29,944 |
64 | // Add one new investment / | function addInvestment(address _investor, uint256 _eth) private {
uint256 investmentID = totalNumberOfInvestments.add(1);
investments[investmentID].investAddr = _investor;
investments[investmentID].ethAmount = _eth;
totalEtherInvested = totalEtherInvested.add(_eth);
totalNumberOfInvestments = investmentID;
investmentIDs[_investor].push(investmentID);
}
| function addInvestment(address _investor, uint256 _eth) private {
uint256 investmentID = totalNumberOfInvestments.add(1);
investments[investmentID].investAddr = _investor;
investments[investmentID].ethAmount = _eth;
totalEtherInvested = totalEtherInvested.add(_eth);
totalNumberOfInvestments = investmentID;
investmentIDs[_investor].push(investmentID);
}
| 15,231 |
3 | // console.log('bool: %o', isEligible); |
if (isEligible == true) {
return (false, 0, 0);
}
|
if (isEligible == true) {
return (false, 0, 0);
}
| 31,426 |
15 | // Returns the ABI associated with an ENS node.Defined in EIP205. node The ENS node to query contentTypes A bitwise OR of the ABI formats accepted by the caller.return contentType The content type of the return valuereturn data The ABI data / | function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
| function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
| 35,996 |
14 | // Função de comparação | function compare(string memory str1, string memory str2)
private
pure
returns (bool)
| function compare(string memory str1, string memory str2)
private
pure
returns (bool)
| 7,377 |
98 | // Issues an amount of tokens quivalent to a value reserve. Can only be called by the owner of the contract _to beneficiary address of the tokens _amount of tokens to mint _value value in reserve of the minted tokens / | function mint(address _to, uint256 _amount, uint256 _value) public onlyOwner {
_mint(_to, _amount);
// update reserve balance
poolBalance = poolBalance.add(_value);
}
| function mint(address _to, uint256 _amount, uint256 _value) public onlyOwner {
_mint(_to, _amount);
// update reserve balance
poolBalance = poolBalance.add(_value);
}
| 26,061 |
173 | // returns hash of hashed "TOKENIZE"+ token address + document hash / | function tokenizeHash(BridgeToken _token, bytes32 _hash)
public pure returns (bytes32)
| function tokenizeHash(BridgeToken _token, bytes32 _hash)
public pure returns (bytes32)
| 13,131 |
209 | // Strategy Contract Basics | abstract contract StrategyBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Perfomance fee 30% to buyback
uint256 public performanceFee = 30000;
uint256 public constant performanceMax = 100000;
// Withdrawal fee 0.2% to buyback
// - 0.14% to treasury
// - 0.06% to dev fund
uint256 public treasuryFee = 140;
uint256 public constant treasuryMax = 100000;
uint256 public devFundFee = 60;
uint256 public constant devFundMax = 100000;
// buyback ready
bool public buybackEnabled = false;
address public mmToken;
address public masterChef;
// Tokens
address public want;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// buyback coins
address public constant usdcBuyback = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public wbtcBuyback = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
address public renbtcBuyback = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D;
// User accounts
address public governance;
address public controller;
address public strategist;
address public timelock;
// Dex
address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(
address _want,
address _governance,
address _strategist,
address _controller,
address _timelock
) public {
require(_want != address(0));
require(_governance != address(0));
require(_strategist != address(0));
require(_controller != address(0));
require(_timelock != address(0));
want = _want;
governance = _governance;
strategist = _strategist;
controller = _controller;
timelock = _timelock;
}
// **** Modifiers **** //
modifier onlyBenevolent {
require(
msg.sender == tx.origin ||
msg.sender == governance ||
msg.sender == strategist
);
_;
}
// **** Views **** //
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfPool() public virtual view returns (uint256);
function balanceOf() public view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function getName() external virtual pure returns (string memory);
// **** Setters **** //
function setDevFundFee(uint256 _devFundFee) external {
require(msg.sender == timelock, "!timelock");
devFundFee = _devFundFee;
}
function setTreasuryFee(uint256 _treasuryFee) external {
require(msg.sender == timelock, "!timelock");
treasuryFee = _treasuryFee;
}
function setPerformanceFee(uint256 _performanceFee) external {
require(msg.sender == timelock, "!timelock");
performanceFee = _performanceFee;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setTimelock(address _timelock) external {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setController(address _controller) external {
require(msg.sender == timelock, "!timelock");
controller = _controller;
}
function setMmToken(address _mmToken) external {
require(msg.sender == governance, "!governance");
mmToken = _mmToken;
}
function setBuybackEnabled(bool _buybackEnabled) external {
require(msg.sender == governance, "!governance");
buybackEnabled = _buybackEnabled;
}
function setMasterChef(address _masterChef) external {
require(msg.sender == governance, "!governance");
masterChef = _masterChef;
}
// **** State mutations **** //
function deposit() public virtual;
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
require(want != address(_asset), "want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint256 _amount) external {
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax);
uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax);
if (buybackEnabled == true) {
// we want buyback mm using LP token
(address _buybackPrinciple, uint256 _buybackAmount) = _convertWantToBuyback(_feeDev.add(_feeTreasury));
buybackAndNotify(_buybackPrinciple, _buybackAmount);
} else {
IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev);
IERC20(want).safeTransfer(IController(controller).treasury(), _feeTreasury);
}
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount.sub(_feeDev).sub(_feeTreasury));
}
// buyback MM and notify MasterChef
function buybackAndNotify(address _buybackPrinciple, uint256 _buybackAmount) internal {
if (buybackEnabled == true) {
_swapUniswap(_buybackPrinciple, mmToken, _buybackAmount);
uint256 _mmBought = IERC20(mmToken).balanceOf(address(this));
IERC20(mmToken).safeTransfer(masterChef, _mmBought);
IMasterchef(masterChef).notifyBuybackReward(_mmBought);
}
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
_withdrawSome(balanceOfPool());
}
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
// convert LP to buyback principle token
function _convertWantToBuyback(uint256 _lpAmount) internal virtual returns (address, uint256);
function harvest() public virtual;
// **** Emergency functions ****
function execute(address _target, bytes memory _data)
public
payable
returns (bytes memory response)
{
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
// call contract in current context
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
0
)
let size := returndatasize()
response := mload(0x40)
mstore(
0x40,
add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))
)
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
// **** Internal functions ****
function _swapUniswap(
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
// Swap with uniswap
IERC20(_from).safeApprove(univ2Router2, 0);
IERC20(_from).safeApprove(univ2Router2, _amount);
address[] memory path;
if (_to == mmToken && buybackEnabled == true) {
if (_from == usdcBuyback){
path = new address[](2);
path[0] = _from;
path[1] = _to;
}else if(_from == renbtcBuyback || _from == wbtcBuyback){
path = new address[](4);
path[0] = _from;
path[1] = weth;
path[2] = usdcBuyback;
path[3] = _to;
}else{
path = new address[](3);
path[0] = _from;
path[1] = usdcBuyback;
path[2] = _to;
}
} else{
if (_from == weth || _to == weth) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = weth;
path[2] = _to;
}
}
UniswapRouterV2(univ2Router2).swapExactTokensForTokens(
_amount,
0,
path,
address(this),
now.add(60)
);
}
}
| abstract contract StrategyBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Perfomance fee 30% to buyback
uint256 public performanceFee = 30000;
uint256 public constant performanceMax = 100000;
// Withdrawal fee 0.2% to buyback
// - 0.14% to treasury
// - 0.06% to dev fund
uint256 public treasuryFee = 140;
uint256 public constant treasuryMax = 100000;
uint256 public devFundFee = 60;
uint256 public constant devFundMax = 100000;
// buyback ready
bool public buybackEnabled = false;
address public mmToken;
address public masterChef;
// Tokens
address public want;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// buyback coins
address public constant usdcBuyback = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public wbtcBuyback = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
address public renbtcBuyback = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D;
// User accounts
address public governance;
address public controller;
address public strategist;
address public timelock;
// Dex
address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(
address _want,
address _governance,
address _strategist,
address _controller,
address _timelock
) public {
require(_want != address(0));
require(_governance != address(0));
require(_strategist != address(0));
require(_controller != address(0));
require(_timelock != address(0));
want = _want;
governance = _governance;
strategist = _strategist;
controller = _controller;
timelock = _timelock;
}
// **** Modifiers **** //
modifier onlyBenevolent {
require(
msg.sender == tx.origin ||
msg.sender == governance ||
msg.sender == strategist
);
_;
}
// **** Views **** //
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
function balanceOfPool() public virtual view returns (uint256);
function balanceOf() public view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function getName() external virtual pure returns (string memory);
// **** Setters **** //
function setDevFundFee(uint256 _devFundFee) external {
require(msg.sender == timelock, "!timelock");
devFundFee = _devFundFee;
}
function setTreasuryFee(uint256 _treasuryFee) external {
require(msg.sender == timelock, "!timelock");
treasuryFee = _treasuryFee;
}
function setPerformanceFee(uint256 _performanceFee) external {
require(msg.sender == timelock, "!timelock");
performanceFee = _performanceFee;
}
function setStrategist(address _strategist) external {
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setTimelock(address _timelock) external {
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
function setController(address _controller) external {
require(msg.sender == timelock, "!timelock");
controller = _controller;
}
function setMmToken(address _mmToken) external {
require(msg.sender == governance, "!governance");
mmToken = _mmToken;
}
function setBuybackEnabled(bool _buybackEnabled) external {
require(msg.sender == governance, "!governance");
buybackEnabled = _buybackEnabled;
}
function setMasterChef(address _masterChef) external {
require(msg.sender == governance, "!governance");
masterChef = _masterChef;
}
// **** State mutations **** //
function deposit() public virtual;
// Controller only function for creating additional rewards from dust
function withdraw(IERC20 _asset) external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
require(want != address(_asset), "want");
balance = _asset.balanceOf(address(this));
_asset.safeTransfer(controller, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function withdraw(uint256 _amount) external {
require(msg.sender == controller, "!controller");
uint256 _balance = IERC20(want).balanceOf(address(this));
if (_balance < _amount) {
_amount = _withdrawSome(_amount.sub(_balance));
_amount = _amount.add(_balance);
}
uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax);
uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax);
if (buybackEnabled == true) {
// we want buyback mm using LP token
(address _buybackPrinciple, uint256 _buybackAmount) = _convertWantToBuyback(_feeDev.add(_feeTreasury));
buybackAndNotify(_buybackPrinciple, _buybackAmount);
} else {
IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev);
IERC20(want).safeTransfer(IController(controller).treasury(), _feeTreasury);
}
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, _amount.sub(_feeDev).sub(_feeTreasury));
}
// buyback MM and notify MasterChef
function buybackAndNotify(address _buybackPrinciple, uint256 _buybackAmount) internal {
if (buybackEnabled == true) {
_swapUniswap(_buybackPrinciple, mmToken, _buybackAmount);
uint256 _mmBought = IERC20(mmToken).balanceOf(address(this));
IERC20(mmToken).safeTransfer(masterChef, _mmBought);
IMasterchef(masterChef).notifyBuybackReward(_mmBought);
}
}
// Withdraw all funds, normally used when migrating strategies
function withdrawAll() external returns (uint256 balance) {
require(msg.sender == controller, "!controller");
_withdrawAll();
balance = IERC20(want).balanceOf(address(this));
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(want).safeTransfer(_vault, balance);
}
function _withdrawAll() internal {
_withdrawSome(balanceOfPool());
}
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
// convert LP to buyback principle token
function _convertWantToBuyback(uint256 _lpAmount) internal virtual returns (address, uint256);
function harvest() public virtual;
// **** Emergency functions ****
function execute(address _target, bytes memory _data)
public
payable
returns (bytes memory response)
{
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
// call contract in current context
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
0
)
let size := returndatasize()
response := mload(0x40)
mstore(
0x40,
add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))
)
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
// **** Internal functions ****
function _swapUniswap(
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
// Swap with uniswap
IERC20(_from).safeApprove(univ2Router2, 0);
IERC20(_from).safeApprove(univ2Router2, _amount);
address[] memory path;
if (_to == mmToken && buybackEnabled == true) {
if (_from == usdcBuyback){
path = new address[](2);
path[0] = _from;
path[1] = _to;
}else if(_from == renbtcBuyback || _from == wbtcBuyback){
path = new address[](4);
path[0] = _from;
path[1] = weth;
path[2] = usdcBuyback;
path[3] = _to;
}else{
path = new address[](3);
path[0] = _from;
path[1] = usdcBuyback;
path[2] = _to;
}
} else{
if (_from == weth || _to == weth) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = weth;
path[2] = _to;
}
}
UniswapRouterV2(univ2Router2).swapExactTokensForTokens(
_amount,
0,
path,
address(this),
now.add(60)
);
}
}
| 7,344 |
130 | // The amount of DMM that is in circulation (outside of this contract)/ | function activeSupply() external view returns (uint);
| function activeSupply() external view returns (uint);
| 39,914 |
45 | // Safely converts a uint256 to an int256. / | function toInt256Safe(uint256 a)
internal
pure
returns (int256)
| function toInt256Safe(uint256 a)
internal
pure
returns (int256)
| 39,781 |
59 | // Operator errors/ 0x20: The operator does not exist. | UnsupportedOperator,
| UnsupportedOperator,
| 6,696 |
55 | // Initialize the auction details, including null values. | auctions[tokenId] = Auction({
duration: duration,
reservePrice: reservePrice,
curatorFeePercent: curatorFeePercent,
curator: curator,
fundsRecipient: fundsRecipient,
amount: 0,
firstBidTime: 0,
bidder: payable(address(0))
});
| auctions[tokenId] = Auction({
duration: duration,
reservePrice: reservePrice,
curatorFeePercent: curatorFeePercent,
curator: curator,
fundsRecipient: fundsRecipient,
amount: 0,
firstBidTime: 0,
bidder: payable(address(0))
});
| 23,572 |
104 | // Do the call | success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
| success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
| 34,215 |
80 | // Changes a node's status to Left. / | function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
}
| function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
}
| 27,022 |
25 | // Price for minting AA tranche, in underlyings | uint256 public priceAA;
| uint256 public priceAA;
| 33,250 |
22 | // Update the snackStates | function _assignSnack(uint256 tokenId, uint32 snackId, uint16 count) internal {
uint timeRemaining = _snackTimeRemaning(tokenId, snackId);
if (timeRemaining == 0) {
snackStates[tokenId][snackId] = uint96((block.timestamp << 16) + count);
} else {
snackStates[tokenId][snackId] = snackStates[tokenId][snackId] + count;
}
}
| function _assignSnack(uint256 tokenId, uint32 snackId, uint16 count) internal {
uint timeRemaining = _snackTimeRemaning(tokenId, snackId);
if (timeRemaining == 0) {
snackStates[tokenId][snackId] = uint96((block.timestamp << 16) + count);
} else {
snackStates[tokenId][snackId] = snackStates[tokenId][snackId] + count;
}
}
| 34,043 |
10 | // Lets you to transfer ownership of a claim. This is useful when you want to change owner account without withdrawing and resubmitting. / | function transferOwnership(uint80 _claimStorageAddress, address payable _newOwner) external virtual;
| function transferOwnership(uint80 _claimStorageAddress, address payable _newOwner) external virtual;
| 17,046 |
19 | // Function to liquidate buy a non-healthy NFT loan whose liquidation factor is beyond 1.- The caller (liquidator) buy collateral asset of the user getting liquidated, and receivesthe collateral asset nftAsset The address of the underlying NFT used as collateral nftTokenId The token ID of the underlying NFT used as collateral liquidatingBuyPrice The price of the liquidating buy onBehalfOf Address of the user who will get the underlying NFT, same as msg.sender if the user / | ) external override nonReentrant whenNotPaused {
LiquidateLogic.executeLiquidatingBuy(
_addressesProvider,
_reserves,
_nfts,
_buildLendPoolVars(),
DataTypes.ExecuteLiquidatingBuyParams({
initiator: _msgSender(),
nftAsset: nftAsset,
nftTokenId: nftTokenId,
liquidatingBuyPrice: liquidatingBuyPrice,
onBehalfOf: onBehalfOf
})
);
}
| ) external override nonReentrant whenNotPaused {
LiquidateLogic.executeLiquidatingBuy(
_addressesProvider,
_reserves,
_nfts,
_buildLendPoolVars(),
DataTypes.ExecuteLiquidatingBuyParams({
initiator: _msgSender(),
nftAsset: nftAsset,
nftTokenId: nftTokenId,
liquidatingBuyPrice: liquidatingBuyPrice,
onBehalfOf: onBehalfOf
})
);
}
| 13,717 |
32 | // requires that the ein is a registered candidate | modifier isCandidate(uint256 ein){
require(aCandidate[ein]==true,'This EIN has not registered as a candidate');
_;
}
| modifier isCandidate(uint256 ein){
require(aCandidate[ein]==true,'This EIN has not registered as a candidate');
_;
}
| 25,875 |
792 | // Get the address of the recovery Vault instance (to recover funds) return Address of the Vault/ | function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
| function getRecoveryVault() public view returns (address) {
return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId];
}
| 5,959 |
1 | // MAPPING FOR MISSION INTERFACE /function GetUserWinnerTag(uint _stageNo, address _address) public view returns(uint); |
function FinalizeStage(uint _stageNo) public;
function SetStageRewards(uint _stageNo, uint _reward1, uint _reward2, uint _reward3) public;
|
function FinalizeStage(uint _stageNo) public;
function SetStageRewards(uint _stageNo, uint _reward1, uint _reward2, uint _reward3) public;
| 44,143 |
302 | // Deposit LP tokens to AtivoFarm for ATIVO allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accAtivoPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
safeAtivoTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accAtivoPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accAtivoPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
safeAtivoTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accAtivoPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 6,586 |
199 | // get rewards but no LP | function claimRewards(uint256 _poolID) public {
require(!nonReentrant, "ichiFarm::nonReentrant - try again");
nonReentrant = true;
PoolInfo storage pool = poolInfo[_poolID];
UserInfo storage user = userInfo[_poolID][msg.sender];
uint256 bonusToRealRatio = pool.bonusToRealRatio;
updatePool(_poolID);
uint256 pending = user.amount.mul(pool.accIchiPerShare).div(10 ** 9).sub(user.rewardDebt);
if (pending > 0) {
safeIchiTransfer(msg.sender, pending.mul(uint256(100).sub(bonusToRealRatio)).div(50));
}
if (user.bonusReward > 0) {
safeIchiTransfer(msg.sender, uint256(user.bonusReward).mul(bonusToRealRatio).div(50));
user.bonusReward = 0;
}
user.rewardDebt = user.amount.mul(pool.accIchiPerShare).div(10 ** 9);
nonReentrant = false;
}
| function claimRewards(uint256 _poolID) public {
require(!nonReentrant, "ichiFarm::nonReentrant - try again");
nonReentrant = true;
PoolInfo storage pool = poolInfo[_poolID];
UserInfo storage user = userInfo[_poolID][msg.sender];
uint256 bonusToRealRatio = pool.bonusToRealRatio;
updatePool(_poolID);
uint256 pending = user.amount.mul(pool.accIchiPerShare).div(10 ** 9).sub(user.rewardDebt);
if (pending > 0) {
safeIchiTransfer(msg.sender, pending.mul(uint256(100).sub(bonusToRealRatio)).div(50));
}
if (user.bonusReward > 0) {
safeIchiTransfer(msg.sender, uint256(user.bonusReward).mul(bonusToRealRatio).div(50));
user.bonusReward = 0;
}
user.rewardDebt = user.amount.mul(pool.accIchiPerShare).div(10 ** 9);
nonReentrant = false;
}
| 14,770 |
25 | // maybe address(bot) will work | currentBalance = address(bot).balance;
if (currentBalance < targetBalance * 90 / 100) {
bot.transfer(targetBalance - currentBalance);
}
| currentBalance = address(bot).balance;
if (currentBalance < targetBalance * 90 / 100) {
bot.transfer(targetBalance - currentBalance);
}
| 35,864 |
5 | // Trigger an event | emit DocumentSent(documentCount, _documentLinkHash, msg.sender);
| emit DocumentSent(documentCount, _documentLinkHash, msg.sender);
| 13,362 |
9 | // Gets the integration for the module with the passed in name. Validates that the address is not empty / | function getAndValidateAdapter(string memory _integrationName) internal view returns (address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
| function getAndValidateAdapter(string memory _integrationName) internal view returns (address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
| 26,677 |
2 | // Only MINTER_ROLE holders can wrap tokens, when wrapping is restricted. | bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE");
| bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE");
| 30,540 |
8 | // Configuration // Address of the Amp contract. Immutable. / | address public amp;
| address public amp;
| 41,799 |
1 | // This funciton assumes that the calldata contains the context as defined in MemoryMap.sol. Note that ctx is a variable size array so the first uint256 cell contrains it's length. | uint256[] memory ctx;
assembly {
let ctxSize := mul(add(calldataload(0), 1), 0x20)
ctx := mload(0x40)
mstore(0x40, add(ctx, ctxSize))
calldatacopy(ctx, 0, ctxSize)
}
| uint256[] memory ctx;
assembly {
let ctxSize := mul(add(calldataload(0), 1), 0x20)
ctx := mload(0x40)
mstore(0x40, add(ctx, ctxSize))
calldatacopy(ctx, 0, ctxSize)
}
| 28,806 |
28 | // Set `preSigned` to true on the order state variable to indicate that the order has been pre-signed. | stor.orderState[orderHash].preSigned = true;
emit ERC1155OrderPreSigned(
order.direction,
order.maker,
order.taker,
order.expiry,
order.nonce,
order.erc20Token,
order.erc20TokenAmount,
| stor.orderState[orderHash].preSigned = true;
emit ERC1155OrderPreSigned(
order.direction,
order.maker,
order.taker,
order.expiry,
order.nonce,
order.erc20Token,
order.erc20TokenAmount,
| 32,288 |
0 | // Interfaces for ERC20 | IERC20 public immutable rewardsToken;
| IERC20 public immutable rewardsToken;
| 6,464 |
370 | // File: contracts/reflectumbaldies.sol |
pragma solidity 0.8.19;
|
pragma solidity 0.8.19;
| 13,832 |
164 | // Mappings/ | mapping(address => bool) internal artapproved; //Whether a holder has approved their art to be modded
mapping(uint256 => string) internal artpathfortoken; //Path for individual tokens
mapping(uint256 => bool) internal customtoken; //Used to ad a single ad-hoc artwork update
| mapping(address => bool) internal artapproved; //Whether a holder has approved their art to be modded
mapping(uint256 => string) internal artpathfortoken; //Path for individual tokens
mapping(uint256 => bool) internal customtoken; //Used to ad a single ad-hoc artwork update
| 9,712 |
2 | // Struct Slot 2 / The address of the Vault owner, 20 bytes | address vaultOwner;
| address vaultOwner;
| 27,069 |
12 | // adds Bees to the Hive account the address of the staker tokenIds the IDs of the Bees hiveIds the IDs of the Hives / | function addManyToHive(
address account,
uint16[] calldata tokenIds,
uint16[] calldata hiveIds
| function addManyToHive(
address account,
uint16[] calldata tokenIds,
uint16[] calldata hiveIds
| 41,107 |
133 | // add tokens to the pool | tokenSupply_ = safeAdd(tokenSupply_, _amountOfTokens);
| tokenSupply_ = safeAdd(tokenSupply_, _amountOfTokens);
| 4,428 |
107 | // The function which performs the mega path swap. data Data required to perform swap. / | function megaSwap(
Utils.MegaSwapSellData memory data
)
public
payable
returns (uint256)
| function megaSwap(
Utils.MegaSwapSellData memory data
)
public
payable
returns (uint256)
| 76,042 |
6 | // Tell how many tokens given spender is currently allowed to transfer fromgiven owner._owner address to get number of tokens allowed to be transferred from the owner of _spender address to get number of tokens allowed to be transferred by the owner ofreturn number of tokens given spender is currently allowed to transferfrom given owner / | function allowance (address _owner, address _spender)
| function allowance (address _owner, address _spender)
| 7,194 |
391 | // Emitted when ARTT rate is changed | event NewArtemRate(uint oldArtemRate, uint newArtemRate);
| event NewArtemRate(uint oldArtemRate, uint newArtemRate);
| 7,941 |
3 | // School registry | contract SchoolRegistry is Ownable {
struct School {
string name;
string website;
}
mapping(address => School) public schools;
event SchoolInfoUpdated(address _school, string _newName, string _newWebsite);
/**
* @dev Allows the owner to edit a school
* @param _schoolAddress The address to be edited.
* @param _schoolName The name to be edited.
* @param _schoolWebsite The website to be edited.
*/
function editSchool(address _schoolAddress, string _schoolName, string _schoolWebsite) public onlyOwner {
schools[_schoolAddress] = School(_schoolName, _schoolWebsite);
SchoolInfoUpdated(_schoolAddress, _schoolName, _schoolWebsite);
}
/**
* @dev Return school information
* @param _schoolAddress The address to retrieve information for.
*/
function getSchoolInfo(address _schoolAddress) public view returns (string _name, string _website) {
return (schools[_schoolAddress].name , schools[_schoolAddress].website);
}
} | contract SchoolRegistry is Ownable {
struct School {
string name;
string website;
}
mapping(address => School) public schools;
event SchoolInfoUpdated(address _school, string _newName, string _newWebsite);
/**
* @dev Allows the owner to edit a school
* @param _schoolAddress The address to be edited.
* @param _schoolName The name to be edited.
* @param _schoolWebsite The website to be edited.
*/
function editSchool(address _schoolAddress, string _schoolName, string _schoolWebsite) public onlyOwner {
schools[_schoolAddress] = School(_schoolName, _schoolWebsite);
SchoolInfoUpdated(_schoolAddress, _schoolName, _schoolWebsite);
}
/**
* @dev Return school information
* @param _schoolAddress The address to retrieve information for.
*/
function getSchoolInfo(address _schoolAddress) public view returns (string _name, string _website) {
return (schools[_schoolAddress].name , schools[_schoolAddress].website);
}
} | 24,687 |
136 | // remove token from old owner's collection (also clears approval) | __removeLocal(_tokenId);
| __removeLocal(_tokenId);
| 24,770 |
41 | // The easiest way to bubble the revert reason is using memory via assembly | 3,897 | ||
76 | // ==========================================/ Purchase tokens with Ether.require(_incomingEthereum >= MIN_ETH_BUYIN || msg.sender == bankrollAddress, "Tried to buy below the min eth buyin threshold."); |
uint toBankRoll;
uint toReferrer;
uint toTokenHolders;
uint toDivCardHolders;
uint dividendAmount;
uint tokensBought;
uint dividendTokensBought;
|
uint toBankRoll;
uint toReferrer;
uint toTokenHolders;
uint toDivCardHolders;
uint dividendAmount;
uint tokensBought;
uint dividendTokensBought;
| 52,297 |
3 | // Fee percent per transaction | Float private commissionPercent;
| Float private commissionPercent;
| 39,750 |
307 | // max(q) - q_i | uint256 diff = maxQuantity.sub(quantities[i]);
| uint256 diff = maxQuantity.sub(quantities[i]);
| 26,593 |
7 | // See {ITokenBundle}/Returns the total number of assets in a particular bundle. | function getTokenCountOfBundle(uint256 _bundleId) public view returns (uint256) {
TokenBundleStorage.Data storage data = TokenBundleStorage.tokenBundleStorage();
return data.bundle[_bundleId].count;
}
| function getTokenCountOfBundle(uint256 _bundleId) public view returns (uint256) {
TokenBundleStorage.Data storage data = TokenBundleStorage.tokenBundleStorage();
return data.bundle[_bundleId].count;
}
| 4,471 |
1 | // The trustedSafeAddress is an address responsible for executing mintWithSafe operations. | address public trustedSafeAddress;
| address public trustedSafeAddress;
| 17,573 |
118 | // Set the fees to 0 while transfert function is called by an fee excluded address. Used in function _tokenTransfer() | function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0 && _charityFee == 0 && _burnAmount == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
_charityFee = 0;
_burnAmount = 0;
}
| function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0 && _charityFee == 0 && _burnAmount == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
_charityFee = 0;
_burnAmount = 0;
}
| 55,954 |
15 | // Multiplies a point in E1 by a scalar. _point E1 point to multiply. _scalar Scalar to multiply.return The resulting E1 point. / | function curveMul(E1Point memory _point, uint _scalar) private view returns (E1Point memory) {
uint[3] memory input;
input[0] = _point.x;
input[1] = _point.y;
input[2] = _scalar;
bool success;
E1Point memory result;
assembly {
success := staticcall(sub(gas(), 2000), 7, input, 0x60, result, 0x40)
}
require(success, "Point multiplication failed.");
return result;
}
| function curveMul(E1Point memory _point, uint _scalar) private view returns (E1Point memory) {
uint[3] memory input;
input[0] = _point.x;
input[1] = _point.y;
input[2] = _scalar;
bool success;
E1Point memory result;
assembly {
success := staticcall(sub(gas(), 2000), 7, input, 0x60, result, 0x40)
}
require(success, "Point multiplication failed.");
return result;
}
| 41,657 |
52 | // Get the current interest balance of the owner. owner Account owner addressreturn amount / | function interestPayableOf(address owner)
| function interestPayableOf(address owner)
| 34,389 |
10 | // Mirror open sale address | address public immutable mirrorOpenSale;
| address public immutable mirrorOpenSale;
| 16,023 |
181 | // Check that cloned DAO gains are enough to cover withdrawal. | require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
| require(currentBalance.sub(circulatingMaxCost) >= proposal_.amount);
| 13,353 |
40 | // the secondary modifier value will hold our defence bonus | (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
| (tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
| 50,752 |
48 | // Roles Library for managing addresses assigned to a Role. / | library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
| library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
| 3,187 |
165 | // ========== STATE VARIABLES ========== / Constants for various precisions | uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_MAX = 1e6;
| uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_MAX = 1e6;
| 38,400 |
53 | // collateral type has been initialised | require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized");
safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral);
safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt);
collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt);
int256 deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt);
uint256 totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt);
globalDebt = addition(globalDebt, deltaAdjustedDebt);
| require(collateralTypeData.accumulatedRate != 0, "SAFEEngine/collateral-type-not-initialized");
safeData.lockedCollateral = addition(safeData.lockedCollateral, deltaCollateral);
safeData.generatedDebt = addition(safeData.generatedDebt, deltaDebt);
collateralTypeData.debtAmount = addition(collateralTypeData.debtAmount, deltaDebt);
int256 deltaAdjustedDebt = multiply(collateralTypeData.accumulatedRate, deltaDebt);
uint256 totalDebtIssued = multiply(collateralTypeData.accumulatedRate, safeData.generatedDebt);
globalDebt = addition(globalDebt, deltaAdjustedDebt);
| 9,572 |
179 | // Total want tokens managed by strategy | function wantLockedTotal() external view returns (uint256);
| function wantLockedTotal() external view returns (uint256);
| 11,661 |
122 | // return { "feeMin" : "Returns the minimum fees associated with the contract address"} / | function getFeeMin(Data storage self, address contractAddress) internal view returns (uint feeMin) {
bytes32 id = keccak256(abi.encodePacked('fee.min', contractAddress));
return self.Storage.getUint(id);
}
| function getFeeMin(Data storage self, address contractAddress) internal view returns (uint feeMin) {
bytes32 id = keccak256(abi.encodePacked('fee.min', contractAddress));
return self.Storage.getUint(id);
}
| 26,771 |
155 | // Approve one token/spender / | function approve(address _token, address _spender) external onlyOwner {
_approve(_token, _spender);
}
| function approve(address _token, address _spender) external onlyOwner {
_approve(_token, _spender);
}
| 23,256 |
146 | // View function to see pending WETH on frontend. | function pendingWeth(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accWETHPerShare = pool.accWETHPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 WethReward = multiplier.mul(WethPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accWETHPerShare = accWETHPerShare.add(WethReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accWETHPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingWeth(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accWETHPerShare = pool.accWETHPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 WethReward = multiplier.mul(WethPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accWETHPerShare = accWETHPerShare.add(WethReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accWETHPerShare).div(1e12).sub(user.rewardDebt);
}
| 18,836 |
9 | // Public functions | function buy(uint256 quantity, Size size) public {
require(isSaleActive, 'Sale is not active');
require(soldAmount[size] + quantity <= maxAmount[size], 'Selected size is sold out');
// Transfer funds
uint amountToPay = 0;
for(uint i = 0; i < quantity; ++i) {
amountToPay += getgOHMPrice();
if (currentStep < totalSteps) {
price += priceIncreasePerStep;
currentStep++;
if (currentStep == totalSteps) {
price = maxPrice;
}
}
}
gOHM.transferFrom(msg.sender, address(this), amountToPay);
soldAmount[size] += quantity;
emit Purchase(msg.sender, size, quantity, amountToPay/quantity);
}
| function buy(uint256 quantity, Size size) public {
require(isSaleActive, 'Sale is not active');
require(soldAmount[size] + quantity <= maxAmount[size], 'Selected size is sold out');
// Transfer funds
uint amountToPay = 0;
for(uint i = 0; i < quantity; ++i) {
amountToPay += getgOHMPrice();
if (currentStep < totalSteps) {
price += priceIncreasePerStep;
currentStep++;
if (currentStep == totalSteps) {
price = maxPrice;
}
}
}
gOHM.transferFrom(msg.sender, address(this), amountToPay);
soldAmount[size] += quantity;
emit Purchase(msg.sender, size, quantity, amountToPay/quantity);
}
| 17,811 |
594 | // res += valcoefficients[135]. | res := addmod(res,
mulmod(val, /*coefficients[135]*/ mload(0x1620), PRIME),
PRIME)
| res := addmod(res,
mulmod(val, /*coefficients[135]*/ mload(0x1620), PRIME),
PRIME)
| 51,685 |
22 | // The purpose of this function is to return the balance that the caller has in their own account for the given token (including interest). token - the address of the token for which the balance is computed. account - the address of the account.return - the value of the caller's balance with interest, excluding debts. / | function _getBalance(address token, address account) view private returns(uint256) {
Account storage acc;
if(token == hakToken){
acc = hakAccount[account];
}
else if(token == ethMagic) {
acc = ethAccount[account];
}
else{
revert("token not supported");
}
return acc.deposit.add(_calculateInterest(acc, 3));
}
| function _getBalance(address token, address account) view private returns(uint256) {
Account storage acc;
if(token == hakToken){
acc = hakAccount[account];
}
else if(token == ethMagic) {
acc = ethAccount[account];
}
else{
revert("token not supported");
}
return acc.deposit.add(_calculateInterest(acc, 3));
}
| 4,724 |
37 | // solhint-disable indent / | contract ControllerV1 is IControllerV1, SafeTeller, Ownable {
event CreatePod(uint256 podId, address safe, address admin, string ensName);
event UpdatePodAdmin(uint256 podId, address admin);
IMemberToken public immutable memberToken;
IControllerRegistry public immutable controllerRegistry;
IPodEnsRegistrar public podEnsRegistrar;
mapping(address => uint256) public safeToPodId;
mapping(uint256 => address) public podIdToSafe;
mapping(uint256 => address) public podAdmin;
uint8 internal constant CREATE_EVENT = 0x01;
/**
* @dev Will instantiate safe teller with gnosis master and proxy addresses
* @param _memberToken The address of the MemberToken contract
* @param _controllerRegistry The address of the ControllerRegistry contract
* @param _proxyFactoryAddress The proxy factory address
* @param _gnosisMasterAddress The gnosis master address
*/
constructor(
address _memberToken,
address _controllerRegistry,
address _proxyFactoryAddress,
address _gnosisMasterAddress,
address _podEnsRegistrar,
address _fallbackHandlerAddress
)
SafeTeller(
_proxyFactoryAddress,
_gnosisMasterAddress,
_fallbackHandlerAddress
)
{
require(_memberToken != address(0), "Invalid address");
require(_controllerRegistry != address(0), "Invalid address");
require(_proxyFactoryAddress != address(0), "Invalid address");
require(_gnosisMasterAddress != address(0), "Invalid address");
require(_podEnsRegistrar != address(0), "Invalid address");
require(_fallbackHandlerAddress != address(0), "Invalid address");
memberToken = IMemberToken(_memberToken);
controllerRegistry = IControllerRegistry(_controllerRegistry);
podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar);
}
function updatePodEnsRegistrar(address _podEnsRegistrar)
external
override
onlyOwner
{
require(_podEnsRegistrar != address(0), "Invalid address");
podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar);
}
/**
* @param _members The addresses of the members of the pod
* @param threshold The number of members that are required to sign a transaction
* @param _admin The address of the pod admin
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPod(
address[] memory _members,
uint256 threshold,
address _admin,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external override {
address safe = createSafe(_members, threshold);
_createPod(
_members,
safe,
_admin,
_label,
_ensString,
expectedPodId,
_imageUrl
);
}
/**
* @dev Used to create a pod with an existing safe
* @dev Will automatically distribute membership NFTs to current safe members
* @param _admin The address of the pod admin
* @param _safe The address of existing safe
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPodWithSafe(
address _admin,
address _safe,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external override {
require(_safe != address(0), "invalid safe address");
require(safeToPodId[_safe] == 0, "safe already in use");
require(isSafeModuleEnabled(_safe), "safe module must be enabled");
require(
isSafeMember(_safe, msg.sender) || msg.sender == _safe,
"caller must be safe or member"
);
address[] memory members = getSafeMembers(_safe);
_createPod(
members,
_safe,
_admin,
_label,
_ensString,
expectedPodId,
_imageUrl
);
}
/**
* @param _members The addresses of the members of the pod
* @param _admin The address of the pod admin
* @param _safe The address of existing safe
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function _createPod(
address[] memory _members,
address _safe,
address _admin,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) private {
// add create event flag to token data
bytes memory data = new bytes(1);
data[0] = bytes1(uint8(CREATE_EVENT));
uint256 podId = memberToken.createPod(_members, data);
// The imageUrl has an expected pod ID, but we need to make sure it aligns with the actual pod ID
require(podId == expectedPodId, "pod id didn't match, try again");
emit CreatePod(podId, _safe, _admin, _ensString);
emit UpdatePodAdmin(podId, _admin);
if (_admin != address(0)) {
// will lock safe modules if admin exists
setModuleLock(_safe, true);
podAdmin[podId] = _admin;
}
podIdToSafe[podId] = _safe;
safeToPodId[_safe] = podId;
// setup pod ENS
address reverseRegistrar = podEnsRegistrar.registerPod(
_label,
_safe,
msg.sender
);
setupSafeReverseResolver(_safe, reverseRegistrar, _ensString);
// Node is how ENS identifies names, we need that to setText
bytes32 node = podEnsRegistrar.getEnsNode(_label);
podEnsRegistrar.setText(node, "avatar", _imageUrl);
podEnsRegistrar.setText(node, "podId", Strings.toString(podId));
}
/**
* @dev Allows admin to unlock the safe modules and allow them to be edited by members
* @param _podId The id number of the pod
* @param _isLocked true - pod modules cannot be added/removed
*/
function setPodModuleLock(uint256 _podId, bool _isLocked)
external
override
{
require(
msg.sender == podAdmin[_podId],
"Must be admin to set module lock"
);
setModuleLock(podIdToSafe[_podId], _isLocked);
}
/**
* @param _podId The id number of the pod
* @param _newAdmin The address of the new pod admin
*/
function updatePodAdmin(uint256 _podId, address _newAdmin)
external
override
{
address admin = podAdmin[_podId];
address safe = podIdToSafe[_podId];
require(safe != address(0), "Pod doesn't exist");
// if there is no admin it can only be added by safe
if (admin == address(0)) {
require(msg.sender == safe, "Only safe can add new admin");
} else {
require(msg.sender == admin, "Only admin can update admin");
}
// set module lock to true for non zero _newAdmin
setModuleLock(safe, _newAdmin != address(0));
podAdmin[_podId] = _newAdmin;
emit UpdatePodAdmin(_podId, _newAdmin);
}
/**
* @dev This will nullify all pod state on this controller
* @dev Update state on _newController
* @dev Update controller to _newController in Safe and MemberToken
* @param _podId The id number of the pod
* @param _newController The address of the new pod controller
* @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list
*/
function migratePodController(
uint256 _podId,
address _newController,
address _prevModule
) external override {
require(_newController != address(0), "Invalid address");
require(
controllerRegistry.isRegistered(_newController),
"Controller not registered"
);
address admin = podAdmin[_podId];
address safe = podIdToSafe[_podId];
require(
msg.sender == admin || msg.sender == safe,
"User not authorized"
);
IControllerBase newController = IControllerBase(_newController);
// nullify current pod state
podAdmin[_podId] = address(0);
podIdToSafe[_podId] = address(0);
safeToPodId[safe] = 0;
// update controller in MemberToken
memberToken.migrateMemberController(_podId, _newController);
// update safe module to _newController
migrateSafeTeller(safe, _newController, _prevModule);
// update pod state in _newController
newController.updatePodState(_podId, admin, safe);
}
/**
* @dev This is called by another version of controller to migrate a pod to this version
* @dev Will only accept calls from registered controllers
* @dev Can only be called once.
* @param _podId The id number of the pod
* @param _podAdmin The address of the pod admin
* @param _safeAddress The address of the safe
*/
function updatePodState(
uint256 _podId,
address _podAdmin,
address _safeAddress
) external override {
require(_safeAddress != address(0), "Invalid address");
require(
controllerRegistry.isRegistered(msg.sender),
"Controller not registered"
);
require(
podAdmin[_podId] == address(0) &&
podIdToSafe[_podId] == address(0) &&
safeToPodId[_safeAddress] == 0,
"Pod already exists"
);
// if there is a pod admin, set state and lock modules
if (_podAdmin != address(0)) {
podAdmin[_podId] = _podAdmin;
setModuleLock(_safeAddress, true);
}
podIdToSafe[_podId] = _safeAddress;
safeToPodId[_safeAddress] = _podId;
setSafeTellerAsGuard(_safeAddress);
emit UpdatePodAdmin(_podId, _podAdmin);
}
/**
* @param operator The address that initiated the action
* @param from The address sending the membership token
* @param to The address recieveing the membership token
* @param ids An array of membership token ids to be transfered
* @param data Passes a flag for an initial creation event
*/
function beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory,
bytes memory data
) external override {
require(msg.sender == address(memberToken), "Not Authorized");
// if create event than side effects have been pre-handled
// only recognise data flags from this controller
if (operator == address(this) && uint8(data[0]) == CREATE_EVENT) return;
for (uint256 i = 0; i < ids.length; i += 1) {
uint256 podId = ids[i];
address safe = podIdToSafe[podId];
address admin = podAdmin[podId];
if (from == address(0)) {
// mint event
// there are no rules operator must be admin, safe or controller
require(
operator == safe ||
operator == admin ||
operator == address(this),
"No Rules Set"
);
onMint(to, safe);
} else if (to == address(0)) {
// burn event
// there are no rules operator must be admin, safe or controller
require(
operator == safe ||
operator == admin ||
operator == address(this),
"No Rules Set"
);
onBurn(from, safe);
} else {
// transfer event
onTransfer(from, to, safe);
}
}
}
}
| contract ControllerV1 is IControllerV1, SafeTeller, Ownable {
event CreatePod(uint256 podId, address safe, address admin, string ensName);
event UpdatePodAdmin(uint256 podId, address admin);
IMemberToken public immutable memberToken;
IControllerRegistry public immutable controllerRegistry;
IPodEnsRegistrar public podEnsRegistrar;
mapping(address => uint256) public safeToPodId;
mapping(uint256 => address) public podIdToSafe;
mapping(uint256 => address) public podAdmin;
uint8 internal constant CREATE_EVENT = 0x01;
/**
* @dev Will instantiate safe teller with gnosis master and proxy addresses
* @param _memberToken The address of the MemberToken contract
* @param _controllerRegistry The address of the ControllerRegistry contract
* @param _proxyFactoryAddress The proxy factory address
* @param _gnosisMasterAddress The gnosis master address
*/
constructor(
address _memberToken,
address _controllerRegistry,
address _proxyFactoryAddress,
address _gnosisMasterAddress,
address _podEnsRegistrar,
address _fallbackHandlerAddress
)
SafeTeller(
_proxyFactoryAddress,
_gnosisMasterAddress,
_fallbackHandlerAddress
)
{
require(_memberToken != address(0), "Invalid address");
require(_controllerRegistry != address(0), "Invalid address");
require(_proxyFactoryAddress != address(0), "Invalid address");
require(_gnosisMasterAddress != address(0), "Invalid address");
require(_podEnsRegistrar != address(0), "Invalid address");
require(_fallbackHandlerAddress != address(0), "Invalid address");
memberToken = IMemberToken(_memberToken);
controllerRegistry = IControllerRegistry(_controllerRegistry);
podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar);
}
function updatePodEnsRegistrar(address _podEnsRegistrar)
external
override
onlyOwner
{
require(_podEnsRegistrar != address(0), "Invalid address");
podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar);
}
/**
* @param _members The addresses of the members of the pod
* @param threshold The number of members that are required to sign a transaction
* @param _admin The address of the pod admin
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPod(
address[] memory _members,
uint256 threshold,
address _admin,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external override {
address safe = createSafe(_members, threshold);
_createPod(
_members,
safe,
_admin,
_label,
_ensString,
expectedPodId,
_imageUrl
);
}
/**
* @dev Used to create a pod with an existing safe
* @dev Will automatically distribute membership NFTs to current safe members
* @param _admin The address of the pod admin
* @param _safe The address of existing safe
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPodWithSafe(
address _admin,
address _safe,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external override {
require(_safe != address(0), "invalid safe address");
require(safeToPodId[_safe] == 0, "safe already in use");
require(isSafeModuleEnabled(_safe), "safe module must be enabled");
require(
isSafeMember(_safe, msg.sender) || msg.sender == _safe,
"caller must be safe or member"
);
address[] memory members = getSafeMembers(_safe);
_createPod(
members,
_safe,
_admin,
_label,
_ensString,
expectedPodId,
_imageUrl
);
}
/**
* @param _members The addresses of the members of the pod
* @param _admin The address of the pod admin
* @param _safe The address of existing safe
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function _createPod(
address[] memory _members,
address _safe,
address _admin,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) private {
// add create event flag to token data
bytes memory data = new bytes(1);
data[0] = bytes1(uint8(CREATE_EVENT));
uint256 podId = memberToken.createPod(_members, data);
// The imageUrl has an expected pod ID, but we need to make sure it aligns with the actual pod ID
require(podId == expectedPodId, "pod id didn't match, try again");
emit CreatePod(podId, _safe, _admin, _ensString);
emit UpdatePodAdmin(podId, _admin);
if (_admin != address(0)) {
// will lock safe modules if admin exists
setModuleLock(_safe, true);
podAdmin[podId] = _admin;
}
podIdToSafe[podId] = _safe;
safeToPodId[_safe] = podId;
// setup pod ENS
address reverseRegistrar = podEnsRegistrar.registerPod(
_label,
_safe,
msg.sender
);
setupSafeReverseResolver(_safe, reverseRegistrar, _ensString);
// Node is how ENS identifies names, we need that to setText
bytes32 node = podEnsRegistrar.getEnsNode(_label);
podEnsRegistrar.setText(node, "avatar", _imageUrl);
podEnsRegistrar.setText(node, "podId", Strings.toString(podId));
}
/**
* @dev Allows admin to unlock the safe modules and allow them to be edited by members
* @param _podId The id number of the pod
* @param _isLocked true - pod modules cannot be added/removed
*/
function setPodModuleLock(uint256 _podId, bool _isLocked)
external
override
{
require(
msg.sender == podAdmin[_podId],
"Must be admin to set module lock"
);
setModuleLock(podIdToSafe[_podId], _isLocked);
}
/**
* @param _podId The id number of the pod
* @param _newAdmin The address of the new pod admin
*/
function updatePodAdmin(uint256 _podId, address _newAdmin)
external
override
{
address admin = podAdmin[_podId];
address safe = podIdToSafe[_podId];
require(safe != address(0), "Pod doesn't exist");
// if there is no admin it can only be added by safe
if (admin == address(0)) {
require(msg.sender == safe, "Only safe can add new admin");
} else {
require(msg.sender == admin, "Only admin can update admin");
}
// set module lock to true for non zero _newAdmin
setModuleLock(safe, _newAdmin != address(0));
podAdmin[_podId] = _newAdmin;
emit UpdatePodAdmin(_podId, _newAdmin);
}
/**
* @dev This will nullify all pod state on this controller
* @dev Update state on _newController
* @dev Update controller to _newController in Safe and MemberToken
* @param _podId The id number of the pod
* @param _newController The address of the new pod controller
* @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list
*/
function migratePodController(
uint256 _podId,
address _newController,
address _prevModule
) external override {
require(_newController != address(0), "Invalid address");
require(
controllerRegistry.isRegistered(_newController),
"Controller not registered"
);
address admin = podAdmin[_podId];
address safe = podIdToSafe[_podId];
require(
msg.sender == admin || msg.sender == safe,
"User not authorized"
);
IControllerBase newController = IControllerBase(_newController);
// nullify current pod state
podAdmin[_podId] = address(0);
podIdToSafe[_podId] = address(0);
safeToPodId[safe] = 0;
// update controller in MemberToken
memberToken.migrateMemberController(_podId, _newController);
// update safe module to _newController
migrateSafeTeller(safe, _newController, _prevModule);
// update pod state in _newController
newController.updatePodState(_podId, admin, safe);
}
/**
* @dev This is called by another version of controller to migrate a pod to this version
* @dev Will only accept calls from registered controllers
* @dev Can only be called once.
* @param _podId The id number of the pod
* @param _podAdmin The address of the pod admin
* @param _safeAddress The address of the safe
*/
function updatePodState(
uint256 _podId,
address _podAdmin,
address _safeAddress
) external override {
require(_safeAddress != address(0), "Invalid address");
require(
controllerRegistry.isRegistered(msg.sender),
"Controller not registered"
);
require(
podAdmin[_podId] == address(0) &&
podIdToSafe[_podId] == address(0) &&
safeToPodId[_safeAddress] == 0,
"Pod already exists"
);
// if there is a pod admin, set state and lock modules
if (_podAdmin != address(0)) {
podAdmin[_podId] = _podAdmin;
setModuleLock(_safeAddress, true);
}
podIdToSafe[_podId] = _safeAddress;
safeToPodId[_safeAddress] = _podId;
setSafeTellerAsGuard(_safeAddress);
emit UpdatePodAdmin(_podId, _podAdmin);
}
/**
* @param operator The address that initiated the action
* @param from The address sending the membership token
* @param to The address recieveing the membership token
* @param ids An array of membership token ids to be transfered
* @param data Passes a flag for an initial creation event
*/
function beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory,
bytes memory data
) external override {
require(msg.sender == address(memberToken), "Not Authorized");
// if create event than side effects have been pre-handled
// only recognise data flags from this controller
if (operator == address(this) && uint8(data[0]) == CREATE_EVENT) return;
for (uint256 i = 0; i < ids.length; i += 1) {
uint256 podId = ids[i];
address safe = podIdToSafe[podId];
address admin = podAdmin[podId];
if (from == address(0)) {
// mint event
// there are no rules operator must be admin, safe or controller
require(
operator == safe ||
operator == admin ||
operator == address(this),
"No Rules Set"
);
onMint(to, safe);
} else if (to == address(0)) {
// burn event
// there are no rules operator must be admin, safe or controller
require(
operator == safe ||
operator == admin ||
operator == address(this),
"No Rules Set"
);
onBurn(from, safe);
} else {
// transfer event
onTransfer(from, to, safe);
}
}
}
}
| 37,525 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.