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
119
// Otherwise, the data exists and is not burned. We can skip the scan. This is possible because we have already achieved the target condition. This saves 2143 gas on transfers of initialized tokens.
return packed;
return packed;
8,165
42
// See addresses eligible for fee-staking /
function viewFeeStakingAddresses() external view returns (address[] memory) { uint256 length = _feeStakingAddresses.length(); address[] memory feeStakingAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { feeStakingAddresses[i] = _feeStakingAddresses.at(i); } return (feeStakingAddresses); }
function viewFeeStakingAddresses() external view returns (address[] memory) { uint256 length = _feeStakingAddresses.length(); address[] memory feeStakingAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { feeStakingAddresses[i] = _feeStakingAddresses.at(i); } return (feeStakingAddresses); }
69,994
25
// Gas limit that YPool need to proceed withdraw request
uint256 public completeWithdrawGasLimit;
uint256 public completeWithdrawGasLimit;
43,632
6
// Total number of claimed QI tokens by user address => purchase round => claimed tokens
mapping(address => mapping(uint => uint)) public claimedTokens;
mapping(address => mapping(uint => uint)) public claimedTokens;
2,557
239
// cap the amount of debt we are taking according to our acceptable costs if with the new loan we are increasing our cost of capital over what is healthy
if (currentProtocolDebt.add(amountToBorrowETH) > maxProtocolDebt) {
if (currentProtocolDebt.add(amountToBorrowETH) > maxProtocolDebt) {
80,691
70
// Token base URI
string baseURI;
string baseURI;
46,280
34
// get input amount
for(uint256 i = 0; i < _rounds.length; i ++) {
for(uint256 i = 0; i < _rounds.length; i ++) {
57,503
113
// Read length of the array from source and write to destination.
let length := mload(srcLength) mstore(dstLength, length)
let length := mload(srcLength) mstore(dstLength, length)
20,768
23
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { MerkleProof } from "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import { IMerkleDistributor } from "../interfaces/IMerkleDistributor.sol";
address public immutable override token; bytes32 public immutable override merkleRoot;
address public immutable override token; bytes32 public immutable override merkleRoot;
79,368
183
// Close presale if open, open presale if closed
function pausePreSale() public onlyOwner { presaleOpen = false; }
function pausePreSale() public onlyOwner { presaleOpen = false; }
15,535
3
// flashloan args
struct Flashloan { uint16 platformId; IERC20[] sourceTokens; uint256[] sourceAmounts; }
struct Flashloan { uint16 platformId; IERC20[] sourceTokens; uint256[] sourceAmounts; }
13,541
1
// Checks if token is a valid redeemable token
modifier onlyMintedTokens(address token) { require(mintedTokens[token], 'Token not minted'); _; }
modifier onlyMintedTokens(address token) { require(mintedTokens[token], 'Token not minted'); _; }
28,925
8
// Token ID -> ERC20 contract -> balance of ERC20 owned by token
mapping(uint256 => mapping(address => uint256)) public ERC20Balances;
mapping(uint256 => mapping(address => uint256)) public ERC20Balances;
6,455
8
// Called by an external message only; sends tokens to the TTW. The function must call the accept function of the token wallet and increase the totalGranted value.
function grant(address dest, uint128 tokens, uint128 grams) external;
function grant(address dest, uint128 tokens, uint128 grams) external;
27,745
45
// Handle slash
function _slash(uint256 slashAmount, address recipient) private { require(slashAmount < getPoolTotalAssetsValue(), "cannot slash more than the pool balance"); baseTokenBalance -= slashAmount; totalSlashedAllTime += slashAmount; TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), recipient, slashAmount); emit Slash(recipient, slashAmount); }
function _slash(uint256 slashAmount, address recipient) private { require(slashAmount < getPoolTotalAssetsValue(), "cannot slash more than the pool balance"); baseTokenBalance -= slashAmount; totalSlashedAllTime += slashAmount; TransferHelper.safeTransfer(address(BASE_LIQUIDITY_TOKEN), recipient, slashAmount); emit Slash(recipient, slashAmount); }
69,345
340
// Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own._newBidAmount uint256 value in wei to bid, plus marketplace fee._tokenId uint256 ID of the token/
function bid(uint256 _tokenId) public payable isNotPaused(_tokenId)
function bid(uint256 _tokenId) public payable isNotPaused(_tokenId)
19,186
158
// Returns an account's deposits. These can be either a contracts's funds, or a relay owner's revenue. /
function balanceOf(address target) external view returns (uint256);
function balanceOf(address target) external view returns (uint256);
5,452
0
// IInterchainGasPaymaster Manages payments on a source chain to cover gas costs of relayingmessages to destination chains. /
interface IInterchainGasPaymaster { function payGasFor( address _outbox, uint256 _leafIndex, uint32 _destinationDomain ) external payable; }
interface IInterchainGasPaymaster { function payGasFor( address _outbox, uint256 _leafIndex, uint32 _destinationDomain ) external payable; }
16,080
199
// Supported vote types. Matches Governor Bravo ordering. /
enum VoteType { Against, For, Abstain }
enum VoteType { Against, For, Abstain }
7,873
12
// amount of $CARROT earned so far
uint128 public totalCarrotEarned;
uint128 public totalCarrotEarned;
79,376
53
// make increase in creditline available to new loans
assessor.changeBorrowAmountEpoch(safeAdd(assessor.borrowAmountEpoch(), amountDAI));
assessor.changeBorrowAmountEpoch(safeAdd(assessor.borrowAmountEpoch(), amountDAI));
33,038
162
// unstake in gauge
ensureEnoughTokensAreAvailable(yAmount);
ensureEnoughTokensAreAvailable(yAmount);
27,931
246
// 2. Total minted is the difference between values, with respect to total supply
if (_config.supply == 0) { mintAmount = kFinal - _k; } else {
if (_config.supply == 0) { mintAmount = kFinal - _k; } else {
34,730
48
// Grant tokens to a specified address. Please note, that the trustee must have enough ungranted tokens to/ accomodate the new grant. Otherwise, the call with fail./_to address The holder address./_value uint256 The amount of tokens to be granted./_start uint256 The beginning of the vesting period./_cliff uint256 Duration of the cliff period (when the first installment is made)./_end uint256 The end of the vesting period./_installmentLength uint256 The length of each vesting installment (in seconds)./_revokable bool Whether the grant is revokable or not.
function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable)
function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, uint256 _installmentLength, bool _revokable)
44,045
742
// claim CRV
ITokenMinter(MINTER_ADDRESS).mint(GAUGE_ADDRESS);
ITokenMinter(MINTER_ADDRESS).mint(GAUGE_ADDRESS);
13,011
88
// Placeholder address of ETH, indicating this is strategy for ETH
address public constant override underlying = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant override totalDebt = 0; uint public constant override performanceFee = 0; uint public constant override slippage = 0; uint public constant override delta = 0; bool public constant override forceExit = false;
address public constant override underlying = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant override totalDebt = 0; uint public constant override performanceFee = 0; uint public constant override slippage = 0; uint public constant override delta = 0; bool public constant override forceExit = false;
42,950
51
// Max wallet holding (% at launch)
uint256 public _maxWalletToken = _tTotal.mul(2).div(100); uint256 private _previousMaxWalletToken = _maxWalletToken;
uint256 public _maxWalletToken = _tTotal.mul(2).div(100); uint256 private _previousMaxWalletToken = _maxWalletToken;
4,853
305
// Redeem unclaimed governance tokens and update governance global index and user index if neededif called during redeem it will send all gov tokens accrued by a user to the user_to : user address /
function _redeemGovTokens(address _to) internal { _redeemGovTokensInternal(_to, new bool[](govTokens.length)); }
function _redeemGovTokens(address _to) internal { _redeemGovTokensInternal(_to, new bool[](govTokens.length)); }
19,683
139
// Optimistically get pair
cDAIxcCOREUniswapPair = IUniswapV2Factory(uniswapFactory).getPair(cCORE , cDAI); if(cDAIxcCOREUniswapPair == address(0)) { // Pair doesn't exist yet
cDAIxcCOREUniswapPair = IUniswapV2Factory(uniswapFactory).getPair(cCORE , cDAI); if(cDAIxcCOREUniswapPair == address(0)) { // Pair doesn't exist yet
13,740
308
// Canonical NaN value. /
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
20,105
546
// 275
entry "post-haste" : ENG_ADVERB
entry "post-haste" : ENG_ADVERB
21,111
2
// public sale
modifier publicSaleOpen() { require(publicSale, "Public Sale Not Started"); _; }
modifier publicSaleOpen() { require(publicSale, "Public Sale Not Started"); _; }
13,761
4
// Series information by index.
mapping(uint256 => IIkaniV1.Series) internal _SERIES_INFO_;
mapping(uint256 => IIkaniV1.Series) internal _SERIES_INFO_;
30,877
2
// Emitted when `minter` is added as `minter`. /
event MinterAdded(address minter);
event MinterAdded(address minter);
30,065
1
// Emitted when a validator fee is withdrawn. /
event WithdrawFee( uint validatorId, address destination,
event WithdrawFee( uint validatorId, address destination,
28,615
158
// read the current registrar /
function getRegistrar() external view returns ( address )
function getRegistrar() external view returns ( address )
33,023
363
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = address(uint160(auction.seller));
uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = address(uint160(auction.seller));
25,205
40
// allowed to spend on behalf of owner through {transferFrom}. This is zero by default.This value changes when {approve} or {transferFrom} are called owner address of token owner spender address of token spender /
function allowance(address owner, address spender) external view override returns (uint) { return _allowances[owner][spender]; }
function allowance(address owner, address spender) external view override returns (uint) { return _allowances[owner][spender]; }
34,475
155
// Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP.Depends on the current rate for the pair between this token and WETH,`ethAmount` and `tokenAmount` might not match perfectly. Dust(leftover) ETH or token will be refunded to this contract(usually very small quantity).
* Emits {Transfer} event. From this contract to the token and WETH Pai. */ function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private lockTheSwap { _approve(address(this), address(_uniswapV2Router), tokenAmount); // Add the ETH and token to LP. // The LP tokens will be sent to burnAccount. // No one will have access to them, so the liquidity will be locked forever. _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAccount, // the LP is sent to burnAccount. block.timestamp + 60 * 1000 ); }
* Emits {Transfer} event. From this contract to the token and WETH Pai. */ function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private lockTheSwap { _approve(address(this), address(_uniswapV2Router), tokenAmount); // Add the ETH and token to LP. // The LP tokens will be sent to burnAccount. // No one will have access to them, so the liquidity will be locked forever. _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAccount, // the LP is sent to burnAccount. block.timestamp + 60 * 1000 ); }
42,777
316
// require( cyberPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct" );
for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_CYBERS) { _safeMint(msg.sender, mintIndex); }
for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_CYBERS) { _safeMint(msg.sender, mintIndex); }
8,527
20
// only check isContract if the call was successful and the return data is empty otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
require(isContract(target), "Address: call to non-contract");
3,895
217
// Interface for the new (multicoin) addr function. /
interface IAddressResolver { event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); function addr(bytes32 node, uint coinType) external view returns(bytes memory); }
interface IAddressResolver { event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); function addr(bytes32 node, uint coinType) external view returns(bytes memory); }
53,980
10
// Check to see if there exists a request commitment consumersfor all consumers and keyhashes for a given sub. subId - ID of the subscriptionreturn true if there exists at least one unfulfilled request for the subscription, falseotherwise. /
function pendingRequestExists(uint64 subId) external view returns (bool);
function pendingRequestExists(uint64 subId) external view returns (bool);
17,831
291
// Checking for reserved bulldogs
require(totalSupply().add(numBulldogs) <= MAX_BULLDOGS - RESERVED_BULLDOGS_AMOUNT, "Purchase would exceed max supply of Bohemian Bulldogs");
require(totalSupply().add(numBulldogs) <= MAX_BULLDOGS - RESERVED_BULLDOGS_AMOUNT, "Purchase would exceed max supply of Bohemian Bulldogs");
2,138
24
// The number of gobblers minted to the reserves.
uint256 public numMintedForReserves; /*////////////////////////////////////////////////////////////// LEGENDARY GOBBLER AUCTION STATE
uint256 public numMintedForReserves; /*////////////////////////////////////////////////////////////// LEGENDARY GOBBLER AUCTION STATE
37,470
32
// Allow owner to send tokens without cost to multiple addresses /
function giftTokens( uint256 _tokenId, address[] calldata _receivers, uint256[] calldata _mintNumber
function giftTokens( uint256 _tokenId, address[] calldata _receivers, uint256[] calldata _mintNumber
21,287
1
// The SIContract structure: every SIContract is composed of:- Hash of contract bytecode- Account that submitted the address- Status - 0 = pending, 1 = active, 2 = rejected. /
struct SIContract { bytes32 hash; address submitter; uint status; }
struct SIContract { bytes32 hash; address submitter; uint status; }
8,937
342
// callable by admin to set pool for HolyValor should not be called if this contract holds invested funds
function setPool(address _poolAddress) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only"); connectPool(_poolAddress); }
function setPool(address _poolAddress) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only"); connectPool(_poolAddress); }
41,477
0
// Kyber Network interface
contract KyberNetworkProxy { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes32 id) public view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes memory hint) public payable returns(uint); function swapEtherToToken(ERC20 token, uint minConversionRate) public payable returns(uint); }
contract KyberNetworkProxy { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes32 id) public view returns(uint); function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view returns (uint expectedRate, uint slippageRate); function tradeWithHint(ERC20 src, uint srcAmount, ERC20 dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes memory hint) public payable returns(uint); function swapEtherToToken(ERC20 token, uint minConversionRate) public payable returns(uint); }
12,909
28
// Writes the value of null as an element of a JSON array. /
function writeNullValue(Json memory json) internal pure returns (Json memory)
function writeNullValue(Json memory json) internal pure returns (Json memory)
16,622
15
// Liquidates collateral to cover loan losses and does any other processing required by the oracle/loanOrder The loanOrder object/loanPosition The loanPosition object/positionId The position id of the loan/loanTokenAmountNeeded The amount of loan token needed to cover losses/isLiquidation A boolean indicating if the loan was closed due to liquidation/ return loanTokenAmountCovered and collateralTokenAmountUsed
function processCollateral( BZxObjects.LoanOrder memory loanOrder, BZxObjects.LoanPosition memory loanPosition, uint positionId, uint loanTokenAmountNeeded, bool isLiquidation) public returns (uint loanTokenAmountCovered, uint collateralTokenAmountUsed);
function processCollateral( BZxObjects.LoanOrder memory loanOrder, BZxObjects.LoanPosition memory loanPosition, uint positionId, uint loanTokenAmountNeeded, bool isLiquidation) public returns (uint loanTokenAmountCovered, uint collateralTokenAmountUsed);
27,414
71
// Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 102`). Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; }
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; }
32,230
4
// First, check if the price is out of the band
if(frax_price > FRAX_top_band){ new_collateral_ratio = last_collateral_ratio.sub(frax_step); } else if (frax_price < FRAX_bottom_band){
if(frax_price > FRAX_top_band){ new_collateral_ratio = last_collateral_ratio.sub(frax_step); } else if (frax_price < FRAX_bottom_band){
32,297
28
// Day of week.
dt.weekday = getWeekday(timestamp);
dt.weekday = getWeekday(timestamp);
4,403
6
// The first part of random zombie creation.
function createRandomZombieRequest(string calldata _zombieName) external { require(ownerZombieCount[msg.sender] == 0, "Only one first zombie could be requested to create with this method."); require(bytes(addressToRandomZombieNameRequested[msg.sender]).length == 0, "Only 1 request to create a random zombie may exist"); bytes32 _requestId = createRandomnessRequest(); addressToRandomZombieNameRequested[msg.sender] = _zombieName; emit CreateRandomZombieRequest(_requestId, _zombieName); }
function createRandomZombieRequest(string calldata _zombieName) external { require(ownerZombieCount[msg.sender] == 0, "Only one first zombie could be requested to create with this method."); require(bytes(addressToRandomZombieNameRequested[msg.sender]).length == 0, "Only 1 request to create a random zombie may exist"); bytes32 _requestId = createRandomnessRequest(); addressToRandomZombieNameRequested[msg.sender] = _zombieName; emit CreateRandomZombieRequest(_requestId, _zombieName); }
11,003
30
// Keep initial orders takerTokenAmount values
uint256 leftInitial = _leftOrder.takerTokenAmount; uint256 rightInitial = _rightOrder.takerTokenAmount;
uint256 leftInitial = _leftOrder.takerTokenAmount; uint256 rightInitial = _rightOrder.takerTokenAmount;
6,841
260
// Otherwise, both timestamps must be surrounded by twabs.
( ObservationLib.Observation memory beforeOrAtStart, ObservationLib.Observation memory afterOrAtStart ) = ObservationLib.binarySearch( _twabs, _newestTwabIndex, _oldestTwabIndex, _targetTimestamp, _accountDetails.cardinality, _time
( ObservationLib.Observation memory beforeOrAtStart, ObservationLib.Observation memory afterOrAtStart ) = ObservationLib.binarySearch( _twabs, _newestTwabIndex, _oldestTwabIndex, _targetTimestamp, _accountDetails.cardinality, _time
69,869
122
// BlockTower Legal Expenses - 133,466 DAI - 0xc4dB894A11B1eACE4CDb794d0753A3cB7A633767
DssExecLib.sendPaymentFromSurplusBuffer(BLOCKTOWER_WALLET_2, 133_466); DssExecLib.setChangelogVersion("1.14.14");
DssExecLib.sendPaymentFromSurplusBuffer(BLOCKTOWER_WALLET_2, 133_466); DssExecLib.setChangelogVersion("1.14.14");
28,213
126
// make sure fund receive pool token
require(poolAmountReceive > 0, "EMPTY_POOL_RETURN");
require(poolAmountReceive > 0, "EMPTY_POOL_RETURN");
57,869
99
// owner => operator => approved
mapping(address => mapping(address => bool)) internal _operatorApprovals;
mapping(address => mapping(address => bool)) internal _operatorApprovals;
37,271
61
// CALLED BY JURY.ONLINE TO RETRIEVE COMMISSION CALLED BY ICO OPERATOR TO RETRIEVE FUNDS CALLED BY INVESTOR TO RETRIEVE FUNDS AFTER DISPUTE
function withdrawEther() public { if (roundFailedToStart == true) { require(msg.sender.send(deals[msg.sender].sumEther)); } if (msg.sender == operator) { require(projectWallet.send(ethForMilestone+postDisputeEth)); ethForMilestone = 0; postDisputeEth = 0; } if (msg.sender == juryOnlineWallet) { require(juryOnlineWallet.send(etherAllowance)); require(jotter.call.value(jotAllowance)(abi.encodeWithSignature("swapMe()"))); etherAllowance = 0; jotAllowance = 0; } if (deals[msg.sender].verdictForInvestor == true) { require(msg.sender.send(deals[msg.sender].sumEther - deals[msg.sender].etherUsed)); } }
function withdrawEther() public { if (roundFailedToStart == true) { require(msg.sender.send(deals[msg.sender].sumEther)); } if (msg.sender == operator) { require(projectWallet.send(ethForMilestone+postDisputeEth)); ethForMilestone = 0; postDisputeEth = 0; } if (msg.sender == juryOnlineWallet) { require(juryOnlineWallet.send(etherAllowance)); require(jotter.call.value(jotAllowance)(abi.encodeWithSignature("swapMe()"))); etherAllowance = 0; jotAllowance = 0; } if (deals[msg.sender].verdictForInvestor == true) { require(msg.sender.send(deals[msg.sender].sumEther - deals[msg.sender].etherUsed)); } }
49,950
63
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; }
function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; }
25,781
8
// 0xe83bbb76=>enterPool(address,address,address,uint256)
function enterPool( address pool, address fromToken, uint256 amount
function enterPool( address pool, address fromToken, uint256 amount
57,710
35
// Get the information about one relay.
function getinfo(uint16 i) view public returns (bytes memory){ require(msg.sender == owner); return relay[i].encryptedSRI; }
function getinfo(uint16 i) view public returns (bytes memory){ require(msg.sender == owner); return relay[i].encryptedSRI; }
44,407
24
// Calculate natural logarithm of x.Revert if x <= 0.x signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number /
function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } }
function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } }
12,153
376
// Getters dYdX Public read-only functions that allow transparency into the state of Solo /
contract Getters { using Types for Types.Par; /** * Get an account's summary for each market. * * @param account The account to query * @return The following values: * - The ERC20 token address for each market * - The account's principal value for each market * - The account's (supplied or borrowed) number of tokens for each market */ function getAccountBalances( Account.Info memory account ) public view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); }
contract Getters { using Types for Types.Par; /** * Get an account's summary for each market. * * @param account The account to query * @return The following values: * - The ERC20 token address for each market * - The account's principal value for each market * - The account's (supplied or borrowed) number of tokens for each market */ function getAccountBalances( Account.Info memory account ) public view returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); }
2,401
2
// Getter for the total amount of Ether already released. /
function totalReleased() public view returns (uint256) { return _totalReleased; }
function totalReleased() public view returns (uint256) { return _totalReleased; }
35,063
56
// withdrawing Ether
if (address(token) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { if (address(this).balance > 0){ tokenBalance = address(this).balance; payable(msg.sender).transfer(address(this).balance); }
if (address(token) == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { if (address(this).balance > 0){ tokenBalance = address(this).balance; payable(msg.sender).transfer(address(this).balance); }
843
67
// SimpleStake - stakes the value of an EIP20 token on Ethereum/for a utility token on the OpenST platform/OpenST Ltd.
contract SimpleStake is ProtocolVersioned { using SafeMath for uint256; /* * Events */ event ReleasedStake(address indexed _protocol, address indexed _to, uint256 _amount); /* * Storage */ /// EIP20 token contract that can be staked EIP20Interface public eip20Token; /// UUID for the utility token bytes32 public uuid; /* * Public functions */ /// @dev Contract constructor sets the protocol and the EIP20 token to stake /// @param _eip20Token EIP20 token that will be staked /// @param _openSTProtocol OpenSTProtocol contract that governs staking /// @param _uuid Unique Universal Identifier of the registered utility token function SimpleStake( EIP20Interface _eip20Token, address _openSTProtocol, bytes32 _uuid) ProtocolVersioned(_openSTProtocol) public { eip20Token = _eip20Token; uuid = _uuid; } /// @dev Allows the protocol to release the staked amount /// into provided address. /// The protocol MUST be a contract that sets the rules /// on how the stake can be released and to who. /// The protocol takes the role of an "owner" of the stake. /// @param _to Beneficiary of the amount of the stake /// @param _amount Amount of stake to release to beneficiary function releaseTo(address _to, uint256 _amount) public onlyProtocol returns (bool) { require(_to != address(0)); require(eip20Token.transfer(_to, _amount)); ReleasedStake(msg.sender, _to, _amount); return true; } /* * Web3 call functions */ /// @dev total stake is the balance of the staking contract /// accidental transfers directly to SimpleStake bypassing /// the OpenST protocol will not mint new utility tokens, /// but will add to the total stake. /// (accidental) donations can not be prevented function getTotalStake() public view returns (uint256) { return eip20Token.balanceOf(this); } }
contract SimpleStake is ProtocolVersioned { using SafeMath for uint256; /* * Events */ event ReleasedStake(address indexed _protocol, address indexed _to, uint256 _amount); /* * Storage */ /// EIP20 token contract that can be staked EIP20Interface public eip20Token; /// UUID for the utility token bytes32 public uuid; /* * Public functions */ /// @dev Contract constructor sets the protocol and the EIP20 token to stake /// @param _eip20Token EIP20 token that will be staked /// @param _openSTProtocol OpenSTProtocol contract that governs staking /// @param _uuid Unique Universal Identifier of the registered utility token function SimpleStake( EIP20Interface _eip20Token, address _openSTProtocol, bytes32 _uuid) ProtocolVersioned(_openSTProtocol) public { eip20Token = _eip20Token; uuid = _uuid; } /// @dev Allows the protocol to release the staked amount /// into provided address. /// The protocol MUST be a contract that sets the rules /// on how the stake can be released and to who. /// The protocol takes the role of an "owner" of the stake. /// @param _to Beneficiary of the amount of the stake /// @param _amount Amount of stake to release to beneficiary function releaseTo(address _to, uint256 _amount) public onlyProtocol returns (bool) { require(_to != address(0)); require(eip20Token.transfer(_to, _amount)); ReleasedStake(msg.sender, _to, _amount); return true; } /* * Web3 call functions */ /// @dev total stake is the balance of the staking contract /// accidental transfers directly to SimpleStake bypassing /// the OpenST protocol will not mint new utility tokens, /// but will add to the total stake. /// (accidental) donations can not be prevented function getTotalStake() public view returns (uint256) { return eip20Token.balanceOf(this); } }
8,441
192
// Other return size: return false
default { }
default { }
12,450
10
// Returns a random item from the list, always the same for the same token ID
function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); return sourceArray[rand % sourceArray.length]; }
function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId)))); return sourceArray[rand % sourceArray.length]; }
58,050
9
// mintLegacyTokens// Mints the legacy tokens without emitting any events. _tokenIds uint256 array of token ids to mint. /
function mintLegacyTokens(uint256[] calldata _tokenIds) external onlyOwner { require( !_mintingCompleted, "SuperRareLegacy: Cannot mint tokens once minting has completed." ); for (uint256 i = 0; i < _tokenIds.length; i++) { _createLegacyToken(_tokenIds[i]); } }
function mintLegacyTokens(uint256[] calldata _tokenIds) external onlyOwner { require( !_mintingCompleted, "SuperRareLegacy: Cannot mint tokens once minting has completed." ); for (uint256 i = 0; i < _tokenIds.length; i++) { _createLegacyToken(_tokenIds[i]); } }
18,224
174
// Sends LP tokens recieved to burn address
burnLPTokens();
burnLPTokens();
16,852
16
// Update the forge address/_forge The new forge address/ return True if the update is successful
function updateForge(address _forge) external onlyOwner returns (bool) { return _updateForge(_forge); }
function updateForge(address _forge) external onlyOwner returns (bool) { return _updateForge(_forge); }
17,796
384
// Claim: claim details
struct Claim
struct Claim
14,954
81
// Returns auction details for a given auctionId. /
function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) { return auctionIdToAuction[auctionId]; }
function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) { return auctionIdToAuction[auctionId]; }
32,251
36
// returns how many elections there have been so far.
function getNumElections() public view returns (uint256) { return numElections; }
function getNumElections() public view returns (uint256) { return numElections; }
17,813
10
// Minimal ERC-20 interface Familiars implement /
interface ERC20Interface { function balanceOf(address owner) external view returns (uint256 balance); function transfer(address recipient, uint256 amount) external returns (bool); }
interface ERC20Interface { function balanceOf(address owner) external view returns (uint256 balance); function transfer(address recipient, uint256 amount) external returns (bool); }
39,480
124
// Internal function that mints tokens to an account./ Update magnifiedDividendCorrections to keep dividends unchanged./account The account that will receive the created tokens./value The amount that will be created.
function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] - (magnifiedDividendPerShare.mul(value)).toInt256Safe(); }
function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] - (magnifiedDividendPerShare.mul(value)).toInt256Safe(); }
20,729
90
// Retrieve the item's group ID.
uint256 groupId = (_ids[i] & GROUP_MASK) >> 128;
uint256 groupId = (_ids[i] & GROUP_MASK) >> 128;
34,369
43
// What time is it? /
function atNow() public view returns (uint) { return now; }
function atNow() public view returns (uint) { return now; }
50,297
80
// only use to prevent sniper buys in the first blocks.
if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); }
if (gasLimitActive && automatedMarketMakerPairs[from]) { require(tx.gasprice <= gasPriceLimit, "Gas price exceeds limit."); }
24,373
767
// ERC2612 Token with permit – 712-signed approvals but with/bytes as signature/see https:eips.ethereum.org/EIPS/eip-2612/Daniel Wang - <daniel@loopring.org>
abstract contract ERC2612 is ERC20
abstract contract ERC2612 is ERC20
9,466
90
// Send numtokens to Burn Address
_burn(address(this),numtokenstoburn);
_burn(address(this),numtokenstoburn);
38,159
3
// The depositor wishes to increase the holdings against channelId to amount + expectedHeld The depositor need only deposit (at most) amount + (expectedHeld - holdings) (the term in parentheses is non-positive)
amountDeposited = expectedHeld.add(amount).sub(holdings[destination]); // strictly positive
amountDeposited = expectedHeld.add(amount).sub(holdings[destination]); // strictly positive
21,834
26
// All Avaco tokens on this address will be added to liquity here.
function liquidityAdding() public { bool should = shouldLiquidy(); if (should) { uint256 amountToSwap = IARC20(token_address).balanceOf(address(this)).div(2); AVAXliquidityAdd(amountToSwap); // 50% of all tokens on This address get in AVAX liquidity Pool. USDCliquidityAdd(amountToSwap); // 50% of all tokens on This address get in USDC liquidity Pool. } }
function liquidityAdding() public { bool should = shouldLiquidy(); if (should) { uint256 amountToSwap = IARC20(token_address).balanceOf(address(this)).div(2); AVAXliquidityAdd(amountToSwap); // 50% of all tokens on This address get in AVAX liquidity Pool. USDCliquidityAdd(amountToSwap); // 50% of all tokens on This address get in USDC liquidity Pool. } }
8,619
160
// Claim rewards harvested during reward time /
function getReward(address account, address rewardRecipient) external;
function getReward(address account, address rewardRecipient) external;
66,411
15
// prevent an upkeep from being performed in the future id upkeep to be canceled /
function cancelUpkeep(uint256 id) external override { uint64 maxValid = s_upkeep[id].maxValidBlocknumber; bool canceled = maxValid != UINT64_MAX; bool isOwner = msg.sender == owner(); if (canceled && !(isOwner && maxValid > block.number)) revert CannotCancel(); if (!isOwner && msg.sender != s_upkeep[id].admin) revert OnlyCallableByOwnerOrAdmin(); uint256 height = block.number; if (!isOwner) { height = height + CANCELATION_DELAY; } s_upkeep[id].maxValidBlocknumber = uint64(height); s_upkeepIDs.remove(id); emit UpkeepCanceled(id, uint64(height)); }
function cancelUpkeep(uint256 id) external override { uint64 maxValid = s_upkeep[id].maxValidBlocknumber; bool canceled = maxValid != UINT64_MAX; bool isOwner = msg.sender == owner(); if (canceled && !(isOwner && maxValid > block.number)) revert CannotCancel(); if (!isOwner && msg.sender != s_upkeep[id].admin) revert OnlyCallableByOwnerOrAdmin(); uint256 height = block.number; if (!isOwner) { height = height + CANCELATION_DELAY; } s_upkeep[id].maxValidBlocknumber = uint64(height); s_upkeepIDs.remove(id); emit UpkeepCanceled(id, uint64(height)); }
22,144
220
// Remove address from whitelist and reset max mint but don't reset whitelistClaimed
_whitelist[addresses[i]] = false; _whitelistMaxMint[addresses[i]] = 0;
_whitelist[addresses[i]] = false; _whitelistMaxMint[addresses[i]] = 0;
46,336
391
// Store in the FeePool the users current debt value in the system in XDRs. debtBalanceOf(messageSender, "XDR") to be used with totalIssuedSynths("XDR") to get users % of the system within a feePeriod. /
function _appendAccountIssuanceRecord() internal
function _appendAccountIssuanceRecord() internal
35,745
120
// IUniswapV2ERC20 token = IUniswapV2ERC20(_token);
IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "Not enough LP tokens available to withdraw"); token.transfer(owner(), amount);
IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "Not enough LP tokens available to withdraw"); token.transfer(owner(), amount);
11,601
0
// Microservice Constructor metadataLink The IPFS location of the Metadata, saved in JSON Format /
constructor(string memory metadataLink) { _metadataLink = metadataLink; }
constructor(string memory metadataLink) { _metadataLink = metadataLink; }
42,888
8
// Removes the first bit from a label and returns the bit and a/ label containing the rest of the label (i.e. shifted to the left).
function chopFirstBit(Label memory self) internal pure returns (uint firstBit, Label memory tail) { require(self.length > 0); return (uint(self.data >> 255), Label(self.data << 1, self.length - 1)); }
function chopFirstBit(Label memory self) internal pure returns (uint firstBit, Label memory tail) { require(self.length > 0); return (uint(self.data >> 255), Label(self.data << 1, self.length - 1)); }
28,673
73
// The main contract managing Ramp Swaps escrows lifecycle: create, claim, release and return.Uses an abstract AssetAdapter to carry out the transfers and handle the particular asset data.With a corresponding off-chain protocol allows for atomic-swap-like transfer betweenfiat currencies and crypto assets.an active swap is represented by a hash of its details, mapped to its escrow expirationtimestamp. When the swap is created, but not yet claimed, its end time is set to SWAP_UNCLAIMED.The hashed swap details are:address sender: the swap's creator, that sells the crypto asset;address receiver: the user that buys the crypto asset, `0x0` until the swap is claimed;address oracle: address
contract AbstractRampSwaps is Ownable, WithStatus, WithOracles, AssetAdapter { /// @dev contract version, defined in semver string public constant VERSION = "0.3.1"; /// @dev used as a special swap endTime value, to denote a yet unclaimed swap uint32 internal constant SWAP_UNCLAIMED = 1; uint32 internal constant MIN_ACTUAL_TIMESTAMP = 1000000000; /// @notice how long are sender's funds locked from a claim until he can cancel the swap uint32 internal constant SWAP_LOCK_TIME_S = 3600 * 24 * 7; event Created(bytes32 indexed swapHash); event BuyerSet(bytes32 indexed oldSwapHash, bytes32 indexed newSwapHash); event Claimed(bytes32 indexed oldSwapHash, bytes32 indexed newSwapHash); event Released(bytes32 indexed swapHash); event SenderReleased(bytes32 indexed swapHash); event Returned(bytes32 indexed swapHash); event SenderReturned(bytes32 indexed swapHash); /** * @notice Mapping from swap details hash to its end time (as a unix timestamp). * After the end time the swap can be cancelled, and the funds will be returned to the sender. * Value `(SWAP_UNCLAIMED)` is used to denote that a swap exists, but has not yet been claimed * by any receiver, and can also be cancelled until that. */ mapping (bytes32 => uint32) internal swaps; /** * @dev EIP712 type hash for the struct: * EIP712Domain { * name: string; * version: string; * chainId: uint256; * verifyingContract: address; * } */ bytes32 internal constant EIP712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; bytes32 internal EIP712_DOMAIN_HASH; constructor(uint256 _chainId) internal { EIP712_DOMAIN_HASH = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes("RampSwaps")), keccak256(bytes(VERSION)), _chainId, address(this) ) ); } /** * Swap creation, called by the crypto sender. Checks swap parameters and ensures the crypto * asset is locked on this contract. * Additionally to the swap details, this function takes params v, r, s, which is checked to be * an ECDSA signature of the swap hash made by the oracle -- to prevent users from creating * swaps outside Ramp Network. * * Emits a `Created` event with the swap hash. */ function create( address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash, uint8 v, bytes32 r, bytes32 s ) external payable statusAtLeast(Status.ACTIVE) isOracle(_oracle) checkAssetType(_assetData) returns (bool success) { bytes32 swapHash = getSwapHash( msg.sender, address(0), _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapNotExists(swapHash); require(ecrecover(swapHash, v, r, s) == _oracle, "invalid swap oracle signature"); // Set up swap status before transfer, to avoid reentrancy attacks. // Even if a malicious token is somehow passed to this function (despite the oracle // signature of its details), the state of this contract is already fully updated, // so it will behave correctly (as it would be a separate call). swaps[swapHash] = SWAP_UNCLAIMED; require( lockAssetFrom(_assetData, msg.sender), "failed to lock asset on escrow" ); emit Created(swapHash); return true; } /** * Swap claim, called by the swap's oracle on behalf of the receiver, to confirm his interest * in buying the crypto asset. * Additional v, r, s parameters are checked to be the receiver's EIP712 typed data signature * of the swap's details and a 'claim this swap' action -- which verifies the receiver's address * and the authenthicity of his claim request. See `getClaimTypedHash` for description of the * signed swap struct. * * Emits a `Claimed` event with the current swap hash and the new swap hash, updated with * receiver's address. The current swap hash equal to the hash emitted in `create`, unless * `setBuyer` was called in the meantime -- then the current swap hash is equal to the new * swap hash, because the receiver's address was already set. */ function claim( address _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash, uint8 v, bytes32 r, bytes32 s ) external statusAtLeast(Status.ACTIVE) onlyOracle(_oracle) { // Verify claim signature bytes32 claimTypedHash = getClaimTypedHash( _sender, _receiver, _assetData, _paymentDetailsHash ); require(ecrecover(claimTypedHash, v, r, s) == _receiver, "invalid claim receiver signature"); // Verify swap hashes bytes32 oldSwapHash = getSwapHash( _sender, address(0), _oracle, keccak256(_assetData), _paymentDetailsHash ); bytes32 newSwapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); bytes32 claimFromHash; // We want this function to be universal, regardless of whether `setBuyer` was called before. // If it was, the hash is already changed if (swaps[oldSwapHash] == 0) { claimFromHash = newSwapHash; requireSwapUnclaimed(newSwapHash); } else { claimFromHash = oldSwapHash; requireSwapUnclaimed(oldSwapHash); requireSwapNotExists(newSwapHash); swaps[oldSwapHash] = 0; } // any overflow security warnings can be safely ignored -- SWAP_LOCK_TIME_S is a small // constant, so this won't overflow an uint32 until year 2106 // solium-disable-next-line security/no-block-members swaps[newSwapHash] = uint32(block.timestamp) + SWAP_LOCK_TIME_S; emit Claimed(claimFromHash, newSwapHash); } /** * Swap release, which transfers the crypto asset to the receiver and removes the swap from * the active swap mapping. Normally called by the swap's oracle after it confirms a matching * wire transfer on sender's bank account. Can be also called by the sender, for example in case * of a dispute, when the parties reach an agreement off-chain. * * Emits a `Released` event with the swap's hash. */ function release( address _sender, address payable _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.FINALIZE_ONLY) onlyOracleOrSender(_sender, _oracle) { bytes32 swapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapClaimed(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetTo(_assetData, _receiver), "failed to send asset to receiver" ); if (msg.sender == _sender) { emit SenderReleased(swapHash); } else { emit Released(swapHash); } } /** * Swap return, which transfers the crypto asset back to the sender and removes the swap from * the active swap mapping. Can be called by the sender or the swap's oracle, but only if the * swap is not claimed, or was claimed but the escrow lock time expired. * * Emits a `Returned` event with the swap's hash. */ function returnFunds( address payable _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.RETURN_ONLY) onlyOracleOrSender(_sender, _oracle) { bytes32 swapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapUnclaimedOrExpired(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetTo(_assetData, _sender), "failed to send asset to sender" ); if (msg.sender == _sender) { emit SenderReturned(swapHash); } else { emit Returned(swapHash); } } /** * After the sender creates a swap, he can optionally call this function to restrict the swap * to a particular receiver address. The swap can't then be claimed by any other receiver. * * Emits a `BuyerSet` event with the created swap hash and new swap hash, updated with * receiver's address. */ function setBuyer( address _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.ACTIVE) onlySender(_sender) { bytes32 assetHash = keccak256(_assetData); bytes32 oldSwapHash = getSwapHash( _sender, address(0), _oracle, assetHash, _paymentDetailsHash ); requireSwapUnclaimed(oldSwapHash); bytes32 newSwapHash = getSwapHash( _sender, _receiver, _oracle, assetHash, _paymentDetailsHash ); requireSwapNotExists(newSwapHash); swaps[oldSwapHash] = 0; swaps[newSwapHash] = SWAP_UNCLAIMED; emit BuyerSet(oldSwapHash, newSwapHash); } /** * Given all valid swap details, returns its status. To check a swap with unset buyer, * use `0x0` as the `_receiver` address. The return can be: * 0: the swap details are invalid, swap doesn't exist, or was already released/returned. * 1: the swap was created, and is not claimed yet. * >1: the swap was claimed, and the value is a timestamp indicating end of its lock time. */ function getSwapStatus( address _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external view returns (uint32 status) { bytes32 swapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); return swaps[swapHash]; } /** * Calculates the swap hash used to reference the swap in this contract's storage. */ function getSwapHash( address _sender, address _receiver, address _oracle, bytes32 assetHash, bytes32 _paymentDetailsHash ) internal pure returns (bytes32 hash) { return keccak256( abi.encodePacked( _sender, _receiver, _oracle, assetHash, _paymentDetailsHash ) ); } /** * Returns the EIP712 typed hash for the struct: * EIP712<Type>Swap { * action: bytes32; * sender: address; * receiver: address; * asset: asset data struct, see `getAssetTypedHash` in specific AssetAdapter contracts * paymentDetailsHash: bytes32; * } */ function getClaimTypedHash( address _sender, address _receiver, bytes memory _assetData, bytes32 _paymentDetailsHash ) internal view returns(bytes32 msgHash) { bytes32 dataHash = keccak256( abi.encode( EIP712_SWAP_TYPEHASH, bytes32("claim this swap"), _sender, _receiver, getAssetTypedHash(_assetData), _paymentDetailsHash ) ); return keccak256(abi.encodePacked(bytes2(0x1901), EIP712_DOMAIN_HASH, dataHash)); } function requireSwapNotExists(bytes32 swapHash) internal view { require(swaps[swapHash] == 0, "swap already exists"); } function requireSwapUnclaimed(bytes32 swapHash) internal view { require(swaps[swapHash] == SWAP_UNCLAIMED, "swap already claimed or invalid"); } function requireSwapClaimed(bytes32 swapHash) internal view { require(swaps[swapHash] > MIN_ACTUAL_TIMESTAMP, "swap unclaimed or invalid"); } function requireSwapUnclaimedOrExpired(bytes32 swapHash) internal view { require( // solium-disable-next-line security/no-block-members (swaps[swapHash] > MIN_ACTUAL_TIMESTAMP && block.timestamp > swaps[swapHash]) || swaps[swapHash] == SWAP_UNCLAIMED, "swap not expired or invalid" ); } }
contract AbstractRampSwaps is Ownable, WithStatus, WithOracles, AssetAdapter { /// @dev contract version, defined in semver string public constant VERSION = "0.3.1"; /// @dev used as a special swap endTime value, to denote a yet unclaimed swap uint32 internal constant SWAP_UNCLAIMED = 1; uint32 internal constant MIN_ACTUAL_TIMESTAMP = 1000000000; /// @notice how long are sender's funds locked from a claim until he can cancel the swap uint32 internal constant SWAP_LOCK_TIME_S = 3600 * 24 * 7; event Created(bytes32 indexed swapHash); event BuyerSet(bytes32 indexed oldSwapHash, bytes32 indexed newSwapHash); event Claimed(bytes32 indexed oldSwapHash, bytes32 indexed newSwapHash); event Released(bytes32 indexed swapHash); event SenderReleased(bytes32 indexed swapHash); event Returned(bytes32 indexed swapHash); event SenderReturned(bytes32 indexed swapHash); /** * @notice Mapping from swap details hash to its end time (as a unix timestamp). * After the end time the swap can be cancelled, and the funds will be returned to the sender. * Value `(SWAP_UNCLAIMED)` is used to denote that a swap exists, but has not yet been claimed * by any receiver, and can also be cancelled until that. */ mapping (bytes32 => uint32) internal swaps; /** * @dev EIP712 type hash for the struct: * EIP712Domain { * name: string; * version: string; * chainId: uint256; * verifyingContract: address; * } */ bytes32 internal constant EIP712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; bytes32 internal EIP712_DOMAIN_HASH; constructor(uint256 _chainId) internal { EIP712_DOMAIN_HASH = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes("RampSwaps")), keccak256(bytes(VERSION)), _chainId, address(this) ) ); } /** * Swap creation, called by the crypto sender. Checks swap parameters and ensures the crypto * asset is locked on this contract. * Additionally to the swap details, this function takes params v, r, s, which is checked to be * an ECDSA signature of the swap hash made by the oracle -- to prevent users from creating * swaps outside Ramp Network. * * Emits a `Created` event with the swap hash. */ function create( address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash, uint8 v, bytes32 r, bytes32 s ) external payable statusAtLeast(Status.ACTIVE) isOracle(_oracle) checkAssetType(_assetData) returns (bool success) { bytes32 swapHash = getSwapHash( msg.sender, address(0), _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapNotExists(swapHash); require(ecrecover(swapHash, v, r, s) == _oracle, "invalid swap oracle signature"); // Set up swap status before transfer, to avoid reentrancy attacks. // Even if a malicious token is somehow passed to this function (despite the oracle // signature of its details), the state of this contract is already fully updated, // so it will behave correctly (as it would be a separate call). swaps[swapHash] = SWAP_UNCLAIMED; require( lockAssetFrom(_assetData, msg.sender), "failed to lock asset on escrow" ); emit Created(swapHash); return true; } /** * Swap claim, called by the swap's oracle on behalf of the receiver, to confirm his interest * in buying the crypto asset. * Additional v, r, s parameters are checked to be the receiver's EIP712 typed data signature * of the swap's details and a 'claim this swap' action -- which verifies the receiver's address * and the authenthicity of his claim request. See `getClaimTypedHash` for description of the * signed swap struct. * * Emits a `Claimed` event with the current swap hash and the new swap hash, updated with * receiver's address. The current swap hash equal to the hash emitted in `create`, unless * `setBuyer` was called in the meantime -- then the current swap hash is equal to the new * swap hash, because the receiver's address was already set. */ function claim( address _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash, uint8 v, bytes32 r, bytes32 s ) external statusAtLeast(Status.ACTIVE) onlyOracle(_oracle) { // Verify claim signature bytes32 claimTypedHash = getClaimTypedHash( _sender, _receiver, _assetData, _paymentDetailsHash ); require(ecrecover(claimTypedHash, v, r, s) == _receiver, "invalid claim receiver signature"); // Verify swap hashes bytes32 oldSwapHash = getSwapHash( _sender, address(0), _oracle, keccak256(_assetData), _paymentDetailsHash ); bytes32 newSwapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); bytes32 claimFromHash; // We want this function to be universal, regardless of whether `setBuyer` was called before. // If it was, the hash is already changed if (swaps[oldSwapHash] == 0) { claimFromHash = newSwapHash; requireSwapUnclaimed(newSwapHash); } else { claimFromHash = oldSwapHash; requireSwapUnclaimed(oldSwapHash); requireSwapNotExists(newSwapHash); swaps[oldSwapHash] = 0; } // any overflow security warnings can be safely ignored -- SWAP_LOCK_TIME_S is a small // constant, so this won't overflow an uint32 until year 2106 // solium-disable-next-line security/no-block-members swaps[newSwapHash] = uint32(block.timestamp) + SWAP_LOCK_TIME_S; emit Claimed(claimFromHash, newSwapHash); } /** * Swap release, which transfers the crypto asset to the receiver and removes the swap from * the active swap mapping. Normally called by the swap's oracle after it confirms a matching * wire transfer on sender's bank account. Can be also called by the sender, for example in case * of a dispute, when the parties reach an agreement off-chain. * * Emits a `Released` event with the swap's hash. */ function release( address _sender, address payable _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.FINALIZE_ONLY) onlyOracleOrSender(_sender, _oracle) { bytes32 swapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapClaimed(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetTo(_assetData, _receiver), "failed to send asset to receiver" ); if (msg.sender == _sender) { emit SenderReleased(swapHash); } else { emit Released(swapHash); } } /** * Swap return, which transfers the crypto asset back to the sender and removes the swap from * the active swap mapping. Can be called by the sender or the swap's oracle, but only if the * swap is not claimed, or was claimed but the escrow lock time expired. * * Emits a `Returned` event with the swap's hash. */ function returnFunds( address payable _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.RETURN_ONLY) onlyOracleOrSender(_sender, _oracle) { bytes32 swapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapUnclaimedOrExpired(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetTo(_assetData, _sender), "failed to send asset to sender" ); if (msg.sender == _sender) { emit SenderReturned(swapHash); } else { emit Returned(swapHash); } } /** * After the sender creates a swap, he can optionally call this function to restrict the swap * to a particular receiver address. The swap can't then be claimed by any other receiver. * * Emits a `BuyerSet` event with the created swap hash and new swap hash, updated with * receiver's address. */ function setBuyer( address _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.ACTIVE) onlySender(_sender) { bytes32 assetHash = keccak256(_assetData); bytes32 oldSwapHash = getSwapHash( _sender, address(0), _oracle, assetHash, _paymentDetailsHash ); requireSwapUnclaimed(oldSwapHash); bytes32 newSwapHash = getSwapHash( _sender, _receiver, _oracle, assetHash, _paymentDetailsHash ); requireSwapNotExists(newSwapHash); swaps[oldSwapHash] = 0; swaps[newSwapHash] = SWAP_UNCLAIMED; emit BuyerSet(oldSwapHash, newSwapHash); } /** * Given all valid swap details, returns its status. To check a swap with unset buyer, * use `0x0` as the `_receiver` address. The return can be: * 0: the swap details are invalid, swap doesn't exist, or was already released/returned. * 1: the swap was created, and is not claimed yet. * >1: the swap was claimed, and the value is a timestamp indicating end of its lock time. */ function getSwapStatus( address _sender, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external view returns (uint32 status) { bytes32 swapHash = getSwapHash( _sender, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); return swaps[swapHash]; } /** * Calculates the swap hash used to reference the swap in this contract's storage. */ function getSwapHash( address _sender, address _receiver, address _oracle, bytes32 assetHash, bytes32 _paymentDetailsHash ) internal pure returns (bytes32 hash) { return keccak256( abi.encodePacked( _sender, _receiver, _oracle, assetHash, _paymentDetailsHash ) ); } /** * Returns the EIP712 typed hash for the struct: * EIP712<Type>Swap { * action: bytes32; * sender: address; * receiver: address; * asset: asset data struct, see `getAssetTypedHash` in specific AssetAdapter contracts * paymentDetailsHash: bytes32; * } */ function getClaimTypedHash( address _sender, address _receiver, bytes memory _assetData, bytes32 _paymentDetailsHash ) internal view returns(bytes32 msgHash) { bytes32 dataHash = keccak256( abi.encode( EIP712_SWAP_TYPEHASH, bytes32("claim this swap"), _sender, _receiver, getAssetTypedHash(_assetData), _paymentDetailsHash ) ); return keccak256(abi.encodePacked(bytes2(0x1901), EIP712_DOMAIN_HASH, dataHash)); } function requireSwapNotExists(bytes32 swapHash) internal view { require(swaps[swapHash] == 0, "swap already exists"); } function requireSwapUnclaimed(bytes32 swapHash) internal view { require(swaps[swapHash] == SWAP_UNCLAIMED, "swap already claimed or invalid"); } function requireSwapClaimed(bytes32 swapHash) internal view { require(swaps[swapHash] > MIN_ACTUAL_TIMESTAMP, "swap unclaimed or invalid"); } function requireSwapUnclaimedOrExpired(bytes32 swapHash) internal view { require( // solium-disable-next-line security/no-block-members (swaps[swapHash] > MIN_ACTUAL_TIMESTAMP && block.timestamp > swaps[swapHash]) || swaps[swapHash] == SWAP_UNCLAIMED, "swap not expired or invalid" ); } }
9,391
157
// Set access control roles
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
9,615
1
// is everything okay?
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future," ); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image;
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future," ); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image;
12,275
287
// returns the multiplier used to calculate the sell penalty/initialDeviation the percent from peg at start of trade/finalDeviation the percent from peg at the end of trade
function getSellPenaltyMultiplier( Decimal.D256 calldata initialDeviation, Decimal.D256 calldata finalDeviation
function getSellPenaltyMultiplier( Decimal.D256 calldata initialDeviation, Decimal.D256 calldata finalDeviation
30,955
342
// Strike's SErc20 Contract STokens which wrap an EIP-20 underlying Strike /
contract SErc20 is SToken, SErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // SToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives sTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems sTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of sTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems sTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this sToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param sTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, STokenInterface sTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, sTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } }
contract SErc20 is SToken, SErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // SToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives sTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems sTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of sTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems sTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this sToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param sTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, STokenInterface sTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, sTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } }
22,197
34
// Red Eyes release token network limit
require(token.balanceOf(address(this)) < token_network_deposit_limit);
require(token.balanceOf(address(this)) < token_network_deposit_limit);
16,875
209
// See {Bozy - transferFrom}
function transferFrom( address _from, address _to, uint256 _tokens ) public override returns (bool success) {
function transferFrom( address _from, address _to, uint256 _tokens ) public override returns (bool success) {
41,620