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
0
// address => id
mapping(address => uint) public accountIdByAddress; //// Association account address and his id
mapping(address => uint) public accountIdByAddress; //// Association account address and his id
18,202
0
// LendingPoolAddressesProviderRegistry contract Main registry of LendingPoolAddressesProvider of multiple OmniDex protocol's markets- Used for indexing purposes of OmniDex protocol's markets- The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with,for example with `0` for the OmniDex main market and `1` for the next created OmniDex /
interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; }
interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; }
26,469
229
// utility to remove liquidity from a converter_converter converter_poolAmountamount of pool tokens to remove_reserveToken1 reserve token 1_reserveToken2 reserve token 2/
function removeLiquidity( ILiquidityPoolV1Converter _converter, uint256 _poolAmount, IERC20Token _reserveToken1, IERC20Token _reserveToken2) internal
function removeLiquidity( ILiquidityPoolV1Converter _converter, uint256 _poolAmount, IERC20Token _reserveToken1, IERC20Token _reserveToken2) internal
41,464
4
// Helps initialize a dispute by assigning it a disputeIdwhen a miner returns a false on the validate array(in Zap.ProofOfWork) it sends theinvalidated value information to POS voting _requestId being disputed _timestamp being disputed _minerIndex the index of the miner that submitted the value being disputed. Since each official valuerequires 5 miners to submit a value. /
function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex
function beginDispute( uint256 _requestId, uint256 _timestamp, uint256 _minerIndex
26,451
103
// If price > anchorPrice(1 + maxSwing) Set price = anchorPrice(1 + maxSwing)
if (greaterThanExp(price, max)) { return (Error.NO_ERROR, true, max); }
if (greaterThanExp(price, max)) { return (Error.NO_ERROR, true, max); }
12,182
83
// housekeeping event
event ResetHeaderBlock(address indexed proposer, uint256 indexed headerBlockId);
event ResetHeaderBlock(address indexed proposer, uint256 indexed headerBlockId);
25,727
126
// This function allows users to retireve all information about a staker_staker address of staker inquiring about return uint current state of staker return uint startDate of staking/
function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate); }
function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) { return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate); }
26,039
253
// 60% chance that sideWeapon/armGuards/shoulderGuard will appear
uint256(keccak256(abi.encodePacked(encodedProp, _range))) % 100 > 60 ) {
uint256(keccak256(abi.encodePacked(encodedProp, _range))) % 100 > 60 ) {
21,569
68
// Swap contract for multisignature bridge
contract SwapContract is AccessControl, Pausable, ECDSAOffsetRecovery { using SafeERC20 for IERC20; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE"); uint128 public immutable numOfThisBlockchain; IUniswapV2Router02 public blockchainRouter; address public blockchainPool; mapping(uint256 => address) public RubicAddresses; mapping(uint256 => bool) public existingOtherBlockchain; mapping(uint256 => uint256) public feeAmountOfBlockchain; mapping(uint256 => uint256) public blockchainCryptoFee; uint256 public constant SIGNATURE_LENGTH = 65; struct processedTx { uint256 statusCode; bytes32 hashedParams; } mapping(bytes32 => processedTx) public processedTransactions; uint256 public minConfirmationSignatures = 3; uint256 public minTokenAmount; uint256 public maxTokenAmount; uint256 public maxGasPrice; uint256 public minConfirmationBlocks; uint256 public refundSlippage; // emitted every time when user gets crypto or tokens after success crossChainSwap event TransferFromOtherBlockchain( address user, uint256 amount, uint256 amountWithoutFee, bytes32 originalTxHash ); // emitted every time when user get a refund event userRefunded( address user, uint256 amount, uint256 amountWithoutFee, bytes32 originalTxHash ); // emitted if the recipient should receive crypto in the target blockchain event TransferCryptoToOtherBlockchainUser( uint256 blockchain, address sender, uint256 RBCAmountIn, uint256 amountSpent, string newAddress, uint256 cryptoOutMin, address[] path ); // emitted if the recipient should receive tokens in the target blockchain event TransferTokensToOtherBlockchainUser( uint256 blockchain, address sender, uint256 RBCAmountIn, uint256 amountSpent, string newAddress, uint256 tokenOutMin, address[] path ); /** * @param blockchain Number of blockchain * @param tokenInAmount Maximum amount of a token being sold * @param firstPath Path used for swapping tokens to *RBC (tokenIn address,.., *RBC addres) * @param secondPath Path used for swapping *RBC to tokenOut (*RBC address,.., tokenOut address) * @param exactRBCtokenOut Exact amount of RBC to get after first swap * @param tokenOutMin Minimal amount of tokens (or crypto) to get after second swap * @param newAddress Address in the blockchain to which the user wants to transfer * @param swapToCrypto This must be _true_ if swapping tokens to desired blockchain's crypto */ struct swapToParams { uint256 blockchain; uint256 tokenInAmount; address[] firstPath; address[] secondPath; uint256 exactRBCtokenOut; uint256 tokenOutMin; string newAddress; bool swapToCrypto; } /** * @param user User address // "newAddress" from event * @param amountWithFee Amount of tokens with included fees to transfer from the pool // "RBCAmountIn" from event * @param amountOutMin Minimal amount of tokens to get after second swap // "tokenOutMin" from event * @param path Path used for a second swap // "secondPath" from event * @param originalTxHash Hash of transaction from other network, on which swap was called * @param concatSignatures Concatenated string of signature bytes for verification of transaction */ struct swapFromParams { address user; uint256 amountWithFee; uint256 amountOutMin; address[] path; bytes32 originalTxHash; bytes concatSignatures; } /** * @dev throws if transaction sender is not in owner role */ modifier onlyOwner() { require( hasRole(OWNER_ROLE, _msgSender()), "Caller is not in owner role" ); _; } /** * @dev throws if transaction sender is not in owner or manager role */ modifier onlyOwnerAndManager() { require( hasRole(OWNER_ROLE, _msgSender()) || hasRole(MANAGER_ROLE, _msgSender()), "Caller is not in owner or manager role" ); _; } /** * @dev throws if transaction sender is not in relayer role */ modifier onlyRelayer() { require( hasRole(RELAYER_ROLE, _msgSender()), "swapContract: Caller is not in relayer role" ); _; } /** * @dev Performs check before swap*ToOtherBlockchain-functions and emits events * @param params The swapToParams structure * @param value The msg.value */ modifier TransferTo(swapToParams memory params, uint256 value) { require( bytes(params.newAddress).length > 0, "swapContract: No destination address provided" ); require( existingOtherBlockchain[params.blockchain] && params.blockchain != numOfThisBlockchain, "swapContract: Wrong choose of blockchain" ); require( params.firstPath.length > 0, "swapContract: firsPath length must be greater than 1" ); require( params.secondPath.length > 0, "swapContract: secondPath length must be greater than 1" ); require( params.firstPath[params.firstPath.length - 1] == RubicAddresses[numOfThisBlockchain], "swapContract: the last address in the firstPath must be Rubic" ); require( params.secondPath[0] == RubicAddresses[params.blockchain], "swapContract: the first address in the secondPath must be Rubic" ); require( params.exactRBCtokenOut >= minTokenAmount, "swapContract: Not enough amount of tokens" ); require( params.exactRBCtokenOut < maxTokenAmount, "swapContract: Too many RBC requested" ); require( value >= blockchainCryptoFee[params.blockchain], "swapContract: Not enough crypto provided" ); _; if (params.swapToCrypto) { emit TransferCryptoToOtherBlockchainUser( params.blockchain, _msgSender(), params.exactRBCtokenOut, params.tokenInAmount, params.newAddress, params.tokenOutMin, params.secondPath ); } else { emit TransferTokensToOtherBlockchainUser( params.blockchain, _msgSender(), params.exactRBCtokenOut, params.tokenInAmount, params.newAddress, params.tokenOutMin, params.secondPath ); } } /** * @dev Performs check before swap*ToUser-functions * @param params The swapFromParams structure */ modifier TransferFrom(swapFromParams memory params) { require( params.amountWithFee >= minTokenAmount, "swapContract: Not enough amount of tokens" ); require( params.amountWithFee < maxTokenAmount, "swapContract: Too many RBC requested" ); require( params.path.length > 0, "swapContract: path length must be greater than 1" ); require( params.path[0] == RubicAddresses[numOfThisBlockchain], "swapContract: the first address in the path must be Rubic" ); require( params.user != address(0), "swapContract: Address cannot be zero address" ); require( params.concatSignatures.length % SIGNATURE_LENGTH == 0, "swapContract: Signatures lengths must be divisible by 65" ); require( params.concatSignatures.length / SIGNATURE_LENGTH >= minConfirmationSignatures, "swapContract: Not enough signatures passed" ); _processTransaction( params.user, params.amountWithFee, params.originalTxHash, params.concatSignatures ); _; } /** * @dev Constructor of contract * @param _numOfThisBlockchain Number of blockchain where contract is deployed * @param _numsOfOtherBlockchains List of blockchain number that is supported by bridge * @param tokenLimits A list where 0 element is minTokenAmount and 1 is maxTokenAmount * @param _maxGasPrice Maximum gas price on which relayer nodes will operate * @param _minConfirmationBlocks Minimal amount of blocks for confirmation on validator nodes * @param _refundSlippage Slippage represented as hundredths of a bip, i.e. 1e-6 that will be used on refund * @param _RubicAddresses Addresses of Rubic in different blockchains */ constructor( uint128 _numOfThisBlockchain, uint128[] memory _numsOfOtherBlockchains, uint256[] memory tokenLimits, uint256 _maxGasPrice, uint256 _minConfirmationBlocks, uint256 _refundSlippage, IUniswapV2Router02 _blockchainRouter, address[] memory _RubicAddresses ) { for (uint256 i = 0; i < _numsOfOtherBlockchains.length; i++) { require( _numsOfOtherBlockchains[i] != _numOfThisBlockchain, "swapContract: Number of this blockchain is in array of other blockchains" ); existingOtherBlockchain[_numsOfOtherBlockchains[i]] = true; } for (uint256 i = 0; i < _RubicAddresses.length; i++) { RubicAddresses[i + 1] = _RubicAddresses[i]; } require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero"); numOfThisBlockchain = _numOfThisBlockchain; minTokenAmount = tokenLimits[0]; maxTokenAmount = tokenLimits[1]; maxGasPrice = _maxGasPrice; refundSlippage = _refundSlippage; minConfirmationBlocks = _minConfirmationBlocks; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OWNER_ROLE, _msgSender()); blockchainRouter = _blockchainRouter; IERC20(RubicAddresses[_numOfThisBlockchain]).safeApprove( address(_blockchainRouter), type(uint256).max ); } /** * @dev Returns true if blockchain of passed id is registered to swap * @param blockchain number of blockchain */ function getOtherBlockchainAvailableByNum(uint256 blockchain) external view returns (bool) { return existingOtherBlockchain[blockchain]; } function _processTransaction( address user, uint256 amountWithFee, bytes32 originalTxHash, bytes memory concatSignatures ) private { bytes32 hashedParams = getHashPacked( user, amountWithFee, originalTxHash ); uint256 statusCode = processedTransactions[originalTxHash].statusCode; bytes32 savedHash = processedTransactions[originalTxHash].hashedParams; require( statusCode == 0 && savedHash != hashedParams, "swapContract: Transaction already processed" ); uint256 signaturesCount = concatSignatures.length / uint256(SIGNATURE_LENGTH); address[] memory validatorAddresses = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { address validatorAddress = ecOffsetRecover( hashedParams, concatSignatures, i * SIGNATURE_LENGTH ); require( isValidator(validatorAddress), "swapContract: Validator address not in whitelist" ); for (uint256 j = 0; j < i; j++) { require( validatorAddress != validatorAddresses[j], "swapContract: Validator address is duplicated" ); } validatorAddresses[i] = validatorAddress; } processedTransactions[originalTxHash].hashedParams = hashedParams; processedTransactions[originalTxHash].statusCode = 1; } /** * @dev Transfers tokens from sender to the contract. * User calls this function when he wants to transfer tokens to another blockchain. * @notice User must have approved tokenInAmount of tokenIn */ function swapTokensToOtherBlockchain(swapToParams memory params) external payable whenNotPaused TransferTo(params, msg.value) { IERC20 tokenIn = IERC20(params.firstPath[0]); if (params.firstPath.length > 1) { tokenIn.safeTransferFrom( msg.sender, address(this), params.tokenInAmount ); tokenIn.safeApprove(address(blockchainRouter), 0); tokenIn.safeApprove( address(blockchainRouter), params.tokenInAmount ); uint256[] memory amounts = blockchainRouter .swapTokensForExactTokens( params.exactRBCtokenOut, params.tokenInAmount, params.firstPath, blockchainPool, block.timestamp ); tokenIn.safeTransfer( _msgSender(), params.tokenInAmount - amounts[0] ); params.tokenInAmount = amounts[0]; } else { tokenIn.safeTransferFrom( msg.sender, blockchainPool, params.exactRBCtokenOut ); } } /** * @dev Transfers tokens from sender to the contract. * User calls this function when he wants to transfer tokens to another blockchain. * @notice User must have approved tokenInAmount of tokenIn */ function swapCryptoToOtherBlockchain(swapToParams memory params) external payable whenNotPaused TransferTo(params, msg.value) { uint256 cryptoWithoutFee = msg.value - blockchainCryptoFee[params.blockchain]; uint256[] memory amounts = blockchainRouter.swapETHForExactTokens{ value: cryptoWithoutFee }( params.exactRBCtokenOut, params.firstPath, blockchainPool, block.timestamp ); params.tokenInAmount = amounts[0]; bool success = payable(_msgSender()).send( cryptoWithoutFee - amounts[0] ); require(success, "swapContract: crypto transfer back to caller failed"); } /** * @dev Transfers tokens to end user in current blockchain */ function swapTokensToUserWithFee(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { uint256 amountWithoutFee = FullMath.mulDiv( params.amountWithFee, 1e6 - feeAmountOfBlockchain[numOfThisBlockchain], 1e6 ); IERC20 RBCToken = IERC20(params.path[0]); if (params.path.length == 1) { RBCToken.safeTransferFrom( blockchainPool, params.user, amountWithoutFee ); RBCToken.safeTransferFrom( blockchainPool, address(this), params.amountWithFee - amountWithoutFee ); } else { RBCToken.safeTransferFrom( blockchainPool, address(this), params.amountWithFee ); blockchainRouter.swapExactTokensForTokens( amountWithoutFee, params.amountOutMin, params.path, params.user, block.timestamp ); } emit TransferFromOtherBlockchain( params.user, params.amountWithFee, amountWithoutFee, params.originalTxHash ); } /** * @dev Transfers tokens to end user in current blockchain */ function swapCryptoToUserWithFee(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { uint256 amountWithoutFee = FullMath.mulDiv( params.amountWithFee, 1e6 - feeAmountOfBlockchain[numOfThisBlockchain], 1e6 ); IERC20 RBCToken = IERC20(params.path[0]); RBCToken.safeTransferFrom( blockchainPool, address(this), params.amountWithFee ); blockchainRouter.swapExactTokensForETH( amountWithoutFee, params.amountOutMin, params.path, params.user, block.timestamp ); emit TransferFromOtherBlockchain( params.user, params.amountWithFee, amountWithoutFee, params.originalTxHash ); } /** * @dev Swaps RBC from pool to initially spent by user tokens and transfers him * @notice There is used the same structure as in other similar functions but amountOutMin should be * equal to the amount of tokens initially spent by user (we are refunding them), AmountWithFee should * be equal to the amount of RBC tokens that the pool got after the first swap (RBCAmountIn in the event) * hashedParams of this originalTxHash */ function refundTokensToUser(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { IERC20 RBCToken = IERC20(params.path[0]); if (params.path.length == 1) { RBCToken.safeTransferFrom( blockchainPool, params.user, params.amountOutMin ); emit userRefunded( params.user, params.amountOutMin, params.amountOutMin, params.originalTxHash ); } else { uint256 amountIn = FullMath.mulDiv( params.amountWithFee, 1e6 + refundSlippage, 1e6 ); RBCToken.safeTransferFrom(blockchainPool, address(this), amountIn); uint256 RBCSpent = blockchainRouter.swapTokensForExactTokens( params.amountOutMin, amountIn, params.path, params.user, block.timestamp )[0]; RBCToken.safeTransfer(blockchainPool, amountIn - RBCSpent); emit userRefunded( params.user, RBCSpent, RBCSpent, params.originalTxHash ); } } function refundCryptoToUser(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { IERC20 RBCToken = IERC20(params.path[0]); uint256 amountIn = FullMath.mulDiv( params.amountWithFee, 1e6 + refundSlippage, 1e6 ); RBCToken.safeTransferFrom(blockchainPool, address(this), amountIn); uint256 RBCSpent = blockchainRouter.swapTokensForExactETH( params.amountOutMin, amountIn, params.path, params.user, block.timestamp )[0]; RBCToken.safeTransfer(blockchainPool, amountIn - RBCSpent); emit userRefunded( params.user, RBCSpent, RBCSpent, params.originalTxHash ); } // OTHER BLOCKCHAIN MANAGEMENT /** * @dev Registers another blockchain for availability to swap * @param numOfOtherBlockchain number of blockchain */ function addOtherBlockchain(uint128 numOfOtherBlockchain) external onlyOwner { require( numOfOtherBlockchain != numOfThisBlockchain, "swapContract: Cannot add this blockchain to array of other blockchains" ); require( !existingOtherBlockchain[numOfOtherBlockchain], "swapContract: This blockchain is already added" ); existingOtherBlockchain[numOfOtherBlockchain] = true; } /** * @dev Unregisters another blockchain for availability to swap * @param numOfOtherBlockchain number of blockchain */ function removeOtherBlockchain(uint128 numOfOtherBlockchain) external onlyOwner { require( existingOtherBlockchain[numOfOtherBlockchain], "swapContract: This blockchain was not added" ); existingOtherBlockchain[numOfOtherBlockchain] = false; } /** * @dev Change existing blockchain id * @param oldNumOfOtherBlockchain number of existing blockchain * @param newNumOfOtherBlockchain number of new blockchain */ function changeOtherBlockchain( uint128 oldNumOfOtherBlockchain, uint128 newNumOfOtherBlockchain ) external onlyOwner { require( oldNumOfOtherBlockchain != newNumOfOtherBlockchain, "swapContract: Cannot change blockchains with same number" ); require( newNumOfOtherBlockchain != numOfThisBlockchain, "swapContract: Cannot add this blockchain to array of other blockchains" ); require( existingOtherBlockchain[oldNumOfOtherBlockchain], "swapContract: This blockchain was not added" ); require( !existingOtherBlockchain[newNumOfOtherBlockchain], "swapContract: This blockchain is already added" ); existingOtherBlockchain[oldNumOfOtherBlockchain] = false; existingOtherBlockchain[newNumOfOtherBlockchain] = true; } /** * @dev Changes/Set Router address * @param _router the new Router address */ function setRouter(IUniswapV2Router02 _router) external onlyOwnerAndManager { blockchainRouter = _router; } /** * @dev Changes/Set Pool address * @param _poolAddress the new Pool address */ function setPoolAddress(address _poolAddress) external onlyOwnerAndManager { blockchainPool = _poolAddress; } // FEE MANAGEMENT /** * @dev Sends collected crypto fee to the owner */ function collectCryptoFee() external onlyOwner { bool success = payable(msg.sender).send(address(this).balance); require(success, "swapContract: fail collecting fee"); } /** * @dev Sends collected token fee to the owner */ function collectTokenFee() external onlyOwner { IERC20(RubicAddresses[numOfThisBlockchain]).safeTransfer( msg.sender, IERC20(RubicAddresses[numOfThisBlockchain]).balanceOf(address(this)) ); } /** * @dev Changes fee values for blockchains in feeAmountOfBlockchain variables * @notice fee is represented as hundredths of a bip, i.e. 1e-6 * @param _blockchainNum Existing number of blockchain * @param feeAmount Fee amount to substruct from transfer amount */ function setFeeAmountOfBlockchain(uint128 _blockchainNum, uint256 feeAmount) external onlyOwnerAndManager { feeAmountOfBlockchain[_blockchainNum] = feeAmount; } /** * @dev Changes crypto fee values for blockchains in blockchainCryptoFee variables * @param _blockchainNum Existing number of blockchain * @param feeAmount Fee amount that must be sent calling transferToOtherBlockchain */ function setCryptoFeeOfBlockchain(uint128 _blockchainNum, uint256 feeAmount) external onlyOwnerAndManager { blockchainCryptoFee[_blockchainNum] = feeAmount; } /** * @dev Changes the address of Rubic in the certain blockchain * @param _blockchainNum Existing number of blockchain * @param _RubicAddress The Rubic address */ function setRubicAddressOfBlockchain( uint128 _blockchainNum, address _RubicAddress ) external onlyOwnerAndManager { RubicAddresses[_blockchainNum] = _RubicAddress; if (_blockchainNum == numOfThisBlockchain) { if ( IERC20(_RubicAddress).allowance( address(this), address(blockchainRouter) ) != 0 ) { IERC20(_RubicAddress).safeApprove(address(blockchainRouter), 0); } IERC20(_RubicAddress).safeApprove( address(blockchainRouter), type(uint256).max ); } } // VALIDATOR CONFIRMATIONS MANAGEMENT /** * @dev Changes requirement for minimal amount of signatures to validate on transfer * @param _minConfirmationSignatures Number of signatures to verify */ function setMinConfirmationSignatures(uint256 _minConfirmationSignatures) external onlyOwner { require( _minConfirmationSignatures > 0, "swapContract: At least 1 confirmation can be set" ); minConfirmationSignatures = _minConfirmationSignatures; } /** * @dev Changes requirement for minimal token amount on transfers * @param _minTokenAmount Amount of tokens */ function setMinTokenAmount(uint256 _minTokenAmount) external onlyOwnerAndManager { minTokenAmount = _minTokenAmount; } /** * @dev Changes requirement for maximum token amount on transfers * @param _maxTokenAmount Amount of tokens */ function setMaxTokenAmount(uint256 _maxTokenAmount) external onlyOwnerAndManager { maxTokenAmount = _maxTokenAmount; } /** * @dev Changes parameter of maximum gas price on which relayer nodes will operate * @param _maxGasPrice Price of gas in wei */ function setMaxGasPrice(uint256 _maxGasPrice) external onlyOwnerAndManager { require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero"); maxGasPrice = _maxGasPrice; } /** * @dev Changes requirement for minimal amount of block to consider tx confirmed on validator * @param _minConfirmationBlocks Amount of blocks */ function setMinConfirmationBlocks(uint256 _minConfirmationBlocks) external onlyOwnerAndManager { minConfirmationBlocks = _minConfirmationBlocks; } function setRefundSlippage(uint256 _refundSlippage) external onlyOwnerAndManager { refundSlippage = _refundSlippage; } /** * @dev Transfers permissions of contract ownership. * Will setup new owner and one manager on contract. * Main purpose of this function is to transfer ownership from deployer account ot real owner * @param newOwner Address of new owner * @param newManager Address of new manager */ function transferOwnerAndSetManager(address newOwner, address newManager) external onlyOwner { require( newOwner != _msgSender(), "swapContract: New owner must be different than current" ); require( newOwner != address(0x0), "swapContract: Owner cannot be zero address" ); require( newManager != address(0x0), "swapContract: Owner cannot be zero address" ); _setupRole(DEFAULT_ADMIN_ROLE, newOwner); _setupRole(OWNER_ROLE, newOwner); _setupRole(MANAGER_ROLE, newManager); renounceRole(OWNER_ROLE, _msgSender()); renounceRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Pauses transfers of tokens on contract */ function pauseExecution() external onlyOwner { _pause(); } /** * @dev Resumes transfers of tokens on contract */ function continueExecution() external onlyOwner { _unpause(); } /** * @dev Function to check if address is belongs to owner role * @param account Address to check */ function isOwner(address account) public view returns (bool) { return hasRole(OWNER_ROLE, account); } /** * @dev Function to check if address is belongs to manager role * @param account Address to check */ function isManager(address account) public view returns (bool) { return hasRole(MANAGER_ROLE, account); } /** * @dev Function to check if address is belongs to relayer role * @param account Address to check */ function isRelayer(address account) public view returns (bool) { return hasRole(RELAYER_ROLE, account); } /** * @dev Function to check if address is belongs to validator role * @param account Address to check * */ function isValidator(address account) public view returns (bool) { return hasRole(VALIDATOR_ROLE, account); } /** * @dev Function changes values associated with certain originalTxHash * @param originalTxHash Transaction hash to change * @param statusCode Associated status: 0-Not processed, 1-Processed, 2-Reverted * @param hashedParams Hashed params with which the initial transaction was executed */ function changeTxStatus( bytes32 originalTxHash, uint256 statusCode, bytes32 hashedParams ) external onlyRelayer { require( statusCode != 0, "swapContract: you cannot set the statusCode to 0" ); require( processedTransactions[originalTxHash].statusCode != 1, "swapContract: transaction with this originalTxHash has already been set as succeed" ); processedTransactions[originalTxHash].statusCode = statusCode; processedTransactions[originalTxHash].hashedParams = hashedParams; } /** * @dev Plain fallback function to receive crypto */ receive() external payable {} }
contract SwapContract is AccessControl, Pausable, ECDSAOffsetRecovery { using SafeERC20 for IERC20; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE"); uint128 public immutable numOfThisBlockchain; IUniswapV2Router02 public blockchainRouter; address public blockchainPool; mapping(uint256 => address) public RubicAddresses; mapping(uint256 => bool) public existingOtherBlockchain; mapping(uint256 => uint256) public feeAmountOfBlockchain; mapping(uint256 => uint256) public blockchainCryptoFee; uint256 public constant SIGNATURE_LENGTH = 65; struct processedTx { uint256 statusCode; bytes32 hashedParams; } mapping(bytes32 => processedTx) public processedTransactions; uint256 public minConfirmationSignatures = 3; uint256 public minTokenAmount; uint256 public maxTokenAmount; uint256 public maxGasPrice; uint256 public minConfirmationBlocks; uint256 public refundSlippage; // emitted every time when user gets crypto or tokens after success crossChainSwap event TransferFromOtherBlockchain( address user, uint256 amount, uint256 amountWithoutFee, bytes32 originalTxHash ); // emitted every time when user get a refund event userRefunded( address user, uint256 amount, uint256 amountWithoutFee, bytes32 originalTxHash ); // emitted if the recipient should receive crypto in the target blockchain event TransferCryptoToOtherBlockchainUser( uint256 blockchain, address sender, uint256 RBCAmountIn, uint256 amountSpent, string newAddress, uint256 cryptoOutMin, address[] path ); // emitted if the recipient should receive tokens in the target blockchain event TransferTokensToOtherBlockchainUser( uint256 blockchain, address sender, uint256 RBCAmountIn, uint256 amountSpent, string newAddress, uint256 tokenOutMin, address[] path ); /** * @param blockchain Number of blockchain * @param tokenInAmount Maximum amount of a token being sold * @param firstPath Path used for swapping tokens to *RBC (tokenIn address,.., *RBC addres) * @param secondPath Path used for swapping *RBC to tokenOut (*RBC address,.., tokenOut address) * @param exactRBCtokenOut Exact amount of RBC to get after first swap * @param tokenOutMin Minimal amount of tokens (or crypto) to get after second swap * @param newAddress Address in the blockchain to which the user wants to transfer * @param swapToCrypto This must be _true_ if swapping tokens to desired blockchain's crypto */ struct swapToParams { uint256 blockchain; uint256 tokenInAmount; address[] firstPath; address[] secondPath; uint256 exactRBCtokenOut; uint256 tokenOutMin; string newAddress; bool swapToCrypto; } /** * @param user User address // "newAddress" from event * @param amountWithFee Amount of tokens with included fees to transfer from the pool // "RBCAmountIn" from event * @param amountOutMin Minimal amount of tokens to get after second swap // "tokenOutMin" from event * @param path Path used for a second swap // "secondPath" from event * @param originalTxHash Hash of transaction from other network, on which swap was called * @param concatSignatures Concatenated string of signature bytes for verification of transaction */ struct swapFromParams { address user; uint256 amountWithFee; uint256 amountOutMin; address[] path; bytes32 originalTxHash; bytes concatSignatures; } /** * @dev throws if transaction sender is not in owner role */ modifier onlyOwner() { require( hasRole(OWNER_ROLE, _msgSender()), "Caller is not in owner role" ); _; } /** * @dev throws if transaction sender is not in owner or manager role */ modifier onlyOwnerAndManager() { require( hasRole(OWNER_ROLE, _msgSender()) || hasRole(MANAGER_ROLE, _msgSender()), "Caller is not in owner or manager role" ); _; } /** * @dev throws if transaction sender is not in relayer role */ modifier onlyRelayer() { require( hasRole(RELAYER_ROLE, _msgSender()), "swapContract: Caller is not in relayer role" ); _; } /** * @dev Performs check before swap*ToOtherBlockchain-functions and emits events * @param params The swapToParams structure * @param value The msg.value */ modifier TransferTo(swapToParams memory params, uint256 value) { require( bytes(params.newAddress).length > 0, "swapContract: No destination address provided" ); require( existingOtherBlockchain[params.blockchain] && params.blockchain != numOfThisBlockchain, "swapContract: Wrong choose of blockchain" ); require( params.firstPath.length > 0, "swapContract: firsPath length must be greater than 1" ); require( params.secondPath.length > 0, "swapContract: secondPath length must be greater than 1" ); require( params.firstPath[params.firstPath.length - 1] == RubicAddresses[numOfThisBlockchain], "swapContract: the last address in the firstPath must be Rubic" ); require( params.secondPath[0] == RubicAddresses[params.blockchain], "swapContract: the first address in the secondPath must be Rubic" ); require( params.exactRBCtokenOut >= minTokenAmount, "swapContract: Not enough amount of tokens" ); require( params.exactRBCtokenOut < maxTokenAmount, "swapContract: Too many RBC requested" ); require( value >= blockchainCryptoFee[params.blockchain], "swapContract: Not enough crypto provided" ); _; if (params.swapToCrypto) { emit TransferCryptoToOtherBlockchainUser( params.blockchain, _msgSender(), params.exactRBCtokenOut, params.tokenInAmount, params.newAddress, params.tokenOutMin, params.secondPath ); } else { emit TransferTokensToOtherBlockchainUser( params.blockchain, _msgSender(), params.exactRBCtokenOut, params.tokenInAmount, params.newAddress, params.tokenOutMin, params.secondPath ); } } /** * @dev Performs check before swap*ToUser-functions * @param params The swapFromParams structure */ modifier TransferFrom(swapFromParams memory params) { require( params.amountWithFee >= minTokenAmount, "swapContract: Not enough amount of tokens" ); require( params.amountWithFee < maxTokenAmount, "swapContract: Too many RBC requested" ); require( params.path.length > 0, "swapContract: path length must be greater than 1" ); require( params.path[0] == RubicAddresses[numOfThisBlockchain], "swapContract: the first address in the path must be Rubic" ); require( params.user != address(0), "swapContract: Address cannot be zero address" ); require( params.concatSignatures.length % SIGNATURE_LENGTH == 0, "swapContract: Signatures lengths must be divisible by 65" ); require( params.concatSignatures.length / SIGNATURE_LENGTH >= minConfirmationSignatures, "swapContract: Not enough signatures passed" ); _processTransaction( params.user, params.amountWithFee, params.originalTxHash, params.concatSignatures ); _; } /** * @dev Constructor of contract * @param _numOfThisBlockchain Number of blockchain where contract is deployed * @param _numsOfOtherBlockchains List of blockchain number that is supported by bridge * @param tokenLimits A list where 0 element is minTokenAmount and 1 is maxTokenAmount * @param _maxGasPrice Maximum gas price on which relayer nodes will operate * @param _minConfirmationBlocks Minimal amount of blocks for confirmation on validator nodes * @param _refundSlippage Slippage represented as hundredths of a bip, i.e. 1e-6 that will be used on refund * @param _RubicAddresses Addresses of Rubic in different blockchains */ constructor( uint128 _numOfThisBlockchain, uint128[] memory _numsOfOtherBlockchains, uint256[] memory tokenLimits, uint256 _maxGasPrice, uint256 _minConfirmationBlocks, uint256 _refundSlippage, IUniswapV2Router02 _blockchainRouter, address[] memory _RubicAddresses ) { for (uint256 i = 0; i < _numsOfOtherBlockchains.length; i++) { require( _numsOfOtherBlockchains[i] != _numOfThisBlockchain, "swapContract: Number of this blockchain is in array of other blockchains" ); existingOtherBlockchain[_numsOfOtherBlockchains[i]] = true; } for (uint256 i = 0; i < _RubicAddresses.length; i++) { RubicAddresses[i + 1] = _RubicAddresses[i]; } require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero"); numOfThisBlockchain = _numOfThisBlockchain; minTokenAmount = tokenLimits[0]; maxTokenAmount = tokenLimits[1]; maxGasPrice = _maxGasPrice; refundSlippage = _refundSlippage; minConfirmationBlocks = _minConfirmationBlocks; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(OWNER_ROLE, _msgSender()); blockchainRouter = _blockchainRouter; IERC20(RubicAddresses[_numOfThisBlockchain]).safeApprove( address(_blockchainRouter), type(uint256).max ); } /** * @dev Returns true if blockchain of passed id is registered to swap * @param blockchain number of blockchain */ function getOtherBlockchainAvailableByNum(uint256 blockchain) external view returns (bool) { return existingOtherBlockchain[blockchain]; } function _processTransaction( address user, uint256 amountWithFee, bytes32 originalTxHash, bytes memory concatSignatures ) private { bytes32 hashedParams = getHashPacked( user, amountWithFee, originalTxHash ); uint256 statusCode = processedTransactions[originalTxHash].statusCode; bytes32 savedHash = processedTransactions[originalTxHash].hashedParams; require( statusCode == 0 && savedHash != hashedParams, "swapContract: Transaction already processed" ); uint256 signaturesCount = concatSignatures.length / uint256(SIGNATURE_LENGTH); address[] memory validatorAddresses = new address[](signaturesCount); for (uint256 i = 0; i < signaturesCount; i++) { address validatorAddress = ecOffsetRecover( hashedParams, concatSignatures, i * SIGNATURE_LENGTH ); require( isValidator(validatorAddress), "swapContract: Validator address not in whitelist" ); for (uint256 j = 0; j < i; j++) { require( validatorAddress != validatorAddresses[j], "swapContract: Validator address is duplicated" ); } validatorAddresses[i] = validatorAddress; } processedTransactions[originalTxHash].hashedParams = hashedParams; processedTransactions[originalTxHash].statusCode = 1; } /** * @dev Transfers tokens from sender to the contract. * User calls this function when he wants to transfer tokens to another blockchain. * @notice User must have approved tokenInAmount of tokenIn */ function swapTokensToOtherBlockchain(swapToParams memory params) external payable whenNotPaused TransferTo(params, msg.value) { IERC20 tokenIn = IERC20(params.firstPath[0]); if (params.firstPath.length > 1) { tokenIn.safeTransferFrom( msg.sender, address(this), params.tokenInAmount ); tokenIn.safeApprove(address(blockchainRouter), 0); tokenIn.safeApprove( address(blockchainRouter), params.tokenInAmount ); uint256[] memory amounts = blockchainRouter .swapTokensForExactTokens( params.exactRBCtokenOut, params.tokenInAmount, params.firstPath, blockchainPool, block.timestamp ); tokenIn.safeTransfer( _msgSender(), params.tokenInAmount - amounts[0] ); params.tokenInAmount = amounts[0]; } else { tokenIn.safeTransferFrom( msg.sender, blockchainPool, params.exactRBCtokenOut ); } } /** * @dev Transfers tokens from sender to the contract. * User calls this function when he wants to transfer tokens to another blockchain. * @notice User must have approved tokenInAmount of tokenIn */ function swapCryptoToOtherBlockchain(swapToParams memory params) external payable whenNotPaused TransferTo(params, msg.value) { uint256 cryptoWithoutFee = msg.value - blockchainCryptoFee[params.blockchain]; uint256[] memory amounts = blockchainRouter.swapETHForExactTokens{ value: cryptoWithoutFee }( params.exactRBCtokenOut, params.firstPath, blockchainPool, block.timestamp ); params.tokenInAmount = amounts[0]; bool success = payable(_msgSender()).send( cryptoWithoutFee - amounts[0] ); require(success, "swapContract: crypto transfer back to caller failed"); } /** * @dev Transfers tokens to end user in current blockchain */ function swapTokensToUserWithFee(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { uint256 amountWithoutFee = FullMath.mulDiv( params.amountWithFee, 1e6 - feeAmountOfBlockchain[numOfThisBlockchain], 1e6 ); IERC20 RBCToken = IERC20(params.path[0]); if (params.path.length == 1) { RBCToken.safeTransferFrom( blockchainPool, params.user, amountWithoutFee ); RBCToken.safeTransferFrom( blockchainPool, address(this), params.amountWithFee - amountWithoutFee ); } else { RBCToken.safeTransferFrom( blockchainPool, address(this), params.amountWithFee ); blockchainRouter.swapExactTokensForTokens( amountWithoutFee, params.amountOutMin, params.path, params.user, block.timestamp ); } emit TransferFromOtherBlockchain( params.user, params.amountWithFee, amountWithoutFee, params.originalTxHash ); } /** * @dev Transfers tokens to end user in current blockchain */ function swapCryptoToUserWithFee(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { uint256 amountWithoutFee = FullMath.mulDiv( params.amountWithFee, 1e6 - feeAmountOfBlockchain[numOfThisBlockchain], 1e6 ); IERC20 RBCToken = IERC20(params.path[0]); RBCToken.safeTransferFrom( blockchainPool, address(this), params.amountWithFee ); blockchainRouter.swapExactTokensForETH( amountWithoutFee, params.amountOutMin, params.path, params.user, block.timestamp ); emit TransferFromOtherBlockchain( params.user, params.amountWithFee, amountWithoutFee, params.originalTxHash ); } /** * @dev Swaps RBC from pool to initially spent by user tokens and transfers him * @notice There is used the same structure as in other similar functions but amountOutMin should be * equal to the amount of tokens initially spent by user (we are refunding them), AmountWithFee should * be equal to the amount of RBC tokens that the pool got after the first swap (RBCAmountIn in the event) * hashedParams of this originalTxHash */ function refundTokensToUser(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { IERC20 RBCToken = IERC20(params.path[0]); if (params.path.length == 1) { RBCToken.safeTransferFrom( blockchainPool, params.user, params.amountOutMin ); emit userRefunded( params.user, params.amountOutMin, params.amountOutMin, params.originalTxHash ); } else { uint256 amountIn = FullMath.mulDiv( params.amountWithFee, 1e6 + refundSlippage, 1e6 ); RBCToken.safeTransferFrom(blockchainPool, address(this), amountIn); uint256 RBCSpent = blockchainRouter.swapTokensForExactTokens( params.amountOutMin, amountIn, params.path, params.user, block.timestamp )[0]; RBCToken.safeTransfer(blockchainPool, amountIn - RBCSpent); emit userRefunded( params.user, RBCSpent, RBCSpent, params.originalTxHash ); } } function refundCryptoToUser(swapFromParams memory params) external onlyRelayer whenNotPaused TransferFrom(params) { IERC20 RBCToken = IERC20(params.path[0]); uint256 amountIn = FullMath.mulDiv( params.amountWithFee, 1e6 + refundSlippage, 1e6 ); RBCToken.safeTransferFrom(blockchainPool, address(this), amountIn); uint256 RBCSpent = blockchainRouter.swapTokensForExactETH( params.amountOutMin, amountIn, params.path, params.user, block.timestamp )[0]; RBCToken.safeTransfer(blockchainPool, amountIn - RBCSpent); emit userRefunded( params.user, RBCSpent, RBCSpent, params.originalTxHash ); } // OTHER BLOCKCHAIN MANAGEMENT /** * @dev Registers another blockchain for availability to swap * @param numOfOtherBlockchain number of blockchain */ function addOtherBlockchain(uint128 numOfOtherBlockchain) external onlyOwner { require( numOfOtherBlockchain != numOfThisBlockchain, "swapContract: Cannot add this blockchain to array of other blockchains" ); require( !existingOtherBlockchain[numOfOtherBlockchain], "swapContract: This blockchain is already added" ); existingOtherBlockchain[numOfOtherBlockchain] = true; } /** * @dev Unregisters another blockchain for availability to swap * @param numOfOtherBlockchain number of blockchain */ function removeOtherBlockchain(uint128 numOfOtherBlockchain) external onlyOwner { require( existingOtherBlockchain[numOfOtherBlockchain], "swapContract: This blockchain was not added" ); existingOtherBlockchain[numOfOtherBlockchain] = false; } /** * @dev Change existing blockchain id * @param oldNumOfOtherBlockchain number of existing blockchain * @param newNumOfOtherBlockchain number of new blockchain */ function changeOtherBlockchain( uint128 oldNumOfOtherBlockchain, uint128 newNumOfOtherBlockchain ) external onlyOwner { require( oldNumOfOtherBlockchain != newNumOfOtherBlockchain, "swapContract: Cannot change blockchains with same number" ); require( newNumOfOtherBlockchain != numOfThisBlockchain, "swapContract: Cannot add this blockchain to array of other blockchains" ); require( existingOtherBlockchain[oldNumOfOtherBlockchain], "swapContract: This blockchain was not added" ); require( !existingOtherBlockchain[newNumOfOtherBlockchain], "swapContract: This blockchain is already added" ); existingOtherBlockchain[oldNumOfOtherBlockchain] = false; existingOtherBlockchain[newNumOfOtherBlockchain] = true; } /** * @dev Changes/Set Router address * @param _router the new Router address */ function setRouter(IUniswapV2Router02 _router) external onlyOwnerAndManager { blockchainRouter = _router; } /** * @dev Changes/Set Pool address * @param _poolAddress the new Pool address */ function setPoolAddress(address _poolAddress) external onlyOwnerAndManager { blockchainPool = _poolAddress; } // FEE MANAGEMENT /** * @dev Sends collected crypto fee to the owner */ function collectCryptoFee() external onlyOwner { bool success = payable(msg.sender).send(address(this).balance); require(success, "swapContract: fail collecting fee"); } /** * @dev Sends collected token fee to the owner */ function collectTokenFee() external onlyOwner { IERC20(RubicAddresses[numOfThisBlockchain]).safeTransfer( msg.sender, IERC20(RubicAddresses[numOfThisBlockchain]).balanceOf(address(this)) ); } /** * @dev Changes fee values for blockchains in feeAmountOfBlockchain variables * @notice fee is represented as hundredths of a bip, i.e. 1e-6 * @param _blockchainNum Existing number of blockchain * @param feeAmount Fee amount to substruct from transfer amount */ function setFeeAmountOfBlockchain(uint128 _blockchainNum, uint256 feeAmount) external onlyOwnerAndManager { feeAmountOfBlockchain[_blockchainNum] = feeAmount; } /** * @dev Changes crypto fee values for blockchains in blockchainCryptoFee variables * @param _blockchainNum Existing number of blockchain * @param feeAmount Fee amount that must be sent calling transferToOtherBlockchain */ function setCryptoFeeOfBlockchain(uint128 _blockchainNum, uint256 feeAmount) external onlyOwnerAndManager { blockchainCryptoFee[_blockchainNum] = feeAmount; } /** * @dev Changes the address of Rubic in the certain blockchain * @param _blockchainNum Existing number of blockchain * @param _RubicAddress The Rubic address */ function setRubicAddressOfBlockchain( uint128 _blockchainNum, address _RubicAddress ) external onlyOwnerAndManager { RubicAddresses[_blockchainNum] = _RubicAddress; if (_blockchainNum == numOfThisBlockchain) { if ( IERC20(_RubicAddress).allowance( address(this), address(blockchainRouter) ) != 0 ) { IERC20(_RubicAddress).safeApprove(address(blockchainRouter), 0); } IERC20(_RubicAddress).safeApprove( address(blockchainRouter), type(uint256).max ); } } // VALIDATOR CONFIRMATIONS MANAGEMENT /** * @dev Changes requirement for minimal amount of signatures to validate on transfer * @param _minConfirmationSignatures Number of signatures to verify */ function setMinConfirmationSignatures(uint256 _minConfirmationSignatures) external onlyOwner { require( _minConfirmationSignatures > 0, "swapContract: At least 1 confirmation can be set" ); minConfirmationSignatures = _minConfirmationSignatures; } /** * @dev Changes requirement for minimal token amount on transfers * @param _minTokenAmount Amount of tokens */ function setMinTokenAmount(uint256 _minTokenAmount) external onlyOwnerAndManager { minTokenAmount = _minTokenAmount; } /** * @dev Changes requirement for maximum token amount on transfers * @param _maxTokenAmount Amount of tokens */ function setMaxTokenAmount(uint256 _maxTokenAmount) external onlyOwnerAndManager { maxTokenAmount = _maxTokenAmount; } /** * @dev Changes parameter of maximum gas price on which relayer nodes will operate * @param _maxGasPrice Price of gas in wei */ function setMaxGasPrice(uint256 _maxGasPrice) external onlyOwnerAndManager { require(_maxGasPrice > 0, "swapContract: Gas price cannot be zero"); maxGasPrice = _maxGasPrice; } /** * @dev Changes requirement for minimal amount of block to consider tx confirmed on validator * @param _minConfirmationBlocks Amount of blocks */ function setMinConfirmationBlocks(uint256 _minConfirmationBlocks) external onlyOwnerAndManager { minConfirmationBlocks = _minConfirmationBlocks; } function setRefundSlippage(uint256 _refundSlippage) external onlyOwnerAndManager { refundSlippage = _refundSlippage; } /** * @dev Transfers permissions of contract ownership. * Will setup new owner and one manager on contract. * Main purpose of this function is to transfer ownership from deployer account ot real owner * @param newOwner Address of new owner * @param newManager Address of new manager */ function transferOwnerAndSetManager(address newOwner, address newManager) external onlyOwner { require( newOwner != _msgSender(), "swapContract: New owner must be different than current" ); require( newOwner != address(0x0), "swapContract: Owner cannot be zero address" ); require( newManager != address(0x0), "swapContract: Owner cannot be zero address" ); _setupRole(DEFAULT_ADMIN_ROLE, newOwner); _setupRole(OWNER_ROLE, newOwner); _setupRole(MANAGER_ROLE, newManager); renounceRole(OWNER_ROLE, _msgSender()); renounceRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Pauses transfers of tokens on contract */ function pauseExecution() external onlyOwner { _pause(); } /** * @dev Resumes transfers of tokens on contract */ function continueExecution() external onlyOwner { _unpause(); } /** * @dev Function to check if address is belongs to owner role * @param account Address to check */ function isOwner(address account) public view returns (bool) { return hasRole(OWNER_ROLE, account); } /** * @dev Function to check if address is belongs to manager role * @param account Address to check */ function isManager(address account) public view returns (bool) { return hasRole(MANAGER_ROLE, account); } /** * @dev Function to check if address is belongs to relayer role * @param account Address to check */ function isRelayer(address account) public view returns (bool) { return hasRole(RELAYER_ROLE, account); } /** * @dev Function to check if address is belongs to validator role * @param account Address to check * */ function isValidator(address account) public view returns (bool) { return hasRole(VALIDATOR_ROLE, account); } /** * @dev Function changes values associated with certain originalTxHash * @param originalTxHash Transaction hash to change * @param statusCode Associated status: 0-Not processed, 1-Processed, 2-Reverted * @param hashedParams Hashed params with which the initial transaction was executed */ function changeTxStatus( bytes32 originalTxHash, uint256 statusCode, bytes32 hashedParams ) external onlyRelayer { require( statusCode != 0, "swapContract: you cannot set the statusCode to 0" ); require( processedTransactions[originalTxHash].statusCode != 1, "swapContract: transaction with this originalTxHash has already been set as succeed" ); processedTransactions[originalTxHash].statusCode = statusCode; processedTransactions[originalTxHash].hashedParams = hashedParams; } /** * @dev Plain fallback function to receive crypto */ receive() external payable {} }
80,395
245
// Variable
uint256 public maxSupply = 555; string public baseURI; string public notRevealedURI = "https://assets.jokercharlie.com/jccgenesis/default.json"; string public baseExtension = ".json"; bool public revealed; address public metadataContract; address public lockerContract;
uint256 public maxSupply = 555; string public baseURI; string public notRevealedURI = "https://assets.jokercharlie.com/jccgenesis/default.json"; string public baseExtension = ".json"; bool public revealed; address public metadataContract; address public lockerContract;
30,725
111
// oods_coefficients[89]/ mload(add(context, 0x64e0)), res += c_90(f_7(x) - f_7(g^19z)) / (x - g^19z).
res := add( res, mulmod(mulmod(/*(x - g^19 * z)^(-1)*/ mload(add(denominatorsPtr, 0x260)),
res := add( res, mulmod(mulmod(/*(x - g^19 * z)^(-1)*/ mload(add(denominatorsPtr, 0x260)),
28,860
166
// Called when BondOperation's bond budget is updated at the beginning of the epoch. Parameters ---------------- |epoch_id|: The epoch ID. |bond_budget|: The bond budget. |total_bond_supply|: The total bond supply. |valid_bond_supply|: The valid bond supply. Returns ---------------- None.
function updateBondBudget(uint epoch_id, int bond_budget, uint total_bond_supply, uint valid_bond_supply)
function updateBondBudget(uint epoch_id, int bond_budget, uint total_bond_supply, uint valid_bond_supply)
20,854
133
// AIX generated so far is 51% of total
uint256 tokenCap = aix.totalSupply().mul(100).div(51);
uint256 tokenCap = aix.totalSupply().mul(100).div(51);
34,797
64
// Calculate receipt tokens for a given amount of deposit tokens If contract is empty, use 1:1 ratio Could return zero shares for very low amounts of deposit tokens amount deposit tokensreturn receipt tokens /
function getSharesForDepositTokens(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return amount; } return amount.mul(totalSupply).div(totalDeposits); }
function getSharesForDepositTokens(uint amount) public view returns (uint) { if (totalSupply.mul(totalDeposits) == 0) { return amount; } return amount.mul(totalSupply).div(totalDeposits); }
19,036
61
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
emit Transfer(_from, _to, _amount);
15,674
137
// Update star info
mapping(address => bool) private _operators;
mapping(address => bool) private _operators;
54,376
154
// Delete the slot where the moved entry was stored
map._entries.pop();
map._entries.pop();
366
36
// Change the member's public key.
members_[addressToMember_[msg.sender]].pubkey = _newMemberKey;
members_[addressToMember_[msg.sender]].pubkey = _newMemberKey;
83,435
2
// Balances KNOW for each account
mapping(address => uint256) balances;
mapping(address => uint256) balances;
9,289
12
// now we loop into storage to look after campaign and populate that var
for(uint i = 0; i < numberOfCampaigns; i++) { Campaign storage item = campaigns[i]; allCampaigns[i] = item; }
for(uint i = 0; i < numberOfCampaigns; i++) { Campaign storage item = campaigns[i]; allCampaigns[i] = item; }
24,945
4
// Fallback function to add funds to the pool without playing /
receive() external payable { require(msg.value > 0, "Requires some value to fund the prize pool"); }
receive() external payable { require(msg.value > 0, "Requires some value to fund the prize pool"); }
29,725
51
// Paybacks Vault's type underlying to activeProvider _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault SafeERC20.safeTransferFrom( IERC20(vAssets.borrowAsset), msg.sender, address(this), amountToPayback ); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } }
* Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault SafeERC20.safeTransferFrom( IERC20(vAssets.borrowAsset), msg.sender, address(this), amountToPayback ); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } }
78,978
1
// The minimum setable proposal threshold
uint256 public constant MIN_PROPOSAL_THRESHOLD_BPS = 1; // 1 basis point or 0.01%
uint256 public constant MIN_PROPOSAL_THRESHOLD_BPS = 1; // 1 basis point or 0.01%
19,268
10
// The ```RemoveFromDelegateCallAllowlist``` event is emitted when governance removes a contract from the allowlist/contractAddress The address of the contract removed
event RemoveFromDelegateCallAllowlist(address contractAddress);
event RemoveFromDelegateCallAllowlist(address contractAddress);
34,441
55
// modifier created to prevent short address attack problems. /
modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; }
modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; }
32,906
94
// Constructor, takes token wallet address. tokenWallet Address holding the tokens, which has approved allowance to the crowdsale /
constructor (address tokenWallet) public { require(tokenWallet != address(0)); _tokenWallet = tokenWallet; }
constructor (address tokenWallet) public { require(tokenWallet != address(0)); _tokenWallet = tokenWallet; }
19,546
7
// Boolean flag to be read by the snapshot contract in order to decide if the validator set needs to be changed or not (i.e if a validator is going to be removed or added).
bool internal _isMaintenanceScheduled;
bool internal _isMaintenanceScheduled;
19,398
32
// Batch set vehicle properties
function setCarIndexs(uint256[18] memory ids,uint256[18] memory fertilities,uint256[18] memory carries) private { for(uint256 i=0;i<ids.length;i++){ setCarIndex(i,ids[i],fertilities[i],carries[i]); } }
function setCarIndexs(uint256[18] memory ids,uint256[18] memory fertilities,uint256[18] memory carries) private { for(uint256 i=0;i<ids.length;i++){ setCarIndex(i,ids[i],fertilities[i],carries[i]); } }
59,926
41
// AdminUpgradeabilityProxy Extends from BaseAdminUpgradeabilityProxy with a constructor for initializing the implementation, admin, and init data. /
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _admin, address _logic, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal { super._willFallback(); } }
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _admin, address _logic, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } function _willFallback() override(Proxy, BaseAdminUpgradeabilityProxy) internal { super._willFallback(); } }
7,782
45
// mint coins immediately that aren't for crowdsale
mint(affiliate, affiliateTokens); mint(contingency, contingencyTokens); mint(advisor, advisorTokens); mint(team, teamTokensPerWallet); mint(teamY1, teamTokensPerWallet); // These will be locked for transfer until 01/01/2019 00:00:00 mint(teamY2, teamTokensPerWallet); // These will be locked for transfer until 01/01/2020 00:00:00 mint(teamY3, teamTokensPerWallet); // These will be locked for transfer until 01/01/2021 00:00:00 mint(teamY4, teamTokensPerWallet); // These will be locked for transfer until 01/01/2022 00:00:00 mintedWallets = true;
mint(affiliate, affiliateTokens); mint(contingency, contingencyTokens); mint(advisor, advisorTokens); mint(team, teamTokensPerWallet); mint(teamY1, teamTokensPerWallet); // These will be locked for transfer until 01/01/2019 00:00:00 mint(teamY2, teamTokensPerWallet); // These will be locked for transfer until 01/01/2020 00:00:00 mint(teamY3, teamTokensPerWallet); // These will be locked for transfer until 01/01/2021 00:00:00 mint(teamY4, teamTokensPerWallet); // These will be locked for transfer until 01/01/2022 00:00:00 mintedWallets = true;
41,625
5
// add a and b and then subtract c/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); }
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); }
4,724
98
// Calculate x - y.Special values behave in the following way: NaN - x = NaN for any x.Infinity - x = Infinity for any finite x.-Infinity - x = -Infinity for any finite x.Infinity - -Infinity = Infinity.-Infinity - Infinity = -Infinity.Infinity - Infinity = -Infinity - -Infinity = NaN.x quadruple precision number y quadruple precision numberreturn quadruple precision number /
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) { unchecked {return add(x, y ^ 0x80000000000000000000000000000000);} }
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) { unchecked {return add(x, y ^ 0x80000000000000000000000000000000);} }
20,743
68
// exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal);
_isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal);
1,269
56
// Equivalent to contains(set, value) To delete an element from the _values array in O(1), we swap the element to delete with the last one in the array, and then remove the last element (sometimes called as 'swap and pop'). This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex];
uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex];
3,144
54
// 获取授权信息
* @param {Object} address */ function allowance(address tokenOwner, address spender) public view returns(uint remaining) { return allowed[tokenOwner][spender]; }
* @param {Object} address */ function allowance(address tokenOwner, address spender) public view returns(uint remaining) { return allowed[tokenOwner][spender]; }
18,908
79
// Storing an initial non-zero value makes deployment a bit more expensive, but in exchange the refund on every call to nonReentrant will be lower in amount. Since refunds are capped to a percetange of the total transaction's gas, it is best to keep them low in cases like this one, to increase the likelihood of the full refund coming into effect.
_notEntered = true;
_notEntered = true;
13,303
5
// owner The address of the account owning tokens/spender The address of the account able to transfer the tokens/ return Amount of remaining tokens allowed to spent
function allowance(address owner, address spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
function allowance(address owner, address spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
17,906
12
// Creates a new token category. metadataHash Hash of metadata about the token categorywhich can be distributed on IPFS. /
function createCategory(bytes32 metadataHash) external onlyOwner { uint256 categoryID = ++categoryIndex; emit CategoryAdded(categoryID, metadataHash); }
function createCategory(bytes32 metadataHash) external onlyOwner { uint256 categoryID = ++categoryIndex; emit CategoryAdded(categoryID, metadataHash); }
8,971
108
// Monetary dYdX Library for types involving money /
library Monetary { /* * The price of a base-unit of an asset. */ struct Price { uint256 value; } /* * Total value of an some amount of an asset. Equal to (price * amount). */ struct Value { uint256 value; } }
library Monetary { /* * The price of a base-unit of an asset. */ struct Price { uint256 value; } /* * Total value of an some amount of an asset. Equal to (price * amount). */ struct Value { uint256 value; } }
59,118
120
// Creates `amount` tokens and assigns them to `account`, increasingthe total supply. /
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "VegionToken: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "VegionToken: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
80,322
985
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee );
FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee );
21,698
7
// Used to disable lock before migrating keys and/or destroying contract.Throws if called by other than a lock manager.Throws if lock contract has already been disabled./
function disableLock() external;
function disableLock() external;
32,204
0
// Auction ends in last 3hrs when this random number is observed
uint256 constant auctionLengthInHours = 72;
uint256 constant auctionLengthInHours = 72;
55,788
61
// KEEP THIS FUNCTION IN CASE THE CONTRACT KEEPS LEFTOVER ETHER!
function withdrawEther() public onlyOwner { address self = address(this); // workaround for a possible solidity bug uint256 balance = self.balance; address(OWNER).transfer(balance); }
function withdrawEther() public onlyOwner { address self = address(this); // workaround for a possible solidity bug uint256 balance = self.balance; address(OWNER).transfer(balance); }
9,575
28
// Return all ETH and tokens to original multisig and then suicide
function abort() public onlyAdmins { require(returnToSender()); selfdestruct(multisig); }
function abort() public onlyAdmins { require(returnToSender()); selfdestruct(multisig); }
35,171
88
// index 0 to save the left token num
lockedAllRewards[msg.sender][idx].alloc[0] = lockedAllRewards[msg.sender][idx].alloc[0].add(amount.sub(divAmount)); uint256 i=2;
lockedAllRewards[msg.sender][idx].alloc[0] = lockedAllRewards[msg.sender][idx].alloc[0].add(amount.sub(divAmount)); uint256 i=2;
68,787
85
// Creates total supply of 500 000 tokens.
_initialSupply = 1000000 * 10 ** _decimals; _totalSupply = _totalSupply.add(_initialSupply); _balances[msg.sender] = _balances[msg.sender].add(_initialSupply); emit Transfer(address(0), msg.sender, _initialSupply);
_initialSupply = 1000000 * 10 ** _decimals; _totalSupply = _totalSupply.add(_initialSupply); _balances[msg.sender] = _balances[msg.sender].add(_initialSupply); emit Transfer(address(0), msg.sender, _initialSupply);
3,451
60
// add ln(2)k5e182192
r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
1,861
33
// total token supply
uint public totalSupply;
uint public totalSupply;
2,104
156
// Updates the endTimestamp propety with the new _end value
function setEndTimestamp(uint256 _end) external onlyAdmin returns (bool) { require(_end > startTimestamp); uint256 _oldValue = endTimestamp; endTimestamp = _end; EndTimestampUpdated(msg.sender, _oldValue, endTimestamp); return true; }
function setEndTimestamp(uint256 _end) external onlyAdmin returns (bool) { require(_end > startTimestamp); uint256 _oldValue = endTimestamp; endTimestamp = _end; EndTimestampUpdated(msg.sender, _oldValue, endTimestamp); return true; }
5,816
306
// BToken initialize does the bulk of the work
super.initialize(bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
super.initialize(bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
26,379
168
// See {IERC20Burnable-burn(uint256)}.
function burn(uint256 amount) public virtual override returns (bool) { _burn(_msgSender(), amount); return true; }
function burn(uint256 amount) public virtual override returns (bool) { _burn(_msgSender(), amount); return true; }
23,398
10
// adds the monetary policy contracts, hop, backstep etc
function setMonetaryPolicyContract(address con_address) public onlyByOracle { frax_monetary_policy_contracts[con_address] = true; }
function setMonetaryPolicyContract(address con_address) public onlyByOracle { frax_monetary_policy_contracts[con_address] = true; }
3,998
295
// Tell whether an action's dispute can be ruled_actionId Identification number of the action return True if the action's dispute can be ruled, false otherwise/
function canRuleDispute(uint256 _actionId) external view returns (bool) { (, Challenge storage challenge, ) = _getChallengedAction(_actionId); return _isDisputed(challenge); }
function canRuleDispute(uint256 _actionId) external view returns (bool) { (, Challenge storage challenge, ) = _getChallengedAction(_actionId); return _isDisputed(challenge); }
19,847
148
// a library for performing various math operations
library Math { using SafeMathUpgradeable for uint256; function max(uint256 x, uint256 y) internal pure returns (uint256) { return x < y ? y : x; } function min(uint256 x, uint256 y) internal pure returns (uint256) { return x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y.div(2).add(1); while (x < z) { z = x; x = (y.div(x).add(x)).div(2); } } else if (y != 0) { z = 1; } } // power private function function pow(uint256 _base, uint256 _exponent) internal pure returns (uint256) { if (_exponent == 0) { return 1; } else if (_exponent == 1) { return _base; } else if (_base == 0 && _exponent != 0) { return 0; } else { uint256 z = _base; for (uint256 i = 1; i < _exponent; i++) { z = z.mul(_base); } return z; } } }
library Math { using SafeMathUpgradeable for uint256; function max(uint256 x, uint256 y) internal pure returns (uint256) { return x < y ? y : x; } function min(uint256 x, uint256 y) internal pure returns (uint256) { return x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y.div(2).add(1); while (x < z) { z = x; x = (y.div(x).add(x)).div(2); } } else if (y != 0) { z = 1; } } // power private function function pow(uint256 _base, uint256 _exponent) internal pure returns (uint256) { if (_exponent == 0) { return 1; } else if (_exponent == 1) { return _base; } else if (_base == 0 && _exponent != 0) { return 0; } else { uint256 z = _base; for (uint256 i = 1; i < _exponent; i++) { z = z.mul(_base); } return z; } } }
10,724
39
// Returns the claim condition at the given uid.
function getClaimConditionById(uint256 _tokenId, uint256 _conditionId) external view returns (ClaimCondition memory condition)
function getClaimConditionById(uint256 _tokenId, uint256 _conditionId) external view returns (ClaimCondition memory condition)
24,768
34
// Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. a a FixedPoint numerator. b a FixedPoint denominator.return the quotient of `a` divided by `b`. /
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } }
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } }
19,181
23
// a reserved symbol means the route is already chosen
address token = symbolRoute[_hashSymbol]; if (token != address(0)) return false;
address token = symbolRoute[_hashSymbol]; if (token != address(0)) return false;
23,531
0
// 当天公司已经发出去币的数量
uint256 oneDaySendCoin = 0; event Transfer(address indexed to, uint256 value); mapping (address => uint256) public exchangeCoin; mapping (address => uint256) public balanceOf;
uint256 oneDaySendCoin = 0; event Transfer(address indexed to, uint256 value); mapping (address => uint256) public exchangeCoin; mapping (address => uint256) public balanceOf;
33,107
16
// withdraws unlockable balance to receiver
vlCvx.withdrawExpiredLocksTo(receiver);
vlCvx.withdrawExpiredLocksTo(receiver);
25,110
37
// first scenario - this is not the first tx in the current block
if (currentBlockData.lastBlock == currentBlock) { if (uint(currentBlockData.lastRateUpdateBlock) == rateUpdateBlock) {
if (currentBlockData.lastBlock == currentBlock) { if (uint(currentBlockData.lastRateUpdateBlock) == rateUpdateBlock) {
58,911
7
// ERC20 token address
address token;
address token;
151
28
// Retreive insurance details patient_id patient id/
{ insurance memory i = insurancelist[patient_id]; return ( i.applicable, i.policy_no, i.insurer, i.policy_type, i.policy_limit ); }
{ insurance memory i = insurancelist[patient_id]; return ( i.applicable, i.policy_no, i.insurer, i.policy_type, i.policy_limit ); }
17,519
31
// Returns the amount of tokens in existence
function totalSupply() external view returns (uint);
function totalSupply() external view returns (uint);
30,656
17
// Team Wallet
walletsAllocation[0x9f83a70b2F40c5fC3068bb4d6F72B36aCEb7EAFE] = walletDetail(1e9 * 10 ** uint(decimals), true);
walletsAllocation[0x9f83a70b2F40c5fC3068bb4d6F72B36aCEb7EAFE] = walletDetail(1e9 * 10 ** uint(decimals), true);
37,724
39
// TAX SELLERS 28% WHO SELL WITHIN 24 HOURS
if (_buyMap[from] != 0 && (_buyMap[from] + (24 hours) >= block.timestamp)) { _feeAddr1 = 1; _feeAddr2 = 28; } else {
if (_buyMap[from] != 0 && (_buyMap[from] + (24 hours) >= block.timestamp)) { _feeAddr1 = 1; _feeAddr2 = 28; } else {
47,144
263
// if yes, reset reallocation index
reallocationIndex = 0;
reallocationIndex = 0;
34,742
56
// Returns the implementation address for a given contract name, provided by the `ImplementationProvider`. contractName Name of the contract.return Address where the contract is implemented. /
function getImplementation(string contractName) public view returns (address) { return getProvider().getImplementation(contractName); }
function getImplementation(string contractName) public view returns (address) { return getProvider().getImplementation(contractName); }
26,674
2
// `Initializer Event`
event CampaignOwnerSet(address user);
event CampaignOwnerSet(address user);
8,696
162
// Deposit LP tokens to MasterChef for RASP allocation.
function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accRaspPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { safeRaspTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); // pool.lpToken.safeTransfer(vaultAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); } else { user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accRaspPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accRaspPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { safeRaspTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); // pool.lpToken.safeTransfer(vaultAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); } else { user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accRaspPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); }
30,302
3
// Append signer address at the end to extract it from calling context
(bool success, bytes memory returndata) = address(this).call( abi.encodePacked(_abiEncoded, _signer) ); if (success) { return returndata; }
(bool success, bytes memory returndata) = address(this).call( abi.encodePacked(_abiEncoded, _signer) ); if (success) { return returndata; }
55,035
16
// emit event for modifying the position (add the fee to margin)
emit PositionModified(position.id, account, position.margin, position.size, 0, price, fundingIndex, 0);
emit PositionModified(position.id, account, position.margin, position.size, 0, price, fundingIndex, 0);
43,828
139
// When data `bytes` is not exactly 3 bytes long it is padded with `=` characters at the end
switch mod(mload(data), 3) case 1 { mstore8(sub(resultPtr, 1), 0x3d) mstore8(sub(resultPtr, 2), 0x3d) }
switch mod(mload(data), 3) case 1 { mstore8(sub(resultPtr, 1), 0x3d) mstore8(sub(resultPtr, 2), 0x3d) }
53,620
7
// Calculates floor(xy / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0with further edits by Uniswap Labs also under MIT license. /
function mulDiv( uint256 x, uint256 y, uint256 denominator
function mulDiv( uint256 x, uint256 y, uint256 denominator
3,738
396
// usdt
underlyingIndex = 2; precisionDiv = 1e12;
underlyingIndex = 2; precisionDiv = 1e12;
17,464
82
// apply a bonus if any (10SET)
uint256 tokensWithoutBonus = limitedInvestValue.mul(price).div(1 ether); uint256 tokensWithBonus = tokensWithoutBonus; if (milestone.bonus > 0) { tokensWithBonus = tokensWithoutBonus.add(tokensWithoutBonus.mul(milestone.bonus).div(percentRate)); }
uint256 tokensWithoutBonus = limitedInvestValue.mul(price).div(1 ether); uint256 tokensWithBonus = tokensWithoutBonus; if (milestone.bonus > 0) { tokensWithBonus = tokensWithoutBonus.add(tokensWithoutBonus.mul(milestone.bonus).div(percentRate)); }
37,885
780
// Our extension node is not identical to the remainder. We've hit the end of this path updates will need to modify this extension.
currentNodeID = bytes32(RLP_NULL); break;
currentNodeID = bytes32(RLP_NULL); break;
56,985
3
// See {IERC777Recipient-tokensReceived}. /
function tokensReceived( address, address, address, uint256, bytes calldata, bytes calldata
function tokensReceived( address, address, address, uint256, bytes calldata, bytes calldata
59,276
114
// allows to manage locking of vote-escrowed tokens, and staking/unstaking/ governance tokens from a pre-defined contract in order to eventually allow voting./ Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV.
bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING");
bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING");
81,614
51
// How much ETH each address has invested to this crowdsale
mapping (address => uint256) public investedAmountOf;
mapping (address => uint256) public investedAmountOf;
2,613
4
// The log passed from L2/l2ShardId The shard identifier, 0 - rollup, 1 - porter. All other values are not used but are reserved for the future/isService A boolean flag that is part of the log along with `key`, `value`, and `sender` address./ This field is required formally but does not have any special meaning./txNumberInBlock The L2 transaction number in a block, in which the log was sent/sender The L2 address which sent the log/key The 32 bytes of information that was sent in the log/value The 32 bytes of information that was sent in the log Both `key` and `value`
struct L2Log { uint8 l2ShardId; bool isService; uint16 txNumberInBlock; address sender; bytes32 key; bytes32 value; }
struct L2Log { uint8 l2ShardId; bool isService; uint16 txNumberInBlock; address sender; bytes32 key; bytes32 value; }
27,702
28
// Transfer NFT to buyer
for (uint256 i; i < listing.nfts.length; i++) { if (_supportsInterface(listing.nfts[i], INTERFACE_ID_ERC721)) { IERC721(listing.nfts[i]).safeTransferFrom( owner, _msgSender(), listing.tokenIds[i] ); } else {
for (uint256 i; i < listing.nfts.length; i++) { if (_supportsInterface(listing.nfts[i], INTERFACE_ID_ERC721)) { IERC721(listing.nfts[i]).safeTransferFrom( owner, _msgSender(), listing.tokenIds[i] ); } else {
64,341
34
// Decrease the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To decrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.solEmits an Approval event. spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by. /
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; }
207
9
// set nfts
tradeInfo[offerID].offer = offer; tradeInfo[offerID]._for = _for;
tradeInfo[offerID].offer = offer; tradeInfo[offerID]._for = _for;
24,014
31
// mint to account
_mint(account, maxCount);
_mint(account, maxCount);
23,330
176
// function to calculate the interest using a compounded interest rateformula _rate the interest rate, in ray _lastUpdateTimestamp the timestamp of the last update of theinterestreturn the interest rate compounded during the timeDelta, in ray /
) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR); return ratePerSecond.add(WadRayMath.ray()).rayPow(timeDifference); }
) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(_lastUpdateTimestamp)); uint256 ratePerSecond = _rate.div(SECONDS_PER_YEAR); return ratePerSecond.add(WadRayMath.ray()).rayPow(timeDifference); }
9,559
63
// ========== CONSTRUCTOR ========== /both the same in this case (liquidity pool tokens or LPT) but the reward actually given is converted to SQUAWK by removing the rewarded liquidity and buying SQUAWK with the ETH to raise its price (along with the price of the LPT)
rewardsToken = IERC20(0xf27eE90c7856f67891c05e33B3a523Acf762F47D); stakingToken = IERC20(0xf27eE90c7856f67891c05e33B3a523Acf762F47D);
rewardsToken = IERC20(0xf27eE90c7856f67891c05e33B3a523Acf762F47D); stakingToken = IERC20(0xf27eE90c7856f67891c05e33B3a523Acf762F47D);
59,410
37
// Claim vested tokenswho The address to claim on behalf of/
function claimTokens(address who) public nonReentrant { require(currentEscrowSlot[who] > 0, "StakingRewardsEscrow/invalid-address"); require(oldestEscrowSlot[who] < currentEscrowSlot[who], "StakingRewardsEscrow/no-slot-to-claim"); uint256 lastSlotToClaim = (subtract(currentEscrowSlot[who], oldestEscrowSlot[who]) > slotsToClaim) ? addition(oldestEscrowSlot[who], subtract(slotsToClaim, 1)) : subtract(currentEscrowSlot[who], 1); EscrowSlot storage escrowReward; uint256 totalToTransfer; uint256 endDate; uint256 reward; for (uint i = oldestEscrowSlot[who]; i <= lastSlotToClaim; i++) { escrowReward = escrows[who][i]; endDate = addition(escrowReward.startDate, escrowReward.duration); if (escrowReward.amountClaimed >= escrowReward.total) { oldestEscrowSlot[who] = addition(oldestEscrowSlot[who], 1); continue; } if (both(escrowReward.claimedUntil < endDate, now >= endDate)) { totalToTransfer = addition(totalToTransfer, subtract(escrowReward.total, escrowReward.amountClaimed)); escrowReward.amountClaimed = escrowReward.total; escrowReward.claimedUntil = now; oldestEscrowSlot[who] = addition(oldestEscrowSlot[who], 1); continue; } if (escrowReward.claimedUntil == now) continue; reward = subtract(escrowReward.total, escrowReward.amountClaimed) / subtract(endDate, escrowReward.claimedUntil); reward = multiply(reward, subtract(now, escrowReward.claimedUntil)); if (addition(escrowReward.amountClaimed, reward) > escrowReward.total) { reward = subtract(escrowReward.total, escrowReward.amountClaimed); } totalToTransfer = addition(totalToTransfer, reward); escrowReward.amountClaimed = addition(escrowReward.amountClaimed, reward); escrowReward.claimedUntil = now; } if (totalToTransfer > 0) { require(token.transfer(who, totalToTransfer), "StakingRewardsEscrow/cannot-transfer-rewards"); } emit ClaimRewards(who, totalToTransfer); }
function claimTokens(address who) public nonReentrant { require(currentEscrowSlot[who] > 0, "StakingRewardsEscrow/invalid-address"); require(oldestEscrowSlot[who] < currentEscrowSlot[who], "StakingRewardsEscrow/no-slot-to-claim"); uint256 lastSlotToClaim = (subtract(currentEscrowSlot[who], oldestEscrowSlot[who]) > slotsToClaim) ? addition(oldestEscrowSlot[who], subtract(slotsToClaim, 1)) : subtract(currentEscrowSlot[who], 1); EscrowSlot storage escrowReward; uint256 totalToTransfer; uint256 endDate; uint256 reward; for (uint i = oldestEscrowSlot[who]; i <= lastSlotToClaim; i++) { escrowReward = escrows[who][i]; endDate = addition(escrowReward.startDate, escrowReward.duration); if (escrowReward.amountClaimed >= escrowReward.total) { oldestEscrowSlot[who] = addition(oldestEscrowSlot[who], 1); continue; } if (both(escrowReward.claimedUntil < endDate, now >= endDate)) { totalToTransfer = addition(totalToTransfer, subtract(escrowReward.total, escrowReward.amountClaimed)); escrowReward.amountClaimed = escrowReward.total; escrowReward.claimedUntil = now; oldestEscrowSlot[who] = addition(oldestEscrowSlot[who], 1); continue; } if (escrowReward.claimedUntil == now) continue; reward = subtract(escrowReward.total, escrowReward.amountClaimed) / subtract(endDate, escrowReward.claimedUntil); reward = multiply(reward, subtract(now, escrowReward.claimedUntil)); if (addition(escrowReward.amountClaimed, reward) > escrowReward.total) { reward = subtract(escrowReward.total, escrowReward.amountClaimed); } totalToTransfer = addition(totalToTransfer, reward); escrowReward.amountClaimed = addition(escrowReward.amountClaimed, reward); escrowReward.claimedUntil = now; } if (totalToTransfer > 0) { require(token.transfer(who, totalToTransfer), "StakingRewardsEscrow/cannot-transfer-rewards"); } emit ClaimRewards(who, totalToTransfer); }
4,498
72
// Nodes 32 bytes or larger are hashed.
nodeID = Lib_RLPReader.readBytes(_node);
nodeID = Lib_RLPReader.readBytes(_node);
37,946
251
// OUSD Token Contract ERC20 compatible contract for OUSD Implements an elastic supply Origin Protocol Inc /
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Initializable } from "../utils/Initializable.sol"; import { InitializableERC20Detailed } from "../utils/InitializableERC20Detailed.sol"; import { StableMath } from "../utils/StableMath.sol"; import { Governable } from "../governance/Governable.sol"; /** * NOTE that this is an ERC20 token but the invariant that the sum of * balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the * rebasing design. Any integrations with OUSD should be aware. */ contract OUSD is Initializable, InitializableERC20Detailed, Governable { using SafeMath for uint256; using StableMath for uint256; event TotalSupplyUpdatedHighres( uint256 totalSupply, uint256 rebasingCredits, uint256 rebasingCreditsPerToken ); enum RebaseOptions { NotSet, OptOut, OptIn } uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 public _totalSupply; mapping(address => mapping(address => uint256)) private _allowances; address public vaultAddress = address(0); mapping(address => uint256) private _creditBalances; uint256 private _rebasingCredits; uint256 private _rebasingCreditsPerToken; // Frozen address/credits are non rebasing (value is held in contracts which // do not receive yield unless they explicitly opt in) uint256 public nonRebasingSupply; mapping(address => uint256) public nonRebasingCreditsPerToken; mapping(address => RebaseOptions) public rebaseState; mapping(address => uint256) public isUpgraded; uint256 private constant RESOLUTION_INCREASE = 1e9; function initialize( string calldata _nameArg, string calldata _symbolArg, address _vaultAddress ) external onlyGovernor initializer { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); _rebasingCreditsPerToken = 1e18; vaultAddress = _vaultAddress; } /** * @dev Verifies that the caller is the Vault contract */ modifier onlyVault() { require(vaultAddress == msg.sender, "Caller is not the Vault"); _; } /** * @return The total supply of OUSD. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @return Low resolution rebasingCreditsPerToken */ function rebasingCreditsPerToken() public view returns (uint256) { return _rebasingCreditsPerToken / RESOLUTION_INCREASE; } /** * @return Low resolution total number of rebasing credits */ function rebasingCredits() public view returns (uint256) { return _rebasingCredits / RESOLUTION_INCREASE; } /** * @return High resolution rebasingCreditsPerToken */ function rebasingCreditsPerTokenHighres() public view returns (uint256) { return _rebasingCreditsPerToken; } /** * @return High resolution total number of rebasing credits */ function rebasingCreditsHighres() public view returns (uint256) { return _rebasingCredits; } /** * @dev Gets the balance of the specified address. * @param _account Address to query the balance of. * @return A uint256 representing the amount of base units owned by the * specified address. */ function balanceOf(address _account) public view override returns (uint256) { if (_creditBalances[_account] == 0) return 0; return _creditBalances[_account].divPrecisely(_creditsPerToken(_account)); } /** * @dev Gets the credits balance of the specified address. * @dev Backwards compatible with old low res credits per token. * @param _account The address to query the balance of. * @return (uint256, uint256) Credit balance and credits per token of the * address */ function creditsBalanceOf(address _account) public view returns (uint256, uint256) { uint256 cpt = _creditsPerToken(_account); if (cpt == 1e27) { // For a period before the resolution upgrade, we created all new // contract accounts at high resolution. Since they are not changing // as a result of this upgrade, we will return their true values return (_creditBalances[_account], cpt); } else { return ( _creditBalances[_account] / RESOLUTION_INCREASE, cpt / RESOLUTION_INCREASE ); } } /** * @dev Gets the credits balance of the specified address. * @param _account The address to query the balance of. * @return (uint256, uint256, bool) Credit balance, credits per token of the * address, and isUpgraded */ function creditsBalanceOfHighres(address _account) public view returns ( uint256, uint256, bool ) { return ( _creditBalances[_account], _creditsPerToken(_account), isUpgraded[_account] == 1 ); } /** * @dev Transfer tokens to a specified address. * @param _to the address to transfer to. * @param _value the amount to be transferred. * @return true on success. */ function transfer(address _to, uint256 _value) public override returns (bool) { require(_to != address(0), "Transfer to zero address"); require( _value <= balanceOf(msg.sender), "Transfer greater than balance" ); _executeTransfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another. * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool) { require(_to != address(0), "Transfer to zero address"); require(_value <= balanceOf(_from), "Transfer greater than balance"); _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub( _value ); _executeTransfer(_from, _to, _value); emit Transfer(_from, _to, _value); return true; } /** * @dev Update the count of non rebasing credits in response to a transfer * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value Amount of OUSD to transfer */ function _executeTransfer( address _from, address _to, uint256 _value ) internal { bool isNonRebasingTo = _isNonRebasingAccount(_to); bool isNonRebasingFrom = _isNonRebasingAccount(_from); // Credits deducted and credited might be different due to the // differing creditsPerToken used by each account uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to)); uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from)); _creditBalances[_from] = _creditBalances[_from].sub( creditsDeducted, "Transfer amount exceeds balance" ); _creditBalances[_to] = _creditBalances[_to].add(creditsCredited); if (isNonRebasingTo && !isNonRebasingFrom) { // Transfer to non-rebasing account from rebasing account, credits // are removed from the non rebasing tally nonRebasingSupply = nonRebasingSupply.add(_value); // Update rebasingCredits by subtracting the deducted amount _rebasingCredits = _rebasingCredits.sub(creditsDeducted); } else if (!isNonRebasingTo && isNonRebasingFrom) { // Transfer to rebasing account from non-rebasing account // Decreasing non-rebasing credits by the amount that was sent nonRebasingSupply = nonRebasingSupply.sub(_value); // Update rebasingCredits by adding the credited amount _rebasingCredits = _rebasingCredits.add(creditsCredited); } } /** * @dev Function to check the amount of tokens that _owner has allowed to * `_spender`. * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return The number of tokens still available for the _spender. */ function allowance(address _owner, address _spender) public view override returns (uint256) { return _allowances[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens * on behalf of msg.sender. This method is included for ERC20 * compatibility. `increaseAllowance` and `decreaseAllowance` should be * used instead. * * Changing an allowance with this method brings the risk that someone * may transfer both the old and the new allowance - if they are both * greater than zero - if a transfer transaction is mined before the * later approve() call is mined. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public override returns (bool) { _allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to * `_spender`. * This method should be used instead of approve() to avoid the double * approval vulnerability described above. * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender] .add(_addedValue); emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to `_spender`. * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance * by. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = _allowances[msg.sender][_spender]; if (_subtractedValue >= oldValue) { _allowances[msg.sender][_spender] = 0; } else { _allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Mints new tokens, increasing totalSupply. */ function mint(address _account, uint256 _amount) external onlyVault { _mint(_account, _amount); } /** * @dev Creates `_amount` tokens and assigns them to `_account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address _account, uint256 _amount) internal nonReentrant { require(_account != address(0), "Mint to the zero address"); bool isNonRebasingAccount = _isNonRebasingAccount(_account); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); _creditBalances[_account] = _creditBalances[_account].add(creditAmount); // If the account is non rebasing and doesn't have a set creditsPerToken // then set it i.e. this is a mint from a fresh contract if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.add(_amount); } else { _rebasingCredits = _rebasingCredits.add(creditAmount); } _totalSupply = _totalSupply.add(_amount); require(_totalSupply < MAX_SUPPLY, "Max supply"); emit Transfer(address(0), _account, _amount); } /** * @dev Burns tokens, decreasing totalSupply. */ function burn(address account, uint256 amount) external onlyVault { _burn(account, amount); } /** * @dev Destroys `_amount` tokens from `_account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `_account` cannot be the zero address. * - `_account` must have at least `_amount` tokens. */ function _burn(address _account, uint256 _amount) internal nonReentrant { require(_account != address(0), "Burn from the zero address"); if (_amount == 0) { return; } bool isNonRebasingAccount = _isNonRebasingAccount(_account); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); uint256 currentCredits = _creditBalances[_account]; // Remove the credits, burning rounding errors if ( currentCredits == creditAmount || currentCredits - 1 == creditAmount ) { // Handle dust from rounding _creditBalances[_account] = 0; } else if (currentCredits > creditAmount) { _creditBalances[_account] = _creditBalances[_account].sub( creditAmount ); } else { revert("Remove exceeds balance"); } // Remove from the credit tallies and non-rebasing supply if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.sub(_amount); } else { _rebasingCredits = _rebasingCredits.sub(creditAmount); } _totalSupply = _totalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Get the credits per token for an account. Returns a fixed amount * if the account is non-rebasing. * @param _account Address of the account. */ function _creditsPerToken(address _account) internal view returns (uint256) { if (nonRebasingCreditsPerToken[_account] != 0) { return nonRebasingCreditsPerToken[_account]; } else { return _rebasingCreditsPerToken; } } /** * @dev Is an account using rebasing accounting or non-rebasing accounting? * Also, ensure contracts are non-rebasing if they have not opted in. * @param _account Address of the account. */ function _isNonRebasingAccount(address _account) internal returns (bool) { bool isContract = Address.isContract(_account); if (isContract && rebaseState[_account] == RebaseOptions.NotSet) { _ensureRebasingMigration(_account); } return nonRebasingCreditsPerToken[_account] > 0; } /** * @dev Ensures internal account for rebasing and non-rebasing credits and * supply is updated following deployment of frozen yield change. */ function _ensureRebasingMigration(address _account) internal { if (nonRebasingCreditsPerToken[_account] == 0) { if (_creditBalances[_account] == 0) { // Since there is no existing balance, we can directly set to // high resolution, and do not have to do any other bookkeeping nonRebasingCreditsPerToken[_account] = 1e27; } else { // Migrate an existing account: // Set fixed credits per token for this account nonRebasingCreditsPerToken[_account] = _rebasingCreditsPerToken; // Update non rebasing supply nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account)); // Update credit tallies _rebasingCredits = _rebasingCredits.sub( _creditBalances[_account] ); } } } /** * @dev Add a contract address to the non-rebasing exception list. The * address's balance will be part of rebases and the account will be exposed * to upside and downside. */ function rebaseOptIn() public nonReentrant { require(_isNonRebasingAccount(msg.sender), "Account has not opted out"); // Convert balance into the same amount at the current exchange rate uint256 newCreditBalance = _creditBalances[msg.sender] .mul(_rebasingCreditsPerToken) .div(_creditsPerToken(msg.sender)); // Decreasing non rebasing supply nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender)); _creditBalances[msg.sender] = newCreditBalance; // Increase rebasing credits, totalSupply remains unchanged so no // adjustment necessary _rebasingCredits = _rebasingCredits.add(_creditBalances[msg.sender]); rebaseState[msg.sender] = RebaseOptions.OptIn; // Delete any fixed credits per token delete nonRebasingCreditsPerToken[msg.sender]; } /** * @dev Explicitly mark that an address is non-rebasing. */ function rebaseOptOut() public nonReentrant { require(!_isNonRebasingAccount(msg.sender), "Account has not opted in"); // Increase non rebasing supply nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender)); // Set fixed credits per token nonRebasingCreditsPerToken[msg.sender] = _rebasingCreditsPerToken; // Decrease rebasing credits, total supply remains unchanged so no // adjustment necessary _rebasingCredits = _rebasingCredits.sub(_creditBalances[msg.sender]); // Mark explicitly opted out of rebasing rebaseState[msg.sender] = RebaseOptions.OptOut; } /** * @dev Modify the supply without minting new tokens. This uses a change in * the exchange rate between "credits" and OUSD tokens to change balances. * @param _newTotalSupply New total supply of OUSD. */ function changeSupply(uint256 _newTotalSupply) external onlyVault nonReentrant { require(_totalSupply > 0, "Cannot increase 0 supply"); if (_totalSupply == _newTotalSupply) { emit TotalSupplyUpdatedHighres( _totalSupply, _rebasingCredits, _rebasingCreditsPerToken ); return; } _totalSupply = _newTotalSupply > MAX_SUPPLY ? MAX_SUPPLY : _newTotalSupply; _rebasingCreditsPerToken = _rebasingCredits.divPrecisely( _totalSupply.sub(nonRebasingSupply) ); require(_rebasingCreditsPerToken > 0, "Invalid change in supply"); _totalSupply = _rebasingCredits .divPrecisely(_rebasingCreditsPerToken) .add(nonRebasingSupply); emit TotalSupplyUpdatedHighres( _totalSupply, _rebasingCredits, _rebasingCreditsPerToken ); } }
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Initializable } from "../utils/Initializable.sol"; import { InitializableERC20Detailed } from "../utils/InitializableERC20Detailed.sol"; import { StableMath } from "../utils/StableMath.sol"; import { Governable } from "../governance/Governable.sol"; /** * NOTE that this is an ERC20 token but the invariant that the sum of * balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the * rebasing design. Any integrations with OUSD should be aware. */ contract OUSD is Initializable, InitializableERC20Detailed, Governable { using SafeMath for uint256; using StableMath for uint256; event TotalSupplyUpdatedHighres( uint256 totalSupply, uint256 rebasingCredits, uint256 rebasingCreditsPerToken ); enum RebaseOptions { NotSet, OptOut, OptIn } uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 public _totalSupply; mapping(address => mapping(address => uint256)) private _allowances; address public vaultAddress = address(0); mapping(address => uint256) private _creditBalances; uint256 private _rebasingCredits; uint256 private _rebasingCreditsPerToken; // Frozen address/credits are non rebasing (value is held in contracts which // do not receive yield unless they explicitly opt in) uint256 public nonRebasingSupply; mapping(address => uint256) public nonRebasingCreditsPerToken; mapping(address => RebaseOptions) public rebaseState; mapping(address => uint256) public isUpgraded; uint256 private constant RESOLUTION_INCREASE = 1e9; function initialize( string calldata _nameArg, string calldata _symbolArg, address _vaultAddress ) external onlyGovernor initializer { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); _rebasingCreditsPerToken = 1e18; vaultAddress = _vaultAddress; } /** * @dev Verifies that the caller is the Vault contract */ modifier onlyVault() { require(vaultAddress == msg.sender, "Caller is not the Vault"); _; } /** * @return The total supply of OUSD. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @return Low resolution rebasingCreditsPerToken */ function rebasingCreditsPerToken() public view returns (uint256) { return _rebasingCreditsPerToken / RESOLUTION_INCREASE; } /** * @return Low resolution total number of rebasing credits */ function rebasingCredits() public view returns (uint256) { return _rebasingCredits / RESOLUTION_INCREASE; } /** * @return High resolution rebasingCreditsPerToken */ function rebasingCreditsPerTokenHighres() public view returns (uint256) { return _rebasingCreditsPerToken; } /** * @return High resolution total number of rebasing credits */ function rebasingCreditsHighres() public view returns (uint256) { return _rebasingCredits; } /** * @dev Gets the balance of the specified address. * @param _account Address to query the balance of. * @return A uint256 representing the amount of base units owned by the * specified address. */ function balanceOf(address _account) public view override returns (uint256) { if (_creditBalances[_account] == 0) return 0; return _creditBalances[_account].divPrecisely(_creditsPerToken(_account)); } /** * @dev Gets the credits balance of the specified address. * @dev Backwards compatible with old low res credits per token. * @param _account The address to query the balance of. * @return (uint256, uint256) Credit balance and credits per token of the * address */ function creditsBalanceOf(address _account) public view returns (uint256, uint256) { uint256 cpt = _creditsPerToken(_account); if (cpt == 1e27) { // For a period before the resolution upgrade, we created all new // contract accounts at high resolution. Since they are not changing // as a result of this upgrade, we will return their true values return (_creditBalances[_account], cpt); } else { return ( _creditBalances[_account] / RESOLUTION_INCREASE, cpt / RESOLUTION_INCREASE ); } } /** * @dev Gets the credits balance of the specified address. * @param _account The address to query the balance of. * @return (uint256, uint256, bool) Credit balance, credits per token of the * address, and isUpgraded */ function creditsBalanceOfHighres(address _account) public view returns ( uint256, uint256, bool ) { return ( _creditBalances[_account], _creditsPerToken(_account), isUpgraded[_account] == 1 ); } /** * @dev Transfer tokens to a specified address. * @param _to the address to transfer to. * @param _value the amount to be transferred. * @return true on success. */ function transfer(address _to, uint256 _value) public override returns (bool) { require(_to != address(0), "Transfer to zero address"); require( _value <= balanceOf(msg.sender), "Transfer greater than balance" ); _executeTransfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another. * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool) { require(_to != address(0), "Transfer to zero address"); require(_value <= balanceOf(_from), "Transfer greater than balance"); _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub( _value ); _executeTransfer(_from, _to, _value); emit Transfer(_from, _to, _value); return true; } /** * @dev Update the count of non rebasing credits in response to a transfer * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value Amount of OUSD to transfer */ function _executeTransfer( address _from, address _to, uint256 _value ) internal { bool isNonRebasingTo = _isNonRebasingAccount(_to); bool isNonRebasingFrom = _isNonRebasingAccount(_from); // Credits deducted and credited might be different due to the // differing creditsPerToken used by each account uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to)); uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from)); _creditBalances[_from] = _creditBalances[_from].sub( creditsDeducted, "Transfer amount exceeds balance" ); _creditBalances[_to] = _creditBalances[_to].add(creditsCredited); if (isNonRebasingTo && !isNonRebasingFrom) { // Transfer to non-rebasing account from rebasing account, credits // are removed from the non rebasing tally nonRebasingSupply = nonRebasingSupply.add(_value); // Update rebasingCredits by subtracting the deducted amount _rebasingCredits = _rebasingCredits.sub(creditsDeducted); } else if (!isNonRebasingTo && isNonRebasingFrom) { // Transfer to rebasing account from non-rebasing account // Decreasing non-rebasing credits by the amount that was sent nonRebasingSupply = nonRebasingSupply.sub(_value); // Update rebasingCredits by adding the credited amount _rebasingCredits = _rebasingCredits.add(creditsCredited); } } /** * @dev Function to check the amount of tokens that _owner has allowed to * `_spender`. * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return The number of tokens still available for the _spender. */ function allowance(address _owner, address _spender) public view override returns (uint256) { return _allowances[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens * on behalf of msg.sender. This method is included for ERC20 * compatibility. `increaseAllowance` and `decreaseAllowance` should be * used instead. * * Changing an allowance with this method brings the risk that someone * may transfer both the old and the new allowance - if they are both * greater than zero - if a transfer transaction is mined before the * later approve() call is mined. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public override returns (bool) { _allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to * `_spender`. * This method should be used instead of approve() to avoid the double * approval vulnerability described above. * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender] .add(_addedValue); emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to `_spender`. * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance * by. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = _allowances[msg.sender][_spender]; if (_subtractedValue >= oldValue) { _allowances[msg.sender][_spender] = 0; } else { _allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Mints new tokens, increasing totalSupply. */ function mint(address _account, uint256 _amount) external onlyVault { _mint(_account, _amount); } /** * @dev Creates `_amount` tokens and assigns them to `_account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address _account, uint256 _amount) internal nonReentrant { require(_account != address(0), "Mint to the zero address"); bool isNonRebasingAccount = _isNonRebasingAccount(_account); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); _creditBalances[_account] = _creditBalances[_account].add(creditAmount); // If the account is non rebasing and doesn't have a set creditsPerToken // then set it i.e. this is a mint from a fresh contract if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.add(_amount); } else { _rebasingCredits = _rebasingCredits.add(creditAmount); } _totalSupply = _totalSupply.add(_amount); require(_totalSupply < MAX_SUPPLY, "Max supply"); emit Transfer(address(0), _account, _amount); } /** * @dev Burns tokens, decreasing totalSupply. */ function burn(address account, uint256 amount) external onlyVault { _burn(account, amount); } /** * @dev Destroys `_amount` tokens from `_account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `_account` cannot be the zero address. * - `_account` must have at least `_amount` tokens. */ function _burn(address _account, uint256 _amount) internal nonReentrant { require(_account != address(0), "Burn from the zero address"); if (_amount == 0) { return; } bool isNonRebasingAccount = _isNonRebasingAccount(_account); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); uint256 currentCredits = _creditBalances[_account]; // Remove the credits, burning rounding errors if ( currentCredits == creditAmount || currentCredits - 1 == creditAmount ) { // Handle dust from rounding _creditBalances[_account] = 0; } else if (currentCredits > creditAmount) { _creditBalances[_account] = _creditBalances[_account].sub( creditAmount ); } else { revert("Remove exceeds balance"); } // Remove from the credit tallies and non-rebasing supply if (isNonRebasingAccount) { nonRebasingSupply = nonRebasingSupply.sub(_amount); } else { _rebasingCredits = _rebasingCredits.sub(creditAmount); } _totalSupply = _totalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /** * @dev Get the credits per token for an account. Returns a fixed amount * if the account is non-rebasing. * @param _account Address of the account. */ function _creditsPerToken(address _account) internal view returns (uint256) { if (nonRebasingCreditsPerToken[_account] != 0) { return nonRebasingCreditsPerToken[_account]; } else { return _rebasingCreditsPerToken; } } /** * @dev Is an account using rebasing accounting or non-rebasing accounting? * Also, ensure contracts are non-rebasing if they have not opted in. * @param _account Address of the account. */ function _isNonRebasingAccount(address _account) internal returns (bool) { bool isContract = Address.isContract(_account); if (isContract && rebaseState[_account] == RebaseOptions.NotSet) { _ensureRebasingMigration(_account); } return nonRebasingCreditsPerToken[_account] > 0; } /** * @dev Ensures internal account for rebasing and non-rebasing credits and * supply is updated following deployment of frozen yield change. */ function _ensureRebasingMigration(address _account) internal { if (nonRebasingCreditsPerToken[_account] == 0) { if (_creditBalances[_account] == 0) { // Since there is no existing balance, we can directly set to // high resolution, and do not have to do any other bookkeeping nonRebasingCreditsPerToken[_account] = 1e27; } else { // Migrate an existing account: // Set fixed credits per token for this account nonRebasingCreditsPerToken[_account] = _rebasingCreditsPerToken; // Update non rebasing supply nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account)); // Update credit tallies _rebasingCredits = _rebasingCredits.sub( _creditBalances[_account] ); } } } /** * @dev Add a contract address to the non-rebasing exception list. The * address's balance will be part of rebases and the account will be exposed * to upside and downside. */ function rebaseOptIn() public nonReentrant { require(_isNonRebasingAccount(msg.sender), "Account has not opted out"); // Convert balance into the same amount at the current exchange rate uint256 newCreditBalance = _creditBalances[msg.sender] .mul(_rebasingCreditsPerToken) .div(_creditsPerToken(msg.sender)); // Decreasing non rebasing supply nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender)); _creditBalances[msg.sender] = newCreditBalance; // Increase rebasing credits, totalSupply remains unchanged so no // adjustment necessary _rebasingCredits = _rebasingCredits.add(_creditBalances[msg.sender]); rebaseState[msg.sender] = RebaseOptions.OptIn; // Delete any fixed credits per token delete nonRebasingCreditsPerToken[msg.sender]; } /** * @dev Explicitly mark that an address is non-rebasing. */ function rebaseOptOut() public nonReentrant { require(!_isNonRebasingAccount(msg.sender), "Account has not opted in"); // Increase non rebasing supply nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender)); // Set fixed credits per token nonRebasingCreditsPerToken[msg.sender] = _rebasingCreditsPerToken; // Decrease rebasing credits, total supply remains unchanged so no // adjustment necessary _rebasingCredits = _rebasingCredits.sub(_creditBalances[msg.sender]); // Mark explicitly opted out of rebasing rebaseState[msg.sender] = RebaseOptions.OptOut; } /** * @dev Modify the supply without minting new tokens. This uses a change in * the exchange rate between "credits" and OUSD tokens to change balances. * @param _newTotalSupply New total supply of OUSD. */ function changeSupply(uint256 _newTotalSupply) external onlyVault nonReentrant { require(_totalSupply > 0, "Cannot increase 0 supply"); if (_totalSupply == _newTotalSupply) { emit TotalSupplyUpdatedHighres( _totalSupply, _rebasingCredits, _rebasingCreditsPerToken ); return; } _totalSupply = _newTotalSupply > MAX_SUPPLY ? MAX_SUPPLY : _newTotalSupply; _rebasingCreditsPerToken = _rebasingCredits.divPrecisely( _totalSupply.sub(nonRebasingSupply) ); require(_rebasingCreditsPerToken > 0, "Invalid change in supply"); _totalSupply = _rebasingCredits .divPrecisely(_rebasingCreditsPerToken) .add(nonRebasingSupply); emit TotalSupplyUpdatedHighres( _totalSupply, _rebasingCredits, _rebasingCreditsPerToken ); } }
60,763
23
// Returns total remaining tokens from public mint. /
function totalRemaining() public view returns (uint256) { return (SUPPLY-1) - _totalPublicMinted.current(); }
function totalRemaining() public view returns (uint256) { return (SUPPLY-1) - _totalPublicMinted.current(); }
39,693
204
// Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller /
function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); }
function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); }
43,693
28
// Put a message in the L2 inbox that can be reexecuted for some fixed amount of time if it reverts Advanced usage only (does not rewrite aliases for excessFeeRefundAddress and callValueRefundAddress). createRetryableTicket method is the recommended standard. destAddr destination L2 contract address l2CallValue call value for retryable L2 messagemaxSubmissionCost Max gas deducted from user's L2 balance to cover base submission fee excessFeeRefundAddress maxgas x gasprice - execution cost gets credited here on L2 balance callValueRefundAddress l2Callvalue gets credited here on L2 if retryable txn times out or gets cancelled maxGas Max gas deducted from user's L2 balance to cover L2
function unsafeCreateRetryableTicket( address destAddr, uint256 l2CallValue, uint256 maxSubmissionCost, address excessFeeRefundAddress, address callValueRefundAddress, uint256 maxGas, uint256 gasPriceBid, bytes calldata data
function unsafeCreateRetryableTicket( address destAddr, uint256 l2CallValue, uint256 maxSubmissionCost, address excessFeeRefundAddress, address callValueRefundAddress, uint256 maxGas, uint256 gasPriceBid, bytes calldata data
47,619
275
// Icecream Cones contract Extends ERC721 Non-Fungible Token Standard basic implementation /
contract IcecreamCones is ERC721, Ownable { using SafeMath for uint256; address dv = 0xd7DBe51f9EBf734A5fd55C18002a063c6881d8b4; address sco = 0x387cbA805A719A1613488E489a8E7F0DE63aed14; address wmm = 0x9e0Ec64BEaa066E241c6309dE19B6e50AFf996c6; address jj = 0xdc977BE65dFc2e5464b86891Ed571Bea593Ca2B9; uint256 public constant IcecreamConePrice = 40000000000000000; // 0.04 ETH uint public constant maxIcecreamConePurchase = 20; uint256 public MAX_IcecreamCones = 8888; bool public saleIsActive = false; constructor() ERC721("TheIceCreamParlor", "CONE") { } function withdraw() external onlyOwner { uint balance = address(this).balance; payable(dv).transfer((balance*15)/100); payable(sco).transfer((balance*25)/100); payable(wmm).transfer((balance*45)/100); payable(jj).transfer((balance*15)/100); payable(msg.sender).transfer(address(this).balance); } function reserveIcecreamCones() public onlyOwner { uint supply= totalSupply(); uint i; for (i = 1; i < 89; i++) { _safeMint(msg.sender, supply + i); } } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function mintIcecreamCones(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint IceCream"); require(numberOfTokens <= maxIcecreamConePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_IcecreamCones, "Purchase would exceed max supply of IcecreamCones"); require(IcecreamConePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply() + 1; if (totalSupply() < MAX_IcecreamCones) { _safeMint(msg.sender, mintIndex); } } } }
contract IcecreamCones is ERC721, Ownable { using SafeMath for uint256; address dv = 0xd7DBe51f9EBf734A5fd55C18002a063c6881d8b4; address sco = 0x387cbA805A719A1613488E489a8E7F0DE63aed14; address wmm = 0x9e0Ec64BEaa066E241c6309dE19B6e50AFf996c6; address jj = 0xdc977BE65dFc2e5464b86891Ed571Bea593Ca2B9; uint256 public constant IcecreamConePrice = 40000000000000000; // 0.04 ETH uint public constant maxIcecreamConePurchase = 20; uint256 public MAX_IcecreamCones = 8888; bool public saleIsActive = false; constructor() ERC721("TheIceCreamParlor", "CONE") { } function withdraw() external onlyOwner { uint balance = address(this).balance; payable(dv).transfer((balance*15)/100); payable(sco).transfer((balance*25)/100); payable(wmm).transfer((balance*45)/100); payable(jj).transfer((balance*15)/100); payable(msg.sender).transfer(address(this).balance); } function reserveIcecreamCones() public onlyOwner { uint supply= totalSupply(); uint i; for (i = 1; i < 89; i++) { _safeMint(msg.sender, supply + i); } } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function mintIcecreamCones(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint IceCream"); require(numberOfTokens <= maxIcecreamConePurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_IcecreamCones, "Purchase would exceed max supply of IcecreamCones"); require(IcecreamConePrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint i = 0; i < numberOfTokens; i++) { uint mintIndex = totalSupply() + 1; if (totalSupply() < MAX_IcecreamCones) { _safeMint(msg.sender, mintIndex); } } } }
44,802
29
// Get an identifiaction contract for a given dweller dweller The address of the dweller we're looking up /
function getDwellerId(address dweller) public view returns(address dwellerId)
function getDwellerId(address dweller) public view returns(address dwellerId)
18,870
79
// Crowdsale finish time
uint public finishTime;
uint public finishTime;
18,905
25
// Sending to NFT:
_sendToNFT(immediateOwner, to, parentId, destinationId, tokenId, data);
_sendToNFT(immediateOwner, to, parentId, destinationId, tokenId, data);
9,322
179
// Extract ERC721 tokens which were accidentally sent to the contract to a list of accounts.Warning: this function should be overriden for contracts which are supposed to hold ERC721 tokensso that the extraction is limited to only tokens sent accidentally. Reverts if the sender is not the contract owner. Reverts if `accounts`, `contracts` and `amounts` do not have the same length. Reverts if one of `contracts` is does not implement the ERC721 transferFrom function. Reverts if one of the ERC721 transfers fail for any reason. accounts the list of accounts to transfer the tokens to. contracts the list of ERC721 contract
function recoverERC721s( address[] calldata accounts, address[] calldata contracts, uint256[] calldata tokenIds
function recoverERC721s( address[] calldata accounts, address[] calldata contracts, uint256[] calldata tokenIds
11,001
87
// increase payment received amount
paymentReceived[_msgSender()] += paymentAmount;
paymentReceived[_msgSender()] += paymentAmount;
15,578
4
// Struct used for "robust" swaps that may have partial fills buying NFTs out of a pool swapInfo Swap info with pool and and Nfts being traded maxCost The maximum amount of tokens you are willing to pay for the Nfts total /
struct RobustSwap { IDittoPool pool; uint256[] nftIds; uint256 maxCost; bytes swapData; }
struct RobustSwap { IDittoPool pool; uint256[] nftIds; uint256 maxCost; bytes swapData; }
30,475