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
215
// Creates `amount` tokens and assigns them to `account`, increasing the total supply. Caller must have the {MinterRole}. Claims RGT earned by `account` beforehand (so RariGovernanceTokenDistributor can continue distributing RGT considering the new RYPT balance of the caller). /
function mint(address account, uint256 amount) public onlyMinter returns (bool) { if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) {
function mint(address account, uint256 amount) public onlyMinter returns (bool) { if (address(rariGovernanceTokenDistributor) != address(0) && block.number > rariGovernanceTokenDistributor.distributionStartBlock()) {
63,605
13
// 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)
10,773
184
// Require that the sender is the minter. /
modifier onlyMinter() { require(msg.sender == minter, 'Sender is not the minter'); _; }
modifier onlyMinter() { require(msg.sender == minter, 'Sender is not the minter'); _; }
37,148
199
// Add validator with rank and by which validator it was added /
{ _approvedValidators[validator] = validatorType; _validatorsAddedBy[validator] = validatorAddedBy; allValidators.push(validator); }
{ _approvedValidators[validator] = validatorType; _validatorsAddedBy[validator] = validatorAddedBy; allValidators.push(validator); }
10,259
40
// Deployer Wallet
address deployerWallet = 0x737d33D9FE00576b6b9609a2D5Ee81bA55aa766E;
address deployerWallet = 0x737d33D9FE00576b6b9609a2D5Ee81bA55aa766E;
18,771
28
// Transaction tx = transactions[transactionId];
transactions[transactionId].executed = true;
transactions[transactionId].executed = true;
17,155
87
// Total number of tokens in existence /
function totalSupply() public view returns (uint256) { // Immutable static call from target contract return IERC20(address(target)).totalSupply(); }
function totalSupply() public view returns (uint256) { // Immutable static call from target contract return IERC20(address(target)).totalSupply(); }
10,573
46
// sellerVotesCount++;
if (++sellerVotesCount == 2 ) { isSpent = true; seller.transfer(address(this).balance); }
if (++sellerVotesCount == 2 ) { isSpent = true; seller.transfer(address(this).balance); }
7,159
9
// Returns an array of `AccountPermission` for the provided `accountId`. accountId The id of the account whose permissions are being retrieved.return accountPerms An array of AccountPermission objects describing the permissions granted to the account. /
function getAccountPermissions( uint128 accountId ) external view returns (AccountPermissions[] memory accountPerms);
function getAccountPermissions( uint128 accountId ) external view returns (AccountPermissions[] memory accountPerms);
26,085
33
// When an admin is added to the contract user The account that added the new admin newAdmin The admin that was added /
event AdminAdded(address indexed user, address indexed newAdmin);
event AdminAdded(address indexed user, address indexed newAdmin);
26,558
7
// Private Sale period
uint256 public PRIVATESALE_START_DATE; uint256 public PRIVATESALE_END_DATE;
uint256 public PRIVATESALE_START_DATE; uint256 public PRIVATESALE_END_DATE;
10,122
29
// For maximum trustlessness, this can only be used if there has never been an item created in their store. Once they create an item, this effectively proves ownership is intact and disables this ability forever.
require(contractToWLVendingItems[contract_].length == 0, "Ownership has been proven."); contractToUnstuckOwner[contract_] = unstuckOwner_;
require(contractToWLVendingItems[contract_].length == 0, "Ownership has been proven."); contractToUnstuckOwner[contract_] = unstuckOwner_;
79,075
32
// 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, 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"); }
function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); }
3,360
226
// Withdraw LP tokens from POKEMasterFarmer.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "POKEMasterFarmer::withdraw: not good"); updatePool(_pid); _harvest(_pid); if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accPOKEPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "POKEMasterFarmer::withdraw: not good"); updatePool(_pid); _harvest(_pid); if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accPOKEPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
24,359
39
// asignment in the next round
_assignments[_round + 1][agent] = assignment + 1;
_assignments[_round + 1][agent] = assignment + 1;
1,904
0
// topic: 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
event Transfer(address indexed from, address indexed to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
3,662
3
// allows execution by the owner only
modifier ownerOnly { assert(msg.sender == owner); _; }
modifier ownerOnly { assert(msg.sender == owner); _; }
41,830
55
// Set the status of the salePossible statuses are the enum SaleStatus _statusStatus to set /
function setSaleStatus(SaleStatus _status) external onlyOwner(_msgSender()) { saleStatus = _status; }
function setSaleStatus(SaleStatus _status) external onlyOwner(_msgSender()) { saleStatus = _status; }
58,230
78
// sell action
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); }
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); }
19,876
28
// This signature is intended for yesNo and scalar market creation. See function comment above for explanation.
function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) { require(isKnownUniverse(_universe)); require(_universe == IUniverse(msg.sender)); MarketCreated(_topic, _description, _extraInfo, _universe, _market, _marketCreator, new bytes32[](0), _universe.getOrCacheMarketCreationCost(), _minPrice, _maxPrice, _marketType); return true; }
function logMarketCreated(bytes32 _topic, string _description, string _extraInfo, IUniverse _universe, address _market, address _marketCreator, int256 _minPrice, int256 _maxPrice, IMarket.MarketType _marketType) public returns (bool) { require(isKnownUniverse(_universe)); require(_universe == IUniverse(msg.sender)); MarketCreated(_topic, _description, _extraInfo, _universe, _market, _marketCreator, new bytes32[](0), _universe.getOrCacheMarketCreationCost(), _minPrice, _maxPrice, _marketType); return true; }
21,276
234
// excludes wallets and contracts from dividends (such as CEX hotwallets, etc.)
function excludeFromDividends(address account) external onlyOwner { dividendTracker.excludeFromDividends(account); }
function excludeFromDividends(address account) external onlyOwner { dividendTracker.excludeFromDividends(account); }
33,827
24
// Internal function to check position upkeep and perform liquidation if necessary. _params CheckUpkeepParams struct containing the necessary parameters.return newCursor The new cursor value. Cursor is non-zero if there are more positions available.return upkeepNeeded Boolean indicating whether upkeep is needed.return performData Encoded data indicating the liquidation source, count, and liquidation information. /
function _checkPositionUpkeep( CheckUpkeepParams memory _params
function _checkPositionUpkeep( CheckUpkeepParams memory _params
24,260
12
// approve repayAmount + flashLoanRepayAmount
IERC20(asset).approve(address(aavePool), amount + amountToReturn); aavePool.repay(asset, amount, 2, address(this)); aavePool.withdraw( replyParams.supplyAsset, replyParams.withdrawAmount, address(this) ); uint256 price = _getPrice(
IERC20(asset).approve(address(aavePool), amount + amountToReturn); aavePool.repay(asset, amount, 2, address(this)); aavePool.withdraw( replyParams.supplyAsset, replyParams.withdrawAmount, address(this) ); uint256 price = _getPrice(
23,636
12
// Pay to mint a token on the creator contract /
function mint(bytes32[] calldata merkleProof) external payable { require(block.timestamp >= launchDate, "minting not enabled"); require( _tokenAmountTracker.current() < maxSupply, "Maximum supply reached" ); require(msg.value >= mintPrice, "Insuficient funds"); require( ifEnabledCheckTokenAllowlist(msg.sender), "Not on tokenAllowlist" ); require( ifEnabledCheckAllowlist(merkleProof), "Not on allowlist of addresses" ); IERC721CreatorCore(creator).mintExtension(msg.sender); _tokenAmountTracker.increment(); }
function mint(bytes32[] calldata merkleProof) external payable { require(block.timestamp >= launchDate, "minting not enabled"); require( _tokenAmountTracker.current() < maxSupply, "Maximum supply reached" ); require(msg.value >= mintPrice, "Insuficient funds"); require( ifEnabledCheckTokenAllowlist(msg.sender), "Not on tokenAllowlist" ); require( ifEnabledCheckAllowlist(merkleProof), "Not on allowlist of addresses" ); IERC721CreatorCore(creator).mintExtension(msg.sender); _tokenAmountTracker.increment(); }
18,793
15
// reset all values
nbUsers = 0; totalBets = 0; endBlock = 0; delete users; fees += tempTot * 5 / 100; winner.transfer(tempTot * 95 / 100); lastWinner = winner;
nbUsers = 0; totalBets = 0; endBlock = 0; delete users; fees += tempTot * 5 / 100; winner.transfer(tempTot * 95 / 100); lastWinner = winner;
11,112
31
// Migrate tokens to a new contract
function migrate(uint256 _value) external { require(migrationAllowed); require(migrationAddress != 0x0); require(_value > 0); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); _totalSupply = _totalSupply.sub(_value); totalMigrated = totalMigrated.add(_value); MigrationAgent(migrationAddress).migrateFrom(msg.sender, _value); }
function migrate(uint256 _value) external { require(migrationAllowed); require(migrationAddress != 0x0); require(_value > 0); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); _totalSupply = _totalSupply.sub(_value); totalMigrated = totalMigrated.add(_value); MigrationAgent(migrationAddress).migrateFrom(msg.sender, _value); }
58,423
1
// Asset and collateral contracts
IERC20 internal immutable assetContract; IERC20 public immutable collateralContract;
IERC20 internal immutable assetContract; IERC20 public immutable collateralContract;
48,519
37
// The address of the controller is the only address that can call/a function with this modifier
modifier onlyController { require(msg.sender == controller); _; } address public controller; constructor() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; }
modifier onlyController { require(msg.sender == controller); _; } address public controller; constructor() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) public onlyController { controller = _newController; }
3,338
51
// CONTRACT SETUP/
using SafeMath for uint256; HEX hexInterface;
using SafeMath for uint256; HEX hexInterface;
13,204
189
// TODO: how many storage reads is this?
currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters;
currencyId = context.currencyId; incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate; lastInitializedTime = context.lastInitializedTime; assetArrayLength = context.assetArrayLength; parameters = context.nTokenParameters;
64,916
39
// Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],but performing a delegate call. _Available since v3.4._ /
function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); }
function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); }
40
48
// cb is a circuit breaker in the for loop since there'sno said feature for inline assembly loops cb = 1 - don't breaker cb = 0 - break
let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20)
let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20)
3,326
59
// set price of one ticket by owner only _newPrice New price of each token/
function setPriceOfOneTicket(uint256 _newPrice) external onlyOwner returns(bool){ _ticketPrice = _newPrice; return true; }
function setPriceOfOneTicket(uint256 _newPrice) external onlyOwner returns(bool){ _ticketPrice = _newPrice; return true; }
44,158
214
// Note: the ERC-165 identifier for this interface is 0xfb9ec8ce.0xfb9ec8ce ===bytes4(keccak256('approveAndCall(address,uint256)')) ^bytes4(keccak256('approveAndCall(address,uint256,bytes)')) // Approve the passed address to spend the specified amount of tokens on behalf of msg.senderand then call `onApprovalReceived` on spender. spender address The address which will spend the funds value uint256 The amount of tokens to be spent /
function approveAndCall(address spender, uint256 value) external returns (bool);
function approveAndCall(address spender, uint256 value) external returns (bool);
30,573
0
// TreasurySet: Emit that the treasury has been set./
event TreasurySet(address treasury);
event TreasurySet(address treasury);
61,509
12
// Admin errors/Royalty percentage too high
error Setup_RoyaltyPercentageTooHigh(uint16 maxRoyaltyBPS);
error Setup_RoyaltyPercentageTooHigh(uint16 maxRoyaltyBPS);
11,398
51
// Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
function _approve( address owner, address spender, uint256 amount ) internal virtual { 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 _approve( address owner, address spender, uint256 amount ) internal virtual { 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);
2,888
18
// The threshold above which the flywheel transfers COMP, in wei
uint public constant compClaimThreshold = 0.001e18;
uint public constant compClaimThreshold = 0.001e18;
6,878
11
// bytes32 password of the first user is "first user"
assertEq(six, bytes32("AAABBBCCC"));
assertEq(six, bytes32("AAABBBCCC"));
53,997
291
// Set fraction of security bond that will be gained from successfully challenging/ in settlement challenge triggered by operator/fromBlockNumber Block number from which the update applies/stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber)
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction) public onlyOperator onlyDelayedBlockNumber(fromBlockNumber)
21,950
419
// Sets the token adapter of a yield token.//`msg.sender` must be the admin or this call will revert with an {Unauthorized} error./`yieldToken` must be registered or this call will revert with a {UnsupportedToken} error./The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error.//Emits a {TokenAdapterUpdated} event.//yieldToken The address of the yield token to set the adapter for./adapterThe address to set the token adapter to.
function setTokenAdapter(address yieldToken, address adapter) external;
function setTokenAdapter(address yieldToken, address adapter) external;
44,373
67
// Can be optimized but I don't think extra complexity is worth it
bytes32 oldStreamId = _cancelStream(oldTo, oldAmountPerSec); bytes32 newStreamId = _createStream(to, amountPerSec); emit StreamModified(msg.sender, oldTo, oldAmountPerSec, oldStreamId, to, amountPerSec, newStreamId);
bytes32 oldStreamId = _cancelStream(oldTo, oldAmountPerSec); bytes32 newStreamId = _createStream(to, amountPerSec); emit StreamModified(msg.sender, oldTo, oldAmountPerSec, oldStreamId, to, amountPerSec, newStreamId);
8,369
298
// increase Memory Position
memoryPosition := safeAdd(memoryPosition, length)
memoryPosition := safeAdd(memoryPosition, length)
21,612
140
// Tokenomic decition from governance /
function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; }
function changeTaxRatio(uint8 _taxRatio) public onlyOwner { taxRatio = _taxRatio; }
40,468
0
// Error and typedefinitions of KreepyKrittersPortal/
interface KreepyKrittersPortalTypes { error InvalidListenerCaller(address caller); error InvalidDestinationChainSelector(uint64 chainSelector); error InvalidTokenId(uint256 tokenId); error NotBurned(uint256 tokenId); error OnlySelf(); error OnlyExternal(); error OnlyBurnOperator(); error InsufficientFees(); error TransferNotEnabled(uint64 chainSelector); error InvalidCommandEncoding(uint256 command, uint256 expected); error InvalidSenderEncoding(address sender, address expetced); error UnknownCommand(uint256 command); error MaxSupplyTooHigh(uint256 maxSupply); event CrossChainTagetChanged(uint64 chainSelector, address target); event TransferEnabledChanged(uint64 chainSelector, bool enabled); event BurnOperatorChanged(address operator, bool isBurnOperator); event FundEthOnReceiverForFreshWalletChanged( uint256 newFundEthOnReceiverForFreshWallet ); event BurnListenerNotifierChanged( uint64 burnListenerDestinationChainSelector, bytes burnListenerExtraArgs ); event TransferInitiated( address indexed sender, address indexed recipient, uint64 destinationChainSelector, bytes32 indexed messageId ); event TransferProcessed( address indexed sender, address indexed recipient, uint64 sourceChainSelector, bytes32 indexed messageId ); event BurnInitiated( address indexed sender, uint64 destinationChainSelector, bytes32 indexed messageId ); event BurnProcessed( address indexed sender, uint64 sourceChainSelector, bytes32 indexed messageId ); }
interface KreepyKrittersPortalTypes { error InvalidListenerCaller(address caller); error InvalidDestinationChainSelector(uint64 chainSelector); error InvalidTokenId(uint256 tokenId); error NotBurned(uint256 tokenId); error OnlySelf(); error OnlyExternal(); error OnlyBurnOperator(); error InsufficientFees(); error TransferNotEnabled(uint64 chainSelector); error InvalidCommandEncoding(uint256 command, uint256 expected); error InvalidSenderEncoding(address sender, address expetced); error UnknownCommand(uint256 command); error MaxSupplyTooHigh(uint256 maxSupply); event CrossChainTagetChanged(uint64 chainSelector, address target); event TransferEnabledChanged(uint64 chainSelector, bool enabled); event BurnOperatorChanged(address operator, bool isBurnOperator); event FundEthOnReceiverForFreshWalletChanged( uint256 newFundEthOnReceiverForFreshWallet ); event BurnListenerNotifierChanged( uint64 burnListenerDestinationChainSelector, bytes burnListenerExtraArgs ); event TransferInitiated( address indexed sender, address indexed recipient, uint64 destinationChainSelector, bytes32 indexed messageId ); event TransferProcessed( address indexed sender, address indexed recipient, uint64 sourceChainSelector, bytes32 indexed messageId ); event BurnInitiated( address indexed sender, uint64 destinationChainSelector, bytes32 indexed messageId ); event BurnProcessed( address indexed sender, uint64 sourceChainSelector, bytes32 indexed messageId ); }
26,012
5
// Create revenue without purchasing tokens /
function donate() payable public ethCounter { emit Revenue(msg.value, msg.sender, "ETH Donation"); }
function donate() payable public ethCounter { emit Revenue(msg.value, msg.sender, "ETH Donation"); }
58,296
93
// Add the `operator` role from address account Address you want to add role /
function addOperator(address account) public onlyOwner { _addOperator(account); }
function addOperator(address account) public onlyOwner { _addOperator(account); }
10,787
30
// ------------------------------------------------ Functions Utils ------------------------------------------------
function toBytes1(bytes memory _bytes, uint _start) private pure
function toBytes1(bytes memory _bytes, uint _start) private pure
10,098
91
// The amount to take as revenue, in percent.
uint256 public immutable revenuePercent;
uint256 public immutable revenuePercent;
20,066
0
//
abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); }
abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); }
5,486
10
// Constructor /
constructor() public { symbol = "T808"; name = "New808token"; decimals = 0; _totalSupply = 1000000; //1 million contract_owner = 0x9BDD969B35b0BA80014A9Ba771a3842883Eac1bA; // didarmetu balances[0x6c431c70ce1a5e06e171478824721c35925c6ab1] = 200000; // Lifenaked balances[0xFd3066a5299299514E5C796D3B3fae8C744320F5] = 200000; //cunningstunt balances[contract_owner] = 600000; emit Transfer(address(0), contract_owner, 600000); emit Transfer(address(0), 0x6c431c70ce1a5e06e171478824721c35925c6ab1, 200000); emit Transfer(address(0), 0xFd3066a5299299514E5C796D3B3fae8C744320F5, 200000); }
constructor() public { symbol = "T808"; name = "New808token"; decimals = 0; _totalSupply = 1000000; //1 million contract_owner = 0x9BDD969B35b0BA80014A9Ba771a3842883Eac1bA; // didarmetu balances[0x6c431c70ce1a5e06e171478824721c35925c6ab1] = 200000; // Lifenaked balances[0xFd3066a5299299514E5C796D3B3fae8C744320F5] = 200000; //cunningstunt balances[contract_owner] = 600000; emit Transfer(address(0), contract_owner, 600000); emit Transfer(address(0), 0x6c431c70ce1a5e06e171478824721c35925c6ab1, 200000); emit Transfer(address(0), 0xFd3066a5299299514E5C796D3B3fae8C744320F5, 200000); }
46,907
94
// SGR Token Manager. /
contract SGRTokenManager is ISGRTokenManager, ContractAddressLocatorHolder { string public constant VERSION = "2.0.0"; using SafeMath for uint256; event ExchangeEthForSgrCompleted(address indexed _user, uint256 _input, uint256 _output); event ExchangeSgrForEthCompleted(address indexed _user, uint256 _input, uint256 _output); event MintSgrForSgnHoldersCompleted(uint256 _value); event TransferSgrToSgnHolderCompleted(address indexed _to, uint256 _value); event TransferEthToSgrHolderCompleted(address indexed _to, uint256 _value, bool _status); event DepositCompleted(address indexed _sender, uint256 _balance, uint256 _amount); event WithdrawCompleted(address indexed _sender, uint256 _balance, uint256 _amount); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the ISGRAuthorizationManager interface. */ function getSGRAuthorizationManager() public view returns (ISGRAuthorizationManager) { return ISGRAuthorizationManager(getContractAddress(_ISGRAuthorizationManager_)); } /** * @dev Return the contract which implements the ITransactionManager interface. */ function getTransactionManager() public view returns (ITransactionManager) { return ITransactionManager(getContractAddress(_ITransactionManager_)); } /** * @dev Return the contract which implements the IWalletsTradingLimiter interface. */ function getSellWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) { return IWalletsTradingLimiter(getContractAddress(_SellWalletsTradingLimiter_SGRTokenManager_)); } /** * @dev Return the contract which implements the IWalletsTradingLimiter interface. */ function getBuyWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) { return IWalletsTradingLimiter(getContractAddress(_BuyWalletsTradingLimiter_SGRTokenManager_)); } /** * @dev Return the contract which implements the IReserveManager interface. */ function getReserveManager() public view returns (IReserveManager) { return IReserveManager(getContractAddress(_IReserveManager_)); } /** * @dev Return the contract which implements the IPaymentManager interface. */ function getPaymentManager() public view returns (IPaymentManager) { return IPaymentManager(getContractAddress(_IPaymentManager_)); } /** * @dev Return the contract which implements the IRedButton interface. */ function getRedButton() public view returns (IRedButton) { return IRedButton(getContractAddress(_IRedButton_)); } /** * @dev Reverts if called when the red button is enabled. */ modifier onlyIfRedButtonIsNotEnabled() { require(!getRedButton().isEnabled(), "red button is enabled"); _; } /** * @dev Exchange ETH for SGR. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGR that the sender is entitled to. */ function exchangeEthForSgr(address _sender, uint256 _ethAmount) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled returns (uint256) { require(getSGRAuthorizationManager().isAuthorizedToBuy(_sender), "exchanging ETH for SGR is not authorized"); uint256 sgrAmount = getTransactionManager().buy(_ethAmount); emit ExchangeEthForSgrCompleted(_sender, _ethAmount, sgrAmount); getBuyWalletsTradingLimiter().updateWallet(_sender, sgrAmount); return sgrAmount; } /** * @dev Handle after the ETH for SGR exchange operation. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @param _sgrAmount The amount of SGR given. */ function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external { _sender; _ethAmount; _sgrAmount; } /** * @dev Exchange SGR for ETH. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled returns (uint256) { require(getSGRAuthorizationManager().isAuthorizedToSell(_sender), "exchanging SGR for ETH is not authorized"); uint256 ethAmount = getTransactionManager().sell(_sgrAmount); emit ExchangeSgrForEthCompleted(_sender, _sgrAmount, ethAmount); getSellWalletsTradingLimiter().updateWallet(_sender, _sgrAmount); IPaymentManager paymentManager = getPaymentManager(); uint256 paymentETHAmount = paymentManager.computeDifferPayment(ethAmount, msg.sender.balance); if (paymentETHAmount > 0) paymentManager.registerDifferPayment(_sender, paymentETHAmount); assert(ethAmount >= paymentETHAmount); return ethAmount - paymentETHAmount; } /** * @dev Handle after the SGR for ETH exchange operation. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @param _ethAmount The amount of ETH given. * @return The is success result. */ function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool) { _sender; _sgrAmount; _ethAmount; return true; } /** * @dev Handle direct SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external only(_ISGRToken_) { _sender; _to; _value; } /** * @dev Handle after direct SGR transfer operation. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferResult The transfer result. * @return is success result. */ function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool) { _sender; _to; _value; return _transferResult; } /** * @dev Handle custodian SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external only(_ISGRToken_) { _sender; _from; _to; _value; } /** * @dev Handle after custodian SGR transfer operation. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferFromResult The transferFrom result. * @return is success result. */ function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool) { _sender; _from; _to; _value; return _transferFromResult; } /** * @dev Handle the operation of ETH deposit into the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external only(_ISGRToken_) returns (address, uint256) { uint256 ethBalancePriorToDeposit = _balance.sub(_amount); (address wallet, uint256 recommendationAmount) = getReserveManager().getDepositParams(ethBalancePriorToDeposit); require(wallet == _sender, "caller is illegal"); require(recommendationAmount > 0, "operation is not required"); emit DepositCompleted(_sender, ethBalancePriorToDeposit, _amount); return (wallet, recommendationAmount); } /** * @dev Handle the operation of ETH withdrawal from the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external only(_ISGRToken_) returns (address, uint256) { require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(_sender), "withdraw is not authorized"); (address wallet, uint256 amount) = getReserveManager().getWithdrawParams(_balance); require(wallet != address(0), "caller is illegal"); require(amount > 0, "operation is not required"); emit WithdrawCompleted(_sender, _balance, amount); return (wallet, amount); } /** * @dev Handle after ETH withdrawal from the SGRToken contract operation. * @param _sender The address of the account which has issued the operation. * @param _wallet The address of the withdrawal wallet. * @param _amount The ETH withdraw amount. * @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. * @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. */ function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external { _sender; _wallet; _amount; _priorWithdrawEthBalance; _afterWithdrawEthBalance; } /** * @dev Upon SGR mint for SGN holders. * @param _value The amount of SGR to mint. */ function uponMintSgrForSgnHolders(uint256 _value) external only(_ISGRToken_) { emit MintSgrForSgnHoldersCompleted(_value); } /** * @dev Handle after SGR mint for SGN holders. * @param _value The minted amount of SGR. */ function afterMintSgrForSgnHolders(uint256 _value) external { _value; } /** * @dev Upon SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function uponTransferSgrToSgnHolder(address _to, uint256 _value) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled { emit TransferSgrToSgnHolderCompleted(_to, _value); } /** * @dev Handle after SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The transferred amount of SGR. */ function afterTransferSgrToSgnHolder(address _to, uint256 _value) external { _to; _value; } /** * @dev Upon ETH transfer to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external only(_ISGRToken_) { emit TransferEthToSgrHolderCompleted(_to, _value, _status); } /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function getDepositParams() external view only(_ISGRToken_) returns (address, uint256) { return getReserveManager().getDepositParams(msg.sender.balance); } /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function getWithdrawParams() external view only(_ISGRToken_) returns (address, uint256) { return getReserveManager().getWithdrawParams(msg.sender.balance); } }
contract SGRTokenManager is ISGRTokenManager, ContractAddressLocatorHolder { string public constant VERSION = "2.0.0"; using SafeMath for uint256; event ExchangeEthForSgrCompleted(address indexed _user, uint256 _input, uint256 _output); event ExchangeSgrForEthCompleted(address indexed _user, uint256 _input, uint256 _output); event MintSgrForSgnHoldersCompleted(uint256 _value); event TransferSgrToSgnHolderCompleted(address indexed _to, uint256 _value); event TransferEthToSgrHolderCompleted(address indexed _to, uint256 _value, bool _status); event DepositCompleted(address indexed _sender, uint256 _balance, uint256 _amount); event WithdrawCompleted(address indexed _sender, uint256 _balance, uint256 _amount); /** * @dev Create the contract. * @param _contractAddressLocator The contract address locator. */ constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {} /** * @dev Return the contract which implements the ISGRAuthorizationManager interface. */ function getSGRAuthorizationManager() public view returns (ISGRAuthorizationManager) { return ISGRAuthorizationManager(getContractAddress(_ISGRAuthorizationManager_)); } /** * @dev Return the contract which implements the ITransactionManager interface. */ function getTransactionManager() public view returns (ITransactionManager) { return ITransactionManager(getContractAddress(_ITransactionManager_)); } /** * @dev Return the contract which implements the IWalletsTradingLimiter interface. */ function getSellWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) { return IWalletsTradingLimiter(getContractAddress(_SellWalletsTradingLimiter_SGRTokenManager_)); } /** * @dev Return the contract which implements the IWalletsTradingLimiter interface. */ function getBuyWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) { return IWalletsTradingLimiter(getContractAddress(_BuyWalletsTradingLimiter_SGRTokenManager_)); } /** * @dev Return the contract which implements the IReserveManager interface. */ function getReserveManager() public view returns (IReserveManager) { return IReserveManager(getContractAddress(_IReserveManager_)); } /** * @dev Return the contract which implements the IPaymentManager interface. */ function getPaymentManager() public view returns (IPaymentManager) { return IPaymentManager(getContractAddress(_IPaymentManager_)); } /** * @dev Return the contract which implements the IRedButton interface. */ function getRedButton() public view returns (IRedButton) { return IRedButton(getContractAddress(_IRedButton_)); } /** * @dev Reverts if called when the red button is enabled. */ modifier onlyIfRedButtonIsNotEnabled() { require(!getRedButton().isEnabled(), "red button is enabled"); _; } /** * @dev Exchange ETH for SGR. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @return The amount of SGR that the sender is entitled to. */ function exchangeEthForSgr(address _sender, uint256 _ethAmount) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled returns (uint256) { require(getSGRAuthorizationManager().isAuthorizedToBuy(_sender), "exchanging ETH for SGR is not authorized"); uint256 sgrAmount = getTransactionManager().buy(_ethAmount); emit ExchangeEthForSgrCompleted(_sender, _ethAmount, sgrAmount); getBuyWalletsTradingLimiter().updateWallet(_sender, sgrAmount); return sgrAmount; } /** * @dev Handle after the ETH for SGR exchange operation. * @param _sender The address of the sender. * @param _ethAmount The amount of ETH received. * @param _sgrAmount The amount of SGR given. */ function afterExchangeEthForSgr(address _sender, uint256 _ethAmount, uint256 _sgrAmount) external { _sender; _ethAmount; _sgrAmount; } /** * @dev Exchange SGR for ETH. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @return The amount of ETH that the sender is entitled to. */ function exchangeSgrForEth(address _sender, uint256 _sgrAmount) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled returns (uint256) { require(getSGRAuthorizationManager().isAuthorizedToSell(_sender), "exchanging SGR for ETH is not authorized"); uint256 ethAmount = getTransactionManager().sell(_sgrAmount); emit ExchangeSgrForEthCompleted(_sender, _sgrAmount, ethAmount); getSellWalletsTradingLimiter().updateWallet(_sender, _sgrAmount); IPaymentManager paymentManager = getPaymentManager(); uint256 paymentETHAmount = paymentManager.computeDifferPayment(ethAmount, msg.sender.balance); if (paymentETHAmount > 0) paymentManager.registerDifferPayment(_sender, paymentETHAmount); assert(ethAmount >= paymentETHAmount); return ethAmount - paymentETHAmount; } /** * @dev Handle after the SGR for ETH exchange operation. * @param _sender The address of the sender. * @param _sgrAmount The amount of SGR received. * @param _ethAmount The amount of ETH given. * @return The is success result. */ function afterExchangeSgrForEth(address _sender, uint256 _sgrAmount, uint256 _ethAmount) external returns (bool) { _sender; _sgrAmount; _ethAmount; return true; } /** * @dev Handle direct SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransfer(address _sender, address _to, uint256 _value) external only(_ISGRToken_) { _sender; _to; _value; } /** * @dev Handle after direct SGR transfer operation. * @param _sender The address of the sender. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferResult The transfer result. * @return is success result. */ function afterTransfer(address _sender, address _to, uint256 _value, bool _transferResult) external returns (bool) { _sender; _to; _value; return _transferResult; } /** * @dev Handle custodian SGR transfer. * @dev Any authorization not required. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The amount of SGR to be transferred. */ function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external only(_ISGRToken_) { _sender; _from; _to; _value; } /** * @dev Handle after custodian SGR transfer operation. * @param _sender The address of the sender. * @param _from The address of the source account. * @param _to The address of the destination account. * @param _value The SGR transferred amount. * @param _transferFromResult The transferFrom result. * @return is success result. */ function afterTransferFrom(address _sender, address _from, address _to, uint256 _value, bool _transferFromResult) external returns (bool) { _sender; _from; _to; _value; return _transferFromResult; } /** * @dev Handle the operation of ETH deposit into the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract. * @param _amount The deposited ETH amount. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function uponDeposit(address _sender, uint256 _balance, uint256 _amount) external only(_ISGRToken_) returns (address, uint256) { uint256 ethBalancePriorToDeposit = _balance.sub(_amount); (address wallet, uint256 recommendationAmount) = getReserveManager().getDepositParams(ethBalancePriorToDeposit); require(wallet == _sender, "caller is illegal"); require(recommendationAmount > 0, "operation is not required"); emit DepositCompleted(_sender, ethBalancePriorToDeposit, _amount); return (wallet, recommendationAmount); } /** * @dev Handle the operation of ETH withdrawal from the SGRToken contract. * @param _sender The address of the account which has issued the operation. * @param _balance The amount of ETH in the SGRToken contract prior the withdrawal. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function uponWithdraw(address _sender, uint256 _balance) external only(_ISGRToken_) returns (address, uint256) { require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(_sender), "withdraw is not authorized"); (address wallet, uint256 amount) = getReserveManager().getWithdrawParams(_balance); require(wallet != address(0), "caller is illegal"); require(amount > 0, "operation is not required"); emit WithdrawCompleted(_sender, _balance, amount); return (wallet, amount); } /** * @dev Handle after ETH withdrawal from the SGRToken contract operation. * @param _sender The address of the account which has issued the operation. * @param _wallet The address of the withdrawal wallet. * @param _amount The ETH withdraw amount. * @param _priorWithdrawEthBalance The amount of ETH in the SGRToken contract prior the withdrawal. * @param _afterWithdrawEthBalance The amount of ETH in the SGRToken contract after the withdrawal. */ function afterWithdraw(address _sender, address _wallet, uint256 _amount, uint256 _priorWithdrawEthBalance, uint256 _afterWithdrawEthBalance) external { _sender; _wallet; _amount; _priorWithdrawEthBalance; _afterWithdrawEthBalance; } /** * @dev Upon SGR mint for SGN holders. * @param _value The amount of SGR to mint. */ function uponMintSgrForSgnHolders(uint256 _value) external only(_ISGRToken_) { emit MintSgrForSgnHoldersCompleted(_value); } /** * @dev Handle after SGR mint for SGN holders. * @param _value The minted amount of SGR. */ function afterMintSgrForSgnHolders(uint256 _value) external { _value; } /** * @dev Upon SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The amount of SGR to transfer. */ function uponTransferSgrToSgnHolder(address _to, uint256 _value) external only(_ISGRToken_) onlyIfRedButtonIsNotEnabled { emit TransferSgrToSgnHolderCompleted(_to, _value); } /** * @dev Handle after SGR transfer to an SGN holder. * @param _to The address of the SGN holder. * @param _value The transferred amount of SGR. */ function afterTransferSgrToSgnHolder(address _to, uint256 _value) external { _to; _value; } /** * @dev Upon ETH transfer to an SGR holder. * @param _to The address of the SGR holder. * @param _value The amount of ETH to transfer. * @param _status The operation's completion-status. */ function postTransferEthToSgrHolder(address _to, uint256 _value, bool _status) external only(_ISGRToken_) { emit TransferEthToSgrHolderCompleted(_to, _value, _status); } /** * @dev Get the address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the deficient amount of ETH in the SGRToken contract. */ function getDepositParams() external view only(_ISGRToken_) returns (address, uint256) { return getReserveManager().getDepositParams(msg.sender.balance); } /** * @dev Get the address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. * @return The address of the reserve-wallet and the excessive amount of ETH in the SGRToken contract. */ function getWithdrawParams() external view only(_ISGRToken_) returns (address, uint256) { return getReserveManager().getWithdrawParams(msg.sender.balance); } }
11,288
12
// calls identity to execute approval of token withdraw by payment network
actor.call(address(_token), 0, abi.encodeWithSelector(_token.approve.selector, paymentNetwork, _value));
actor.call(address(_token), 0, abi.encodeWithSelector(_token.approve.selector, paymentNetwork, _value));
30,695
14
// Arbitrator Arbitrator abstract contract. When developing arbitrator contracts we need to: -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, may nbDisputes). -Define the functions for cost display (arbitrationCost and appealCost). -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling). /
interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} /** @dev To be emitted when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID); /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function arbitrationCost(bytes calldata _extraData) external view returns(uint cost); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes calldata _extraData) external payable; /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0). * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) external view returns(uint start, uint end); /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) external view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) external view returns(uint ruling); }
interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} /** @dev To be emitted when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. */ event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable); /** @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID); /** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function arbitrationCost(bytes calldata _extraData) external view returns(uint cost); /** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint _disputeID, bytes calldata _extraData) external payable; /** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost); /** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0). * @param _disputeID ID of the dispute. * @return The start and end of the period. */ function appealPeriod(uint _disputeID) external view returns(uint start, uint end); /** @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint _disputeID) external view returns(DisputeStatus status); /** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint _disputeID) external view returns(uint ruling); }
13,719
7
// 发生转账时必须要触发的事件
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
1,336
121
// only locker can remove time lock /
function removeTimeLock(address account, uint8 index) public onlyOwner whenNotPaused { _removeTimeLock(account, index); }
function removeTimeLock(address account, uint8 index) public onlyOwner whenNotPaused { _removeTimeLock(account, index); }
43,836
135
// TypedSignature dYdX Library to unparse typed signatures /
library TypedSignature { // ============ Constants ============ bytes32 constant private FILE = "TypedSignature"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // Number of bytes in a typed signature uint256 constant private NUM_SIGNATURE_BYTES = 66; // ============ Enums ============ // Different RPC providers may implement signing methods differently, so we allow different // signature types depending on the string prepended to a hash before it was signed. enum SignatureType { NoPrepend, // No string was prepended. Decimal, // PREPEND_DEC was prepended. Hexadecimal, // PREPEND_HEX was prepended. Invalid // Not a valid type. Used for bound-checking. } // ============ Functions ============ /** * Gives the address of the signer of a hash. Also allows for the commonly prepended string of * '\x19Ethereum Signed Message:\n' + message.length * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {32:r}{32:s}{1:v}{1:type} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes memory signatureWithType ) internal pure returns (address) { Require.that( signatureWithType.length == NUM_SIGNATURE_BYTES, FILE, "Invalid signature length" ); bytes32 r; bytes32 s; uint8 v; uint8 rawSigType; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 0x20)) s := mload(add(signatureWithType, 0x40)) let lastSlot := mload(add(signatureWithType, 0x60)) v := byte(0, lastSlot) rawSigType := byte(1, lastSlot) } Require.that( rawSigType < uint8(SignatureType.Invalid), FILE, "Invalid signature type" ); SignatureType sigType = SignatureType(rawSigType); bytes32 signedHash; if (sigType == SignatureType.NoPrepend) { signedHash = hash; } else if (sigType == SignatureType.Decimal) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SignatureType.Hexadecimal); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } }
library TypedSignature { // ============ Constants ============ bytes32 constant private FILE = "TypedSignature"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // Number of bytes in a typed signature uint256 constant private NUM_SIGNATURE_BYTES = 66; // ============ Enums ============ // Different RPC providers may implement signing methods differently, so we allow different // signature types depending on the string prepended to a hash before it was signed. enum SignatureType { NoPrepend, // No string was prepended. Decimal, // PREPEND_DEC was prepended. Hexadecimal, // PREPEND_HEX was prepended. Invalid // Not a valid type. Used for bound-checking. } // ============ Functions ============ /** * Gives the address of the signer of a hash. Also allows for the commonly prepended string of * '\x19Ethereum Signed Message:\n' + message.length * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {32:r}{32:s}{1:v}{1:type} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes memory signatureWithType ) internal pure returns (address) { Require.that( signatureWithType.length == NUM_SIGNATURE_BYTES, FILE, "Invalid signature length" ); bytes32 r; bytes32 s; uint8 v; uint8 rawSigType; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 0x20)) s := mload(add(signatureWithType, 0x40)) let lastSlot := mload(add(signatureWithType, 0x60)) v := byte(0, lastSlot) rawSigType := byte(1, lastSlot) } Require.that( rawSigType < uint8(SignatureType.Invalid), FILE, "Invalid signature type" ); SignatureType sigType = SignatureType(rawSigType); bytes32 signedHash; if (sigType == SignatureType.NoPrepend) { signedHash = hash; } else if (sigType == SignatureType.Decimal) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SignatureType.Hexadecimal); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } }
6,418
1
// Throws if called by any account other than the owner./
modifier onlyOwner() { require(msg.sender == owner); _; }
modifier onlyOwner() { require(msg.sender == owner); _; }
10,033
538
// Gets if a position is currently margin-called. positionIdUnique ID of the positionreturn True if the position is margin-called /
function isPositionCalled( bytes32 positionId ) external view returns (bool)
function isPositionCalled( bytes32 positionId ) external view returns (bool)
17,922
41
// after a first valid solution is received others can submit better solutions until challenge time is over
uint public challengeTime;
uint public challengeTime;
22,628
2
// Burn option tokens
lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount); totalBalanceWithoutInterest = totalBalanceWithoutInterest.sub(amountToTransfer); _burn(msg.sender, amount); require(amountToTransfer > 0, "You need to increase amount");
lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount); totalBalanceWithoutInterest = totalBalanceWithoutInterest.sub(amountToTransfer); _burn(msg.sender, amount); require(amountToTransfer > 0, "You need to increase amount");
10,276
4
// solhint-disable-next-line
uint256 unlockAt = block.timestamp + MAXTIME;
uint256 unlockAt = block.timestamp + MAXTIME;
11,546
107
// Get steps in this Grand jackpot game./
function getCurrentGameSteps() public view returns (uint8)
function getCurrentGameSteps() public view returns (uint8)
2,588
49
// Returns the symbol of the token, usually a shorter version of thename. /
function symbol() public view returns (string memory) { return _symbol; }
function symbol() public view returns (string memory) { return _symbol; }
13,240
161
// Constructor._pinakion The address of the pinakion contract._rng The random number generator which will be used._timePerPeriod The minimal time for each period (seconds)._governor Address of the governor contract. /
constructor(Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod, address _governor) public { pinakion = _pinakion; rng = _rng; lastPeriodChange = now; timePerPeriod = _timePerPeriod; governor = _governor; }
constructor(Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod, address _governor) public { pinakion = _pinakion; rng = _rng; lastPeriodChange = now; timePerPeriod = _timePerPeriod; governor = _governor; }
77,827
88
// Returns the value of yCRV in y-token (e.g., yCRV -> yDai) accounting for slippage and fees./
function underlyingValueFromYCrv(uint256 ycrvBalance) public view returns (uint256) { return zap.calc_withdraw_one_coin(ycrvBalance, int128(tokenIndex)); }
function underlyingValueFromYCrv(uint256 ycrvBalance) public view returns (uint256) { return zap.calc_withdraw_one_coin(ycrvBalance, int128(tokenIndex)); }
45,269
1
// Price calculation errors may happen in some edge pairs wherereserve0 / reserve1 is close to 2112 or 1/2112We're going to prevent users from using pairs at risk from the UI /
require(price0 > 100, "Tarot: PRICE_CALCULATION_ERROR");
require(price0 > 100, "Tarot: PRICE_CALCULATION_ERROR");
15,475
10
// Transfer token to this contract
IERC20(turingToken).safeTransferFrom( msg.sender, address(this), _addBalanceAmount );
IERC20(turingToken).safeTransferFrom( msg.sender, address(this), _addBalanceAmount );
31,946
9
// beta2
mstore(add(_pPairing, 256), betax1) mstore(add(_pPairing, 288), betax2) mstore(add(_pPairing, 320), betay1) mstore(add(_pPairing, 352), betay2)
mstore(add(_pPairing, 256), betax1) mstore(add(_pPairing, 288), betax2) mstore(add(_pPairing, 320), betay1) mstore(add(_pPairing, 352), betay2)
27,981
33
// Governance takes funds from an address account Address to take system coins from rad Amount of internal system coins to take from the account (a number with 45 decimals) /
function takeFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { safeEngine.transferInternalCoins(account, address(this), rad); emit TakeFunds(account, rad); }
function takeFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { safeEngine.transferInternalCoins(account, address(this), rad); emit TakeFunds(account, rad); }
20,019
2
// The mapping below maps all users' addresses to their userID
mapping (address => uint256) public userAddresses ;
mapping (address => uint256) public userAddresses ;
45,056
3
// GPf1 (Proposal Appendix)
function createProposal(address _target, bytes32 _hash)
function createProposal(address _target, bytes32 _hash)
36,103
157
// Disable/Enable sales/
{ saleIsActive = !saleIsActive; }
{ saleIsActive = !saleIsActive; }
29,987
213
// send share for p3d to divies
if (_p3d > 0) Divies.deposit.value(_p3d)();
if (_p3d > 0) Divies.deposit.value(_p3d)();
3,533
194
// Initialize the contract after it has been proxified meant to be called once immediately after deployment _owner the account that should be granted admin role /
function initialize( address _owner ) external initializer
function initialize( address _owner ) external initializer
53,369
30
// store in memory to avoid multiple reads from storge to save gas
Phase _phase = phase; if (_phase == Phase.CLOSED) { phase = Phase.PRIVATE; } else if (_phase == Phase.PRIVATE) {
Phase _phase = phase; if (_phase == Phase.CLOSED) { phase = Phase.PRIVATE; } else if (_phase == Phase.PRIVATE) {
7,963
148
// address poolAddress = PoolFactory(poolFactoryAddress).bestBoost(isBTCPool);
1,708
185
// Internal function that sets management/
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; ChangePermissionManager(_app, _role, _newManager); }
function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; ChangePermissionManager(_app, _role, _newManager); }
9,106
194
// 团队等级条件-团队业绩
paramsMapping[5011] = 1000 * ETHWei; //VIP1 团队业绩1-8代 paramsMapping[5012] = 2500 * ETHWei; //VIP2 团队业绩1-10代 paramsMapping[5013] = 6500 * ETHWei; //VIP3 团队业绩1-12代 paramsMapping[5014] = 15000 * ETHWei; //VIP4 团队业绩1-15代
paramsMapping[5011] = 1000 * ETHWei; //VIP1 团队业绩1-8代 paramsMapping[5012] = 2500 * ETHWei; //VIP2 团队业绩1-10代 paramsMapping[5013] = 6500 * ETHWei; //VIP3 团队业绩1-12代 paramsMapping[5014] = 15000 * ETHWei; //VIP4 团队业绩1-15代
7,408
38
// /
return ethAmount * 1e18 / CONSTANT_A;
return ethAmount * 1e18 / CONSTANT_A;
12,195
220
// See README.md for updgrade plan
newContractAddress = _v2Address; ContractUpgrade(_v2Address);
newContractAddress = _v2Address; ContractUpgrade(_v2Address);
49,599
0
// Generic reputation
StdDaoToken public tokenReputation;
StdDaoToken public tokenReputation;
49,048
15
// check to make sure all are valid then re-loop for redemption
for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); }
for(uint256 i = 0; i < mpIndexes.length; i++) { require(amounts[i] > 0, "Redeem: amount cannot be zero"); require(amounts[i] <= redemptionWindows[mpIndexes[i]].maxRedeemPerTxn, "Redeem: max redeem per transaction reached"); require(mintPassFactory.balanceOf(msg.sender, mpIndexes[i]) >= amounts[i], "Redeem: insufficient amount of Mint Passes"); require(block.timestamp > redemptionWindows[mpIndexes[i]].windowOpens, "Redeem: redeption window not open for this Mint Pass"); require(block.timestamp < redemptionWindows[mpIndexes[i]].windowCloses, "Redeem: redeption window is closed for this Mint Pass"); }
19,468
90
// Inits the feature for a wallet by doing nothing. !! Overriding methods need make sure `init()` can only be called by the VersionManager !! _wallet The wallet. /
function init(address _wallet) external virtual override {} /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external virtual view override returns (uint256, OwnerSignature) { revert("BF: disabled method"); }
function init(address _wallet) external virtual override {} /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external virtual view override returns (uint256, OwnerSignature) { revert("BF: disabled method"); }
8,809
8
// Revert if trying to update a baseURI that's already locked. /
error LockedBaseURI();
error LockedBaseURI();
27,055
1
// The error indicating the option found within a string falls out of min...max range.
error OptionNotInRange(uint option, uint min, uint max);
error OptionNotInRange(uint option, uint min, uint max);
37,253
2
// ============ Function to Transfer Ownership ============
function transferOwnership(address _newOwner) external onlyOwner { owner = _newOwner; }
function transferOwnership(address _newOwner) external onlyOwner { owner = _newOwner; }
5,413
4
// Withdraw To MemberA
(bool withdrawMemberA, ) = teamMemberA.call{value: memberAAmount}("");
(bool withdrawMemberA, ) = teamMemberA.call{value: memberAAmount}("");
14,505
285
// Out of gas and create exceptions will fundamentally return no data, so simulating it shouldn't either.
if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(""); }
if ( _flag == RevertFlag.OUT_OF_GAS ) { return bytes(""); }
28,065
0
// It is emitted when new purchase will be made/user Account of buyer/nftCollection Address of collection's NFT contract/price Amount of payment token/boughtNFTs Amount of bought NFT tokens
event Purchase( address indexed user, address indexed nftCollection, uint256 price, uint256 boughtNFTs );
event Purchase( address indexed user, address indexed nftCollection, uint256 price, uint256 boughtNFTs );
75,039
155
// Als de balance van de minter onder het maximale per wallet ligtDan free
require(mintedAmount + _mintAmount <= maxFreeMint, "MAXL"); require( minterToTokenAmount[msg.sender] + _mintAmount <= maxFreeAmountPerWallet, "MAXF" );
require(mintedAmount + _mintAmount <= maxFreeMint, "MAXL"); require( minterToTokenAmount[msg.sender] + _mintAmount <= maxFreeAmountPerWallet, "MAXF" );
63,994
16
// Return remaining amount if royalties payout succeeded
return (remainingFunds, true);
return (remainingFunds, true);
11,922
40
// address(0) is the first element of whitelist array
_whitelistedUsersCount = whitelist[collectionProxy].length - 1;
_whitelistedUsersCount = whitelist[collectionProxy].length - 1;
2,727
33
// Safe Function/This method can be used by the controller to extract mistakenly/_token The address of the token contract that you want to recover
function claimTokens(address _token) public onlyOwner returns(bool){ require(_token != address(LBC)); ERC20 token = ERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); return true; }
function claimTokens(address _token) public onlyOwner returns(bool){ require(_token != address(LBC)); ERC20 token = ERC20(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); emit ClaimedTokens(_token, owner, balance); return true; }
27,161
1
// anotherblock Drop Registry contract interface (see IABDataRegistry.sol)
IABDataRegistry public abDataRegistry;
IABDataRegistry public abDataRegistry;
9,316
15
// Adds a contract to the whitelisted DEXes that can be called/contractAddress The address of the DEX
function addWhitelist(address contractAddress) internal { BaseSwapperStorage storage baseStorage = getBaseSwapperStorage(); baseStorage.whitelistContracts[contractAddress] = true; }
function addWhitelist(address contractAddress) internal { BaseSwapperStorage storage baseStorage = getBaseSwapperStorage(); baseStorage.whitelistContracts[contractAddress] = true; }
13,678
325
// Compute hash of data
let dataHash := keccak256(add(data, 32), mload(data))
let dataHash := keccak256(add(data, 32), mload(data))
9,350
106
// reward end block number
uint256 public rewardEndBlock; uint256 public vempBurnPercent; uint256 public xVempHoldPercent; uint256 public vempLockPercent; uint256 public lockPeriod; IERC20 public xVEMP; uint256 public totalVempLock; mapping (address => UserLockInfo) public userLockInfo;
uint256 public rewardEndBlock; uint256 public vempBurnPercent; uint256 public xVempHoldPercent; uint256 public vempLockPercent; uint256 public lockPeriod; IERC20 public xVEMP; uint256 public totalVempLock; mapping (address => UserLockInfo) public userLockInfo;
64,495
5
// Adds a string value to the request with a given key name self The initialized request _key The name of the key _value The string value to add /
function add(Request memory self, string memory _key, string memory _value) internal pure
function add(Request memory self, string memory _key, string memory _value) internal pure
20,996
488
// redeem effect sumBorrowPlusEffects += tokensToDenomredeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); }
16,390