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
|
|---|---|---|---|---|
6
|
// swap last element with deleted element
|
for (uint i = 0; i < numDevices; ++i) {
if (keccak256(names[i]) == keccak256(_name)) {
--numDevices;
names[i] = names[numDevices];
delete names[numDevices];
break;
}
|
for (uint i = 0; i < numDevices; ++i) {
if (keccak256(names[i]) == keccak256(_name)) {
--numDevices;
names[i] = names[numDevices];
delete names[numDevices];
break;
}
| 19,307
|
31
|
// Create new Standard Token contract with given "token issuer" account._tokenIssuer address of "token issuer" account /
|
function StandardToken (address _tokenIssuer) AbstractToken () {
tokenIssuer = _tokenIssuer;
accounts [_tokenIssuer] = MAX_UINT256;
}
|
function StandardToken (address _tokenIssuer) AbstractToken () {
tokenIssuer = _tokenIssuer;
accounts [_tokenIssuer] = MAX_UINT256;
}
| 7,550
|
51
|
// Function to secure contract from fail by toggling _stopped variable /
|
function toggleContractActive() public onlyOwner{
_stopped = !_stopped;
}
|
function toggleContractActive() public onlyOwner{
_stopped = !_stopped;
}
| 18,312
|
69
|
// Safe unsigned integer min returns b, if b < a; otherwise returns aa - first operand b - second operandreturn - the lesser of the two input values /
|
function bmin(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
|
function bmin(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
| 40,253
|
5
|
// Pool info
|
function lockableToken(Victim victim, uint256 poolId) external view returns (IERC20) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockableToken(uint256)", poolId));
require(success, "lockableToken(uint256 poolId) staticcall failed.");
return abi.decode(result, (IERC20));
}
|
function lockableToken(Victim victim, uint256 poolId) external view returns (IERC20) {
(bool success, bytes memory result) = address(victim).staticcall(abi.encodeWithSignature("lockableToken(uint256)", poolId));
require(success, "lockableToken(uint256 poolId) staticcall failed.");
return abi.decode(result, (IERC20));
}
| 15,771
|
278
|
// Saves investment asset rank details. maxIACurr Maximum ranked investment asset currency. maxRate Maximum ranked investment asset rate. minIACurr Minimum ranked investment asset currency. minRate Minimum ranked investment asset rate. date in yyyymmdd. /
|
function saveIARankDetails(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate,
uint64 date
)
external
onlyInternal
|
function saveIARankDetails(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate,
uint64 date
)
external
onlyInternal
| 28,719
|
73
|
// HIVESHARES
|
IERC20 public tradedToken = IERC20(0x007B1DCC6Ac10F3f689eb1EdcE7A2338Cd39ceed); //RewardToken
IUserPool cstarPool;
uint256 public constant DURATION = 360 days;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
address addrDev;
|
IERC20 public tradedToken = IERC20(0x007B1DCC6Ac10F3f689eb1EdcE7A2338Cd39ceed); //RewardToken
IUserPool cstarPool;
uint256 public constant DURATION = 360 days;
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
address addrDev;
| 24,502
|
228
|
// set the grade required
|
gems[_tokenId].grade = grade;
|
gems[_tokenId].grade = grade;
| 29,472
|
46
|
// Uses `StakeManager` to decide if the Relay Manager can be considered staked or not.Returns if the stake's token, amount and delay satisfy all requirements, reverts otherwise. /
|
function verifyRelayManagerStaked(address relayManager) external view;
|
function verifyRelayManagerStaked(address relayManager) external view;
| 4,453
|
459
|
// Define protected tokens for the strategy to manage persistently that will not get converted backto 'want'return address result, the address of the tokens to protect /
|
function protectedTokens()
internal
view
override
returns (address[] memory)
|
function protectedTokens()
internal
view
override
returns (address[] memory)
| 2,370
|
0
|
// ---------------------------------------------------------------------------- ERC Token Standard 20 Interface https:github.com/ethereum/EIPs/issues/20 ----------------------------------------------------------------------------
|
contract ERC20Interface {
uint public totalSupply;
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value)
returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant
returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender,
uint _value);
}
|
contract ERC20Interface {
uint public totalSupply;
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value)
returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant
returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender,
uint _value);
}
| 9,554
|
25
|
// See {mixinERC20.transfer}
|
function _transfer(
address sender,
address recipient,
uint256 amount
)internal virtual
|
function _transfer(
address sender,
address recipient,
uint256 amount
)internal virtual
| 20,105
|
9
|
// Library used to deploy contracts with specific code. This can be used for long-term storage of immutable data ascontract code, which can be retrieved via the `extcodecopy` opcode. /
|
library CodeDeployer {
// During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and
// `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be
// stored as its code.
//
// We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode
// sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the
// full code 32 bytes long:
//
// contract CodeDeployer {
// constructor() payable {
// uint256 size;
// assembly {
// size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long
// codecopy(0, 32, size) // copy all appended data to memory at position 0
// return(0, size) // return appended data for it to be stored as code
// }
// }
// }
//
// More specifically, it is composed of the following opcodes (plus padding):
//
// [1] PUSH1 0x20
// [2] CODESIZE
// [3] SUB
// [4] DUP1
// [6] PUSH1 0x20
// [8] PUSH1 0x00
// [9] CODECOPY
// [11] PUSH1 0x00
// [12] RETURN
//
// The padding is just the 0xfe sequence (invalid opcode). It is important as it lets us work in-place, avoiding
// memory allocation and copying.
bytes32
private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe;
/**
* @dev Deploys a contract with `code` as its code, returning the destination address.
*
* Reverts if deployment fails.
*/
function deploy(bytes memory code) internal returns (address destination) {
bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE;
// We need to concatenate the deployer creation code and `code` in memory, but want to avoid copying all of
// `code` (which could be quite long) into a new memory location. Therefore, we operate in-place using
// assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
let codeLength := mload(code)
// `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply
// replace it with the deployer creation code (which is exactly 32 bytes long).
mstore(code, deployerCreationCode)
// At this point, `code` now points to the deployer creation code immediately followed by `code`'s data
// contents. This is exactly what the deployer expects to receive when created.
destination := create(0, code, add(codeLength, 32))
// Finally, we restore the original length in order to not mutate `code`.
mstore(code, codeLength)
}
// The create opcode returns the zero address when contract creation fails, so we revert if this happens.
_require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED);
}
}
|
library CodeDeployer {
// During contract construction, the full code supplied exists as code, and can be accessed via `codesize` and
// `codecopy`. This is not the contract's final code however: whatever the constructor returns is what will be
// stored as its code.
//
// We use this mechanism to have a simple constructor that stores whatever is appended to it. The following opcode
// sequence corresponds to the creation code of the following equivalent Solidity contract, plus padding to make the
// full code 32 bytes long:
//
// contract CodeDeployer {
// constructor() payable {
// uint256 size;
// assembly {
// size := sub(codesize(), 32) // size of appended data, as constructor is 32 bytes long
// codecopy(0, 32, size) // copy all appended data to memory at position 0
// return(0, size) // return appended data for it to be stored as code
// }
// }
// }
//
// More specifically, it is composed of the following opcodes (plus padding):
//
// [1] PUSH1 0x20
// [2] CODESIZE
// [3] SUB
// [4] DUP1
// [6] PUSH1 0x20
// [8] PUSH1 0x00
// [9] CODECOPY
// [11] PUSH1 0x00
// [12] RETURN
//
// The padding is just the 0xfe sequence (invalid opcode). It is important as it lets us work in-place, avoiding
// memory allocation and copying.
bytes32
private constant _DEPLOYER_CREATION_CODE = 0x602038038060206000396000f3fefefefefefefefefefefefefefefefefefefe;
/**
* @dev Deploys a contract with `code` as its code, returning the destination address.
*
* Reverts if deployment fails.
*/
function deploy(bytes memory code) internal returns (address destination) {
bytes32 deployerCreationCode = _DEPLOYER_CREATION_CODE;
// We need to concatenate the deployer creation code and `code` in memory, but want to avoid copying all of
// `code` (which could be quite long) into a new memory location. Therefore, we operate in-place using
// assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
let codeLength := mload(code)
// `code` is composed of length and data. We've already stored its length in `codeLength`, so we simply
// replace it with the deployer creation code (which is exactly 32 bytes long).
mstore(code, deployerCreationCode)
// At this point, `code` now points to the deployer creation code immediately followed by `code`'s data
// contents. This is exactly what the deployer expects to receive when created.
destination := create(0, code, add(codeLength, 32))
// Finally, we restore the original length in order to not mutate `code`.
mstore(code, codeLength)
}
// The create opcode returns the zero address when contract creation fails, so we revert if this happens.
_require(destination != address(0), Errors.CODE_DEPLOYMENT_FAILED);
}
}
| 26,016
|
4
|
// token symbol
|
string private constant TOKEN_SYMBOL = "4dnft";
|
string private constant TOKEN_SYMBOL = "4dnft";
| 27,670
|
7
|
// Update memory variables based on timestamp against three categories and mint accordingly.
|
function mintSale(uint256 _numOfTokensToMint, bytes32[] calldata _merkleproof)
external
payable
isAddressOnWhitelist(_merkleproof)
|
function mintSale(uint256 _numOfTokensToMint, bytes32[] calldata _merkleproof)
external
payable
isAddressOnWhitelist(_merkleproof)
| 15,453
|
55
|
// Check lottery is in claimable status
|
if (_lotteries[_lotteryId].status != Status.Claimable) {
return 0;
}
|
if (_lotteries[_lotteryId].status != Status.Claimable) {
return 0;
}
| 17,723
|
11
|
// the current protocol fee as a percentage of the swap fee taken on withdrawal represented as an integer denominator (1/x)%
|
uint8 feeProtocol;
|
uint8 feeProtocol;
| 3,365
|
151
|
// rescue continues
|
return p.points[tester_];
|
return p.points[tester_];
| 28,251
|
158
|
// Allows only the owner of the contract to burn a specific token. _tokenId The specific token to be burnt. /
|
function burn(uint256 _tokenId) external onlyOwner() {
_burn(_tokenId);
}
|
function burn(uint256 _tokenId) external onlyOwner() {
_burn(_tokenId);
}
| 49,498
|
7
|
// This allows for the admin to reclaim the non-redeemableTokens./_to this is the address which the reclaimed tokens will be sent to./_nonRedeemableAddresses this is the array of tokens to be claimed.
|
function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) {
for (uint256 i = 0; i < _nonRedeemableAddresses.length; i++) {
//revert if token is redeemable
require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "redeemables cannot be claimed");
uint256 claimBalance = _balance(_nonRedeemableAddresses[i]);
if (claimBalance > 0) {
_safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance);
emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance);
}
}
return true;
}
|
function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) {
for (uint256 i = 0; i < _nonRedeemableAddresses.length; i++) {
//revert if token is redeemable
require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "redeemables cannot be claimed");
uint256 claimBalance = _balance(_nonRedeemableAddresses[i]);
if (claimBalance > 0) {
_safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance);
emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance);
}
}
return true;
}
| 42,907
|
8
|
// Set new admin for this contract Can only be executed by admin newAdmin new admin address /
|
function setAdmin(
address newAdmin
|
function setAdmin(
address newAdmin
| 12,612
|
233
|
// Sell token asset to buyer address _collectionAddressThe address of nft collection _tokenIdThe token id of nft collection _buyerThe buyer address who wants to buy nft asset _quoteToken The quote token for nft exchange /
|
function sellToken(
address _collectionAddress,
uint256 _tokenId,
address _buyer,
address _quoteToken
)
external
whenNotPaused
validAddress(_collectionAddress)
validAddress(_quoteToken)
|
function sellToken(
address _collectionAddress,
uint256 _tokenId,
address _buyer,
address _quoteToken
)
external
whenNotPaused
validAddress(_collectionAddress)
validAddress(_quoteToken)
| 19,388
|
19
|
// now check was money actually donated after the vote
|
(bool donated) = iDonor.donated(_tokenId);
require(donated, "You have not donated to this campaign");
|
(bool donated) = iDonor.donated(_tokenId);
require(donated, "You have not donated to this campaign");
| 15,345
|
1
|
// Returns the addition of two unsigned integers, reverting with custom message on overflow. Counterpart to Solidity's `+` operator. Requirements:- Addition cannot overflow. /
|
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
|
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
| 3,027
|
16
|
// Sets the amount of additional gas allowed to addresses calledThis allows transfers to multisigs that use more than 2300 gas in their fallback function.
|
function set_transfer_gas(uint transfer_gas) public onlyOwner {
gas = transfer_gas;
}
|
function set_transfer_gas(uint transfer_gas) public onlyOwner {
gas = transfer_gas;
}
| 29,579
|
35
|
// calculates the number of tokens purchased based on the amount of wei/spent and the price of tokens/_amount amound of wei that the buyer sent/_price price of tokens in the sale, in tokens/ETH/ return uint256 numTokens the number of tokens purchased/ return remainderany remaining wei leftover from integer division
|
function calculateTokenPurchase(uint256 _amount,
uint256 _price)
private
pure
returns (uint256,uint256)
|
function calculateTokenPurchase(uint256 _amount,
uint256 _price)
private
pure
returns (uint256,uint256)
| 1,131
|
24
|
// ========== INTERNAL FUNCTIONS ========== / From compound's _moveDelegates Keep track of votes. "Delegates" is a misnomer here
|
function trackVotes(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "PEGS::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "PEGS::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
|
function trackVotes(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "PEGS::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "PEGS::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
| 32,124
|
834
|
// Same as `_upscale`, but for an entire array (of two elements). This function does not return anything, butinstead mutates the `amounts` array. /
|
function _upscaleArray(uint256[] memory amounts) internal view {
amounts[0] = Math.mul(amounts[0], _scalingFactor(true));
amounts[1] = Math.mul(amounts[1], _scalingFactor(false));
}
|
function _upscaleArray(uint256[] memory amounts) internal view {
amounts[0] = Math.mul(amounts[0], _scalingFactor(true));
amounts[1] = Math.mul(amounts[1], _scalingFactor(false));
}
| 13,673
|
8
|
// Formats function data call borrow through DSProxy/_cCollToken CToken address of collateral/_cBorrowToken CToken address we will borrow/_borrowToken Token address we will borrow/_amount Amount that will be borrowed
|
function formatDSProxyBorrowCall(
address _cCollToken,
address _cBorrowToken,
address _borrowToken,
uint256 _amount
|
function formatDSProxyBorrowCall(
address _cCollToken,
address _cBorrowToken,
address _borrowToken,
uint256 _amount
| 29,900
|
60
|
// If new entry, replace first entry with this one.
|
if (entry.balance == 0) {
entry.next = entries[0x0].next;
entries[entries[0x0].next].prev = _address;
entries[0x0].next = _address;
}
|
if (entry.balance == 0) {
entry.next = entries[0x0].next;
entries[entries[0x0].next].prev = _address;
entries[0x0].next = _address;
}
| 48,099
|
2
|
// Creates a request that can hold additional parameters specId The Job Specification ID that the request will be created for callbackAddr address to operate the callback on callbackFunctionSignature function signature to use for the callbackreturn A Chainlink Request struct in memory /
|
function buildChainlinkRequest(
bytes32 specId,
address callbackAddr,
bytes4 callbackFunctionSignature
|
function buildChainlinkRequest(
bytes32 specId,
address callbackAddr,
bytes4 callbackFunctionSignature
| 15,193
|
347
|
// Time (s) proposals must be queued before executing
|
uint32 public immutable timelockDelay;
|
uint32 public immutable timelockDelay;
| 7,965
|
63
|
// Library computes actualAmountsIn, and does many validations Cannot call the push/pull/min from an external library for any of these pool functions. Since msg.sender can be anybody, they must be internal
|
uint256[] memory actualAmountsIn = SmartPoolManager.joinPool(
IConfigurableRightsPool(address(this)),
bPool,
poolAmountOut,
maxAmountsIn
);
|
uint256[] memory actualAmountsIn = SmartPoolManager.joinPool(
IConfigurableRightsPool(address(this)),
bPool,
poolAmountOut,
maxAmountsIn
);
| 3,740
|
84
|
// Updates the address of the contract registry
|
function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */;
|
function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */;
| 43,019
|
13
|
// Remove a minter should they no longer require or need the the privilege._minterThe desired address to be removed. /
|
function removeMinter(address _minter) external onlyEtheraffle {
require(isMinter[_minter]);
isMinter[_minter] = false;
for(uint i = 0; i < minters.length - 1; i++)
if(minters[i] == _minter) {
minters[i] = minters[minters.length - 1];
break;
}
minters.length--;
LogMinterRemoval(_minter, now);
}
|
function removeMinter(address _minter) external onlyEtheraffle {
require(isMinter[_minter]);
isMinter[_minter] = false;
for(uint i = 0; i < minters.length - 1; i++)
if(minters[i] == _minter) {
minters[i] = minters[minters.length - 1];
break;
}
minters.length--;
LogMinterRemoval(_minter, now);
}
| 43,484
|
1
|
// admin access control
|
bool isAdmin;
|
bool isAdmin;
| 28,429
|
36
|
// set new Core reference address/newCore the new core address
|
function setCore(address newCore) external override onlyGovernor {
require(newCore != address(0), "CoreRef: zero address");
address oldCore = address(_core);
_core = ICore(newCore);
emit CoreUpdate(oldCore, newCore);
}
|
function setCore(address newCore) external override onlyGovernor {
require(newCore != address(0), "CoreRef: zero address");
address oldCore = address(_core);
_core = ICore(newCore);
emit CoreUpdate(oldCore, newCore);
}
| 30,448
|
106
|
// contracts/MplRewards.sol/ pragma solidity 0.6.11; // import "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; // import "lib/openzeppelin-contracts/contracts/math/Math.sol"; // import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; // import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; // import "./interfaces/IERC2258.sol"; / https:docs.synthetix.io/contracts/source/contracts/stakingrewards/MplRewards Synthetix farming contract fork for liquidity mining.
|
contract MplRewards is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable rewardsToken;
IERC2258 public immutable stakingToken;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public rewardsDuration;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public lastPauseTime;
bool public paused;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
event RewardAdded(uint256 reward);
event Staked(address indexed account, uint256 amount);
event Withdrawn(address indexed account, uint256 amount);
event RewardPaid(address indexed account, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event PauseChanged(bool isPaused);
constructor(address _rewardsToken, address _stakingToken, address _owner) public {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC2258(_stakingToken);
rewardsDuration = 7 days;
transferOwnership(_owner);
}
function _updateReward(address account) internal {
uint256 _rewardPerTokenStored = rewardPerToken();
rewardPerTokenStored = _rewardPerTokenStored;
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = _rewardPerTokenStored;
}
}
function _notPaused() internal view {
require(!paused, "R:PAUSED");
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
return _totalSupply == 0
? rewardPerTokenStored
: rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/**
@dev It emits a `Staked` event.
*/
function stake(uint256 amount) external {
_notPaused();
_updateReward(msg.sender);
uint256 newBalance = _balances[msg.sender].add(amount);
require(amount > 0, "R:ZERO_STAKE");
require(stakingToken.custodyAllowance(msg.sender, address(this)) >= newBalance, "R:INSUF_CUST_ALLOWANCE");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = newBalance;
emit Staked(msg.sender, amount);
}
/**
@dev It emits a `Withdrawn` event.
*/
function withdraw(uint256 amount) public {
_notPaused();
_updateReward(msg.sender);
require(amount > 0, "R:ZERO_WITHDRAW");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.transferByCustodian(msg.sender, msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
/**
@dev It emits a `RewardPaid` event if any rewards are received.
*/
function getReward() public {
_notPaused();
_updateReward(msg.sender);
uint256 reward = rewards[msg.sender];
if (reward == uint256(0)) return;
rewards[msg.sender] = uint256(0);
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardAdded` event.
*/
function notifyRewardAmount(uint256 reward) external onlyOwner {
_updateReward(address(0));
uint256 _rewardRate = block.timestamp >= periodFinish
? reward.div(rewardsDuration)
: reward.add(
periodFinish.sub(block.timestamp).mul(rewardRate)
).div(rewardsDuration);
rewardRate = _rewardRate;
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(_rewardRate <= balance.div(rewardsDuration), "R:REWARD_TOO_HIGH");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
/**
@dev End rewards emission earlier. Only the contract Owner may call this.
*/
function updatePeriodFinish(uint256 timestamp) external onlyOwner {
_updateReward(address(0));
periodFinish = timestamp;
}
/**
@dev Added to support recovering tokens unintentionally sent to this contract.
Only the contract Owner may call this.
@dev It emits a `Recovered` event.
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
IERC20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardsDurationUpdated` event.
*/
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(block.timestamp > periodFinish, "R:PERIOD_NOT_FINISHED");
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
/**
@dev Change the paused state of the contract. Only the contract Owner may call this.
@dev It emits a `PauseChanged` event.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
require(_paused != paused, "R:ALREADY_SET");
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (_paused) lastPauseTime = block.timestamp;
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
|
contract MplRewards is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable rewardsToken;
IERC2258 public immutable stakingToken;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public rewardsDuration;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public lastPauseTime;
bool public paused;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
event RewardAdded(uint256 reward);
event Staked(address indexed account, uint256 amount);
event Withdrawn(address indexed account, uint256 amount);
event RewardPaid(address indexed account, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event PauseChanged(bool isPaused);
constructor(address _rewardsToken, address _stakingToken, address _owner) public {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC2258(_stakingToken);
rewardsDuration = 7 days;
transferOwnership(_owner);
}
function _updateReward(address account) internal {
uint256 _rewardPerTokenStored = rewardPerToken();
rewardPerTokenStored = _rewardPerTokenStored;
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = _rewardPerTokenStored;
}
}
function _notPaused() internal view {
require(!paused, "R:PAUSED");
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
return _totalSupply == 0
? rewardPerTokenStored
: rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/**
@dev It emits a `Staked` event.
*/
function stake(uint256 amount) external {
_notPaused();
_updateReward(msg.sender);
uint256 newBalance = _balances[msg.sender].add(amount);
require(amount > 0, "R:ZERO_STAKE");
require(stakingToken.custodyAllowance(msg.sender, address(this)) >= newBalance, "R:INSUF_CUST_ALLOWANCE");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = newBalance;
emit Staked(msg.sender, amount);
}
/**
@dev It emits a `Withdrawn` event.
*/
function withdraw(uint256 amount) public {
_notPaused();
_updateReward(msg.sender);
require(amount > 0, "R:ZERO_WITHDRAW");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.transferByCustodian(msg.sender, msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
/**
@dev It emits a `RewardPaid` event if any rewards are received.
*/
function getReward() public {
_notPaused();
_updateReward(msg.sender);
uint256 reward = rewards[msg.sender];
if (reward == uint256(0)) return;
rewards[msg.sender] = uint256(0);
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardAdded` event.
*/
function notifyRewardAmount(uint256 reward) external onlyOwner {
_updateReward(address(0));
uint256 _rewardRate = block.timestamp >= periodFinish
? reward.div(rewardsDuration)
: reward.add(
periodFinish.sub(block.timestamp).mul(rewardRate)
).div(rewardsDuration);
rewardRate = _rewardRate;
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(_rewardRate <= balance.div(rewardsDuration), "R:REWARD_TOO_HIGH");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
/**
@dev End rewards emission earlier. Only the contract Owner may call this.
*/
function updatePeriodFinish(uint256 timestamp) external onlyOwner {
_updateReward(address(0));
periodFinish = timestamp;
}
/**
@dev Added to support recovering tokens unintentionally sent to this contract.
Only the contract Owner may call this.
@dev It emits a `Recovered` event.
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
IERC20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardsDurationUpdated` event.
*/
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(block.timestamp > periodFinish, "R:PERIOD_NOT_FINISHED");
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
/**
@dev Change the paused state of the contract. Only the contract Owner may call this.
@dev It emits a `PauseChanged` event.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
require(_paused != paused, "R:ALREADY_SET");
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (_paused) lastPauseTime = block.timestamp;
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
| 27,598
|
17
|
// Freelancer lock can be released by freelancer only
|
bool freelancerLock;
|
bool freelancerLock;
| 24,478
|
35
|
// Get the token type
|
uint256 token_type = getTokenType(token_address);
|
uint256 token_type = getTokenType(token_address);
| 36,618
|
78
|
// ERC-721 Non-Fungible Token Standard, optional metadata extension /
|
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
|
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
| 30,241
|
99
|
// sellTokenAddress the address of token that the user is selling/buyTokenAddress the address of token that the user should receive/target the address of the aggregator contract that will exec the swap/swapCallData the calldata that will be passed to the aggregator contract/sellAmount the amount of tokens that the user is selling/feeAmount the amount of the tokens to sell that we will take as a fee
|
function fillQuoteTokenToToken(
address sellTokenAddress,
address buyTokenAddress,
address payable target,
bytes calldata swapCallData,
uint256 sellAmount,
uint256 feeAmount
|
function fillQuoteTokenToToken(
address sellTokenAddress,
address buyTokenAddress,
address payable target,
bytes calldata swapCallData,
uint256 sellAmount,
uint256 feeAmount
| 14,892
|
95
|
// If we don't want to take Offer with Boost to clear (cheaper gas cost for the purchase)
|
if(!clearExpired) {
if(availableBalance > delegatedBalance){
if(minBoostAmount > (availableBalance - delegatedBalance)) return 0;
return (availableBalance - delegatedBalance);
}
|
if(!clearExpired) {
if(availableBalance > delegatedBalance){
if(minBoostAmount > (availableBalance - delegatedBalance)) return 0;
return (availableBalance - delegatedBalance);
}
| 4,671
|
347
|
// Update the total amount of Fei being using to boost the Vault.
|
getTotalBoostedForVault[vault] = (newTotalBoostedForVault = getTotalBoostedForVault[vault] + feiAmount);
|
getTotalBoostedForVault[vault] = (newTotalBoostedForVault = getTotalBoostedForVault[vault] + feiAmount);
| 30,357
|
165
|
// nonReentrant module to prevent recursive calling of functions /
|
abstract contract nonReentrant {
bool private _reentryKey = false;
modifier reentryLock {
require(!_reentryKey, "cannot reenter a locked function");
_reentryKey = true;
_;
_reentryKey = false;
}
}
|
abstract contract nonReentrant {
bool private _reentryKey = false;
modifier reentryLock {
require(!_reentryKey, "cannot reenter a locked function");
_reentryKey = true;
_;
_reentryKey = false;
}
}
| 65,639
|
29
|
// Transfer the balance from token owner&39;s account to `to` account - Owner&39;s account must have sufficient balance to transfer - 0 value transfers are allowed to Address to transfer tokens to tokens Number of tokens to be transferred /
|
function transfer(address to, uint256 tokens) public returns (bool success) {
requireTrade(msg.sender);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
ensureInAccountList(to);
return true;
}
|
function transfer(address to, uint256 tokens) public returns (bool success) {
requireTrade(msg.sender);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
ensureInAccountList(to);
return true;
}
| 34,643
|
0
|
// EVENTS An event triggered when a transfer of tokens is made from a _from address to a _to address.
|
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
|
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
| 32,764
|
11
|
// create proposal
|
Proposal storage proposal = proposals[_proposalId];
proposal.id = _proposalId;
proposal.isVotingOpen = _isVotingOpen;
proposal.votingCreatedAt = now;
|
Proposal storage proposal = proposals[_proposalId];
proposal.id = _proposalId;
proposal.isVotingOpen = _isVotingOpen;
proposal.votingCreatedAt = now;
| 14,247
|
4
|
// Stores an array of assets owned by a given account /
|
mapping(address => uint256[]) internal _assetsOf;
|
mapping(address => uint256[]) internal _assetsOf;
| 36,972
|
141
|
// 用户取出指定份额的本币/share 取出的基金份额数量/ return amount 返回本币数量
|
function withdraw(uint share) external returns(uint amount);
|
function withdraw(uint share) external returns(uint amount);
| 37,403
|
8
|
// Star node.
|
IStarNode public starNode;
|
IStarNode public starNode;
| 28,071
|
138
|
// uint48 startTime;
|
uint48(block.timestamp),
|
uint48(block.timestamp),
| 55,947
|
287
|
// addresses to withdraw funds
|
address payable public teamAddress;
address payable public charityAddress;
string public prefix;
string public suffix;
Random private generator;
event TokenUpdated(
uint256 tokenId,
|
address payable public teamAddress;
address payable public charityAddress;
string public prefix;
string public suffix;
Random private generator;
event TokenUpdated(
uint256 tokenId,
| 28,103
|
17
|
// Disallows a specific function signature on a scoped target./Only callable by owner./role Role to set for/targetAddress Scoped address on which a function signature should be disallowed./functionSig Function signature to be disallowed.
|
function scopeRevokeFunction(
uint16 role,
address targetAddress,
bytes4 functionSig
|
function scopeRevokeFunction(
uint16 role,
address targetAddress,
bytes4 functionSig
| 60,140
|
14
|
// Functions and events necessary for the ERC20 Token Standard
|
function totalSupply() constant returns (uint totalSupply)
|
function totalSupply() constant returns (uint totalSupply)
| 9,004
|
6
|
// Constructor
|
function NATVCoin(address benificairyAddress) {
admin = msg.sender;
Balances[admin] = 3000000000000000;
coinSupply = 3000000000000000;
decimals = 8;
symbol = "NATV";
name = "Native Currency";
beneficiary = benificairyAddress; // Need to modify to client's wallet address
SetNATVTokenSale();
}
|
function NATVCoin(address benificairyAddress) {
admin = msg.sender;
Balances[admin] = 3000000000000000;
coinSupply = 3000000000000000;
decimals = 8;
symbol = "NATV";
name = "Native Currency";
beneficiary = benificairyAddress; // Need to modify to client's wallet address
SetNATVTokenSale();
}
| 10,752
|
104
|
// Allow RWA015 Join to modify Vat registry
|
DssExecLib.authorize(MCD_VAT, MCD_JOIN_RWA015_A);
|
DssExecLib.authorize(MCD_VAT, MCD_JOIN_RWA015_A);
| 10,559
|
15
|
// Percentage of the staking contract malicious behavior/ notification reward which will be transferred to the notifier/ reporting about a malicious DKG result. Notifiers are rewarded/ from a notifiers treasury pool. For example, if/ notification reward is 1000 and the value of the multiplier is/ 5, the notifier will receive: 5% of 1000 = 50 per each/ operator affected.
|
uint256 public dkgMaliciousResultNotificationRewardMultiplier;
|
uint256 public dkgMaliciousResultNotificationRewardMultiplier;
| 35,387
|
13
|
// fetching the principal, total stable debt and the avg stable rate
|
(
vars.principalStableDebt,
vars.currentStableDebt,
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp
) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData();
|
(
vars.principalStableDebt,
vars.currentStableDebt,
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp
) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData();
| 11,658
|
1
|
// The equivalent of exchangeRateStored() for Compound cTokens
|
function getReserveNormalizedIncome(address _reserve)
external
view
returns (uint256);
|
function getReserveNormalizedIncome(address _reserve)
external
view
returns (uint256);
| 28,097
|
107
|
// If approval is not zero reset it to zero first
|
if(currentAllowance != 0) {
return token.approve(spender, 0);
}
|
if(currentAllowance != 0) {
return token.approve(spender, 0);
}
| 33,513
|
7
|
// ambassadors
|
uint256 ambassadorLimit = HEX * 20000; // 20k hex per ambassador
uint256 devLimit = HEX * 100000;
mapping(address => bool) public ambassadors; // who the ambassadors are
mapping(address => bool) public dev;
address[33] ambassadorList = [
0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f,
0xe8f49490d2b172870b3B225e9fcD39b5D68b2e9E,
0x5161e1380cd661D7d993c8a3b3E57b059Ad8d7A4,
0x4Ca9046dcd4C8712450250208D7eD6fCEbAf75a5,
|
uint256 ambassadorLimit = HEX * 20000; // 20k hex per ambassador
uint256 devLimit = HEX * 100000;
mapping(address => bool) public ambassadors; // who the ambassadors are
mapping(address => bool) public dev;
address[33] ambassadorList = [
0xc951D3463EbBa4e9Ec8dDfe1f42bc5895C46eC8f,
0xe8f49490d2b172870b3B225e9fcD39b5D68b2e9E,
0x5161e1380cd661D7d993c8a3b3E57b059Ad8d7A4,
0x4Ca9046dcd4C8712450250208D7eD6fCEbAf75a5,
| 44,358
|
30
|
// Returns a token ID owned by `owner` at a given `index` of its token list.
|
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
| 786
|
102
|
// Unstakes a certain amount of previously deposited tokens. User also receives theiralotted number of distribution tokens. _amount Number of deposit tokens to unstake / withdraw. _data Not used. /
|
function unstake(uint256 _amount, bytes calldata _data) external;
|
function unstake(uint256 _amount, bytes calldata _data) external;
| 7,691
|
162
|
// res += val(coefficients[16] + coefficients[17]adjustments[3]).
|
res := addmod(res,
mulmod(val,
add(/*coefficients[16]*/ mload(0x640),
mulmod(/*coefficients[17]*/ mload(0x660),
|
res := addmod(res,
mulmod(val,
add(/*coefficients[16]*/ mload(0x640),
mulmod(/*coefficients[17]*/ mload(0x660),
| 20,695
|
2
|
// `transfer` method may return (bool) or nothing.
|
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
|
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
| 29,965
|
1,426
|
// Set winner count (no.of winners).
|
winnerConfig.winnerCount = config.prizeSequence_winnerCount;
|
winnerConfig.winnerCount = config.prizeSequence_winnerCount;
| 4,867
|
444
|
// Fee percentage and balance multiplications round down, while the subtrahend (power) rounds up (as does the base). Because previousInvariant / currentInvariant <= 1, the exponent rounds down.
|
uint256 base = previousInvariant.divUp(currentInvariant);
uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight);
|
uint256 base = previousInvariant.divUp(currentInvariant);
uint256 exponent = FixedPoint.ONE.divDown(normalizedWeight);
| 3,193
|
336
|
// Bridges ERC20 tokens via Hop Protocol from L2/transactionId Custom transaction ID for tracking/receiver Receiving wallet address/destinationChainId Receiving chain/sendingAssetId Address of the source asset to bridge/minAmount Amount of the source asset to bridge/bonderFee Fees payed to hop bonder/amountOutMin Source swap minimal accepted amount/destinationAmountOutMin Destination swap minimal accepted amount/destinationDeadline Destination swap maximal time/hopBridge Address of the Hop L2_AmmWrapper
|
function startBridgeTokensViaHopL2ERC20Min(
bytes8 transactionId,
address receiver,
uint256 destinationChainId,
address sendingAssetId,
uint256 minAmount,
uint256 bonderFee,
uint256 amountOutMin,
uint256 destinationAmountOutMin,
uint256 destinationDeadline,
|
function startBridgeTokensViaHopL2ERC20Min(
bytes8 transactionId,
address receiver,
uint256 destinationChainId,
address sendingAssetId,
uint256 minAmount,
uint256 bonderFee,
uint256 amountOutMin,
uint256 destinationAmountOutMin,
uint256 destinationDeadline,
| 8,962
|
316
|
// Callback for IUniswapV3PoolActionsswap/Any contract that calls IUniswapV3PoolActionsswap must implement this interface
|
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
|
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
| 3,570
|
11
|
// Get join from fyToken
|
IJoin join = fyToken.join();
|
IJoin join = fyToken.join();
| 21,165
|
201
|
// Perform function call
|
_;
|
_;
| 26,621
|
16
|
// Simple withdraw operation for the ERC20 tBTC tokens held in the contract in behalf of an operator
|
function operatorWithdrawTBTC(uint amount) public returns(bool){
Operator storage op = operators[msg.sender];
require(op.tBTCBalance >= amount);
op.tBTCBalance -= amount;
tBTContract.transfer(msg.sender, amount);
return true;
}
|
function operatorWithdrawTBTC(uint amount) public returns(bool){
Operator storage op = operators[msg.sender];
require(op.tBTCBalance >= amount);
op.tBTCBalance -= amount;
tBTContract.transfer(msg.sender, amount);
return true;
}
| 45,552
|
207
|
// 800k redeem lending profit from anXSushi to xSushi
|
uint eta = estimatedTotalAssets();
uint debt = vault.strategies(address(this)).totalDebt;
uint lendingProfitSushi = eta > debt ? eta.sub(debt) : 0;
uint lendingProfitXSushi = lendingProfitSushi.mul(1e18).div(sushiPerXSushi());
_redeemUnderlying(lendingProfitXSushi);
|
uint eta = estimatedTotalAssets();
uint debt = vault.strategies(address(this)).totalDebt;
uint lendingProfitSushi = eta > debt ? eta.sub(debt) : 0;
uint lendingProfitXSushi = lendingProfitSushi.mul(1e18).div(sushiPerXSushi());
_redeemUnderlying(lendingProfitXSushi);
| 3,919
|
1,179
|
// approve FL tokens so we can repay them
|
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
|
ERC20(_reserve).safeApprove(cBorrowToken, uint(-1));
| 31,503
|
139
|
// Gold Period Cap per address
|
uint256 goldPeriodCap;
|
uint256 goldPeriodCap;
| 49,805
|
0
|
// Each sample in the buffer accumulates information for up to 2 minutes. This is simply to reduce the size of the buffer: small time deviations will not have any significant effect. solhint-disable not-rely-on-time
|
uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes;
|
uint256 private constant _MAX_SAMPLE_DURATION = 2 minutes;
| 1,432
|
444
|
// (a + b) / 2 can overflow, so we distribute
|
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
|
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
| 2,631
|
72
|
// add a role to an addressaddr addressroleName the name of the role/
|
function adminAddRole(address addr, string roleName) onlyOwner public {
roles[roleName].add(addr);
RoleAdded(addr, roleName);
}
|
function adminAddRole(address addr, string roleName) onlyOwner public {
roles[roleName].add(addr);
RoleAdded(addr, roleName);
}
| 4,531
|
11
|
// Bet bear position epoch: epoch /
|
function betBear(
uint256 epoch,
uint256 tokenAmount
|
function betBear(
uint256 epoch,
uint256 tokenAmount
| 19,449
|
146
|
// stake into LiquidityGaugeV2
|
uint lpBal = IERC20(LP).balanceOf(address(this));
if (lpBal > 0) {
IERC20(LP).safeApprove(GAUGE, lpBal);
LiquidityGaugeV2(GAUGE).deposit(lpBal);
}
|
uint lpBal = IERC20(LP).balanceOf(address(this));
if (lpBal > 0) {
IERC20(LP).safeApprove(GAUGE, lpBal);
LiquidityGaugeV2(GAUGE).deposit(lpBal);
}
| 30,936
|
6
|
// solium-disable-next-line security/no-inline-assembly
|
assembly {
value := sload(_key)
}
|
assembly {
value := sload(_key)
}
| 362
|
6
|
// Oracle withdraw LINK earned through fulfilling requests/If amount is 0 the full balance will be withdrawn/recipient where to send the funds/amount amount to withdraw
|
function oracleWithdraw(address recipient, uint96 amount) external;
|
function oracleWithdraw(address recipient, uint96 amount) external;
| 24,331
|
26
|
// -- Constructor -- //Constructor to create a ReferenceToken/_name Name of the new token/_symbol Symbol of the new token./_granularity Minimum transferable chunk.
|
constructor(
string memory _name,
string memory _symbol,
uint256 _granularity,
address[] memory _defaultOperators
|
constructor(
string memory _name,
string memory _symbol,
uint256 _granularity,
address[] memory _defaultOperators
| 19,142
|
125
|
// bosomget(): Get bosoms and add Stake. Only contract is able to call this function:
|
function bosomget (address _staker, uint _amount) internal {
addStake(_staker, _amount);
bosoms[_staker] = bosoms[_staker].add(_amount);
}
|
function bosomget (address _staker, uint _amount) internal {
addStake(_staker, _amount);
bosoms[_staker] = bosoms[_staker].add(_amount);
}
| 33,515
|
11
|
// EIP712 typed signatures verifier for EAS delegated attestations. /
|
contract EIP712Verifier is IEIP712Verifier {
error InvalidSignature();
string public constant VERSION = "0.8";
// EIP712 domain separator, making signatures from different domains incompatible.
bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase
// The hash of the data type used to relay calls to the attest function. It's the value of
// keccak256("Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)").
bytes32 public constant ATTEST_TYPEHASH = 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;
// The hash of the data type used to relay calls to the revoke function. It's the value of
// keccak256("Revoke(bytes32 uuid,uint256 nonce)").
bytes32 public constant REVOKE_TYPEHASH = 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;
// Replay protection nonces.
mapping(address => uint256) private _nonces;
/**
* @dev Creates a new EIP712Verifier instance.
*/
constructor() {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("EAS")),
keccak256(bytes(VERSION)),
chainId,
address(this)
)
);
}
/**
* @inheritdoc IEIP712Verifier
*/
function getNonce(address account) external view returns (uint256) {
return _nonces[account];
}
/**
* @inheritdoc IEIP712Verifier
*/
function attest(
address recipient,
bytes32 schema,
uint256 expirationTime,
bytes32 refUUID,
bytes calldata data,
address attester,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
ATTEST_TYPEHASH,
recipient,
schema,
expirationTime,
refUUID,
keccak256(data),
_nonces[attester]++
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
if (recoveredAddress == address(0) || recoveredAddress != attester) {
revert InvalidSignature();
}
}
/**
* @inheritdoc IEIP712Verifier
*/
function revoke(
bytes32 uuid,
address attester,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
if (recoveredAddress == address(0) || recoveredAddress != attester) {
revert InvalidSignature();
}
}
}
|
contract EIP712Verifier is IEIP712Verifier {
error InvalidSignature();
string public constant VERSION = "0.8";
// EIP712 domain separator, making signatures from different domains incompatible.
bytes32 public immutable DOMAIN_SEPARATOR; // solhint-disable-line var-name-mixedcase
// The hash of the data type used to relay calls to the attest function. It's the value of
// keccak256("Attest(address recipient,bytes32 schema,uint256 expirationTime,bytes32 refUUID,bytes data,uint256 nonce)").
bytes32 public constant ATTEST_TYPEHASH = 0x39c0608dd995a3a25bfecb0fffe6801a81bae611d94438af988caa522d9d1476;
// The hash of the data type used to relay calls to the revoke function. It's the value of
// keccak256("Revoke(bytes32 uuid,uint256 nonce)").
bytes32 public constant REVOKE_TYPEHASH = 0xbae0931f3a99efd1b97c2f5b6b6e79d16418246b5055d64757e16de5ad11a8ab;
// Replay protection nonces.
mapping(address => uint256) private _nonces;
/**
* @dev Creates a new EIP712Verifier instance.
*/
constructor() {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("EAS")),
keccak256(bytes(VERSION)),
chainId,
address(this)
)
);
}
/**
* @inheritdoc IEIP712Verifier
*/
function getNonce(address account) external view returns (uint256) {
return _nonces[account];
}
/**
* @inheritdoc IEIP712Verifier
*/
function attest(
address recipient,
bytes32 schema,
uint256 expirationTime,
bytes32 refUUID,
bytes calldata data,
address attester,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
ATTEST_TYPEHASH,
recipient,
schema,
expirationTime,
refUUID,
keccak256(data),
_nonces[attester]++
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
if (recoveredAddress == address(0) || recoveredAddress != attester) {
revert InvalidSignature();
}
}
/**
* @inheritdoc IEIP712Verifier
*/
function revoke(
bytes32 uuid,
address attester,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(REVOKE_TYPEHASH, uuid, _nonces[attester]++))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
if (recoveredAddress == address(0) || recoveredAddress != attester) {
revert InvalidSignature();
}
}
}
| 46,273
|
253
|
// Ensure invoke comptroller.isComptroller() returns true
|
require(newComptroller.isComptroller(), "marker method returned false");
|
require(newComptroller.isComptroller(), "marker method returned false");
| 21,013
|
23
|
// Send a batch of erc20 payments on multiple tokens w/fees with paymentReferences to multiple accounts. _tokenAddresses List of tokens to transact with. _recipients List of recipients accounts. _amounts List of amounts, corresponding to recipients[]. _paymentReferences List of paymentRefs, corr. to the recipients[]. _feeAmounts List of amounts of the payment fee, corr. to the recipients[]. _feeAddress The fee recipient. It uses ERC20FeeProxy to pay an invoice and fees, with a payment reference. Make sure the contract has allowance to spend the payer token. Make sure the payer has enough tokens to pay the amount, the fee, the batch fee /
|
function batchERC20PaymentsMultiTokensWithReference(
address[] calldata _tokenAddresses,
address[] calldata _recipients,
uint256[] calldata _amounts,
bytes[] calldata _paymentReferences,
uint256[] calldata _feeAmounts,
address _feeAddress
|
function batchERC20PaymentsMultiTokensWithReference(
address[] calldata _tokenAddresses,
address[] calldata _recipients,
uint256[] calldata _amounts,
bytes[] calldata _paymentReferences,
uint256[] calldata _feeAmounts,
address _feeAddress
| 32,475
|
100
|
// if any account belongs to _isExcludedFromFee account then remove the fee
|
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
takeFee = false;
}
|
if (_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]) {
takeFee = false;
}
| 79,684
|
28
|
// Emitted when the `royaltyBPS` is set. bps The new royalty, measured in basis points. /
|
event RoyaltySet(uint16 bps);
|
event RoyaltySet(uint16 bps);
| 8,192
|
0
|
// Set the Fintroller contract and sanity check it. //Set the fyToken contract. It cannot be sanity-checked because the fyToken creates thiscontract in its own constructor and contracts cannot be called while initializing. /
|
fyToken = fyToken_;
|
fyToken = fyToken_;
| 12,249
|
281
|
// Performance Fees goes to treasury
|
IERC20(want).safeTransfer(IController(controller).treasury(), _want.mul(performanceFee).div(performanceMax));
|
IERC20(want).safeTransfer(IController(controller).treasury(), _want.mul(performanceFee).div(performanceMax));
| 3,046
|
19
|
// msg.value is sent, but 0 is set to the L2 call value the eth sent is used to pay for the tx's gas
|
return
sendTxToL2CustomRefund(
inbox,
counterpartGateway,
_refundTo,
_from,
msg.value, // we forward the L1 call value to the inbox
0, // l2 call value 0 by default
L2GasParams({
_maxSubmissionCost: _maxSubmissionCost,
|
return
sendTxToL2CustomRefund(
inbox,
counterpartGateway,
_refundTo,
_from,
msg.value, // we forward the L1 call value to the inbox
0, // l2 call value 0 by default
L2GasParams({
_maxSubmissionCost: _maxSubmissionCost,
| 22,357
|
10
|
// ============ Internal Functions ============ //Resolve equity positions associated with SetToken. On issuance, the total equity position for an asset (including default and externalpositions) is transferred in. Then any external position hooks are called to transfer the external positions to their necessary place.On redemption all external positions are recalled by the external position hook, then those position plus any default position aretransferred back to the _to address. /
|
function _resolveEquityPositions(
ISetToken _setToken,
uint256 _quantity,
address _to,
bool _isIssue,
address[] memory _components,
uint256[] memory _componentEquityQuantities,
uint256 _initialSetSupply,
uint256 _finalSetSupply
)
|
function _resolveEquityPositions(
ISetToken _setToken,
uint256 _quantity,
address _to,
bool _isIssue,
address[] memory _components,
uint256[] memory _componentEquityQuantities,
uint256 _initialSetSupply,
uint256 _finalSetSupply
)
| 28,151
|
78
|
// CBOR can be closed with curly-brackets {} or they can be left off self The initialized request data The CBOR data /
|
function setBuffer(Request memory self, bytes memory data) internal pure {
BufferChainlink.init(self.buf, data.length);
BufferChainlink.append(self.buf, data);
}
|
function setBuffer(Request memory self, bytes memory data) internal pure {
BufferChainlink.init(self.buf, data.length);
BufferChainlink.append(self.buf, data);
}
| 42,650
|
152
|
// Get the family /
|
function getFamily(uint16 index)
private
pure
returns (string memory)
|
function getFamily(uint16 index)
private
pure
returns (string memory)
| 63,092
|
33
|
// Deletes a bytes32 array's element for a given key and index key The specified mapping key index The specified index of the desired elementRequirements: - Only callable by the latest version of any Eternal contract /
|
function deleteBytes(bytes32 key, uint256 index) external override onlyLatestVersion {
uint256 length = manyBytes[key].length;
manyBytes[key][index] = manyBytes[key][length - 1];
manyBytes[key].pop();
}
|
function deleteBytes(bytes32 key, uint256 index) external override onlyLatestVersion {
uint256 length = manyBytes[key].length;
manyBytes[key][index] = manyBytes[key][length - 1];
manyBytes[key].pop();
}
| 7,650
|
156
|
// Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance atreturn The number of votes the account had as of the given block /
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
| 1,864
|
12
|
// Freedom Token vesting functionality. /
|
contract TokenVesting {
struct VestClaimStatus {
uint256 claimed;
uint256 perBlock;
uint256 blockGap;
uint256 lastClaimBlock;
uint256 total;
}
uint256 private immutable _initBlock;
/** IMMUTABLE STORAGE */
/// @notice Merkle root for token vesting participants.
bytes32 public immutable vestClaimRoot;
/// @notice Total token supply allocated to vesting.
uint256 public immutable vestSupply;
/// @notice Total number of tokens claimed so far by all vesters.
uint256 private _vestClaimTotal;
/// @notice Claim Status for each wallet with vesting tokens.
mapping(address => VestClaimStatus) private _vestClaims;
/// @notice Emitted on successful vested token claim when the number of tokens claimed
/// is 1 or more. Does not fire for 0 claims.
/// @param to recipient of claim
/// @param amt of tokens claimed
event VestClaim(address indexed to, uint256 amt);
/** ERRORS */
error VestWalletNotFound();
error VestClaimExhausted();
error VestClaimNotReady();
error VestNoTokensClaimableYet();
constructor(
uint256 supply,
uint256 initBlock,
bytes32 root
) {
vestSupply = supply;
vestClaimRoot = root;
_initBlock = initBlock;
_vestClaimTotal = 0;
}
/// @notice Get number of vested wallet & claimable tokens for target wallet.
function getVestedAmt(address target) public view returns (uint256) {
if (_vestClaims[target].perBlock == 0) {
return 0;
}
VestClaimStatus memory status = _vestClaims[target];
if (block.number <= status.lastClaimBlock) {
return 0;
}
uint256 blocks = block.number - status.lastClaimBlock;
if (blocks < status.blockGap) {
return 0;
}
return blocks * status.perBlock;
}
/// @notice Attempt to claim all vested tokens for wallet.
function vestClaim(address to) external {
VestClaimStatus memory vester = _vestClaims[to];
if (vester.perBlock == 0) {
revert VestWalletNotFound();
}
if (vester.claimed >= vester.total) {
revert VestClaimExhausted();
}
uint256 amt = getVestedAmt(to);
uint256 avail = vester.total - vester.claimed;
if (amt == 0) {
revert VestNoTokensClaimableYet();
}
if (avail == 0) {
revert VestClaimExhausted();
}
// Decrease available claim to match available, if claiming the
// current amount would put this wallet over total claim limit.
if (amt > avail) {
amt = avail;
}
if (vester.claimed + amt > vester.total) {
amt = vester.total - vester.claimed;
}
// Update number of tokens claimed.
_vestClaims[to].claimed = amt + vester.claimed;
// Update last block on which tokens were claimed successfully.
_vestClaims[to].lastClaimBlock = block.number;
emit VestClaim(to, amt);
}
}
|
contract TokenVesting {
struct VestClaimStatus {
uint256 claimed;
uint256 perBlock;
uint256 blockGap;
uint256 lastClaimBlock;
uint256 total;
}
uint256 private immutable _initBlock;
/** IMMUTABLE STORAGE */
/// @notice Merkle root for token vesting participants.
bytes32 public immutable vestClaimRoot;
/// @notice Total token supply allocated to vesting.
uint256 public immutable vestSupply;
/// @notice Total number of tokens claimed so far by all vesters.
uint256 private _vestClaimTotal;
/// @notice Claim Status for each wallet with vesting tokens.
mapping(address => VestClaimStatus) private _vestClaims;
/// @notice Emitted on successful vested token claim when the number of tokens claimed
/// is 1 or more. Does not fire for 0 claims.
/// @param to recipient of claim
/// @param amt of tokens claimed
event VestClaim(address indexed to, uint256 amt);
/** ERRORS */
error VestWalletNotFound();
error VestClaimExhausted();
error VestClaimNotReady();
error VestNoTokensClaimableYet();
constructor(
uint256 supply,
uint256 initBlock,
bytes32 root
) {
vestSupply = supply;
vestClaimRoot = root;
_initBlock = initBlock;
_vestClaimTotal = 0;
}
/// @notice Get number of vested wallet & claimable tokens for target wallet.
function getVestedAmt(address target) public view returns (uint256) {
if (_vestClaims[target].perBlock == 0) {
return 0;
}
VestClaimStatus memory status = _vestClaims[target];
if (block.number <= status.lastClaimBlock) {
return 0;
}
uint256 blocks = block.number - status.lastClaimBlock;
if (blocks < status.blockGap) {
return 0;
}
return blocks * status.perBlock;
}
/// @notice Attempt to claim all vested tokens for wallet.
function vestClaim(address to) external {
VestClaimStatus memory vester = _vestClaims[to];
if (vester.perBlock == 0) {
revert VestWalletNotFound();
}
if (vester.claimed >= vester.total) {
revert VestClaimExhausted();
}
uint256 amt = getVestedAmt(to);
uint256 avail = vester.total - vester.claimed;
if (amt == 0) {
revert VestNoTokensClaimableYet();
}
if (avail == 0) {
revert VestClaimExhausted();
}
// Decrease available claim to match available, if claiming the
// current amount would put this wallet over total claim limit.
if (amt > avail) {
amt = avail;
}
if (vester.claimed + amt > vester.total) {
amt = vester.total - vester.claimed;
}
// Update number of tokens claimed.
_vestClaims[to].claimed = amt + vester.claimed;
// Update last block on which tokens were claimed successfully.
_vestClaims[to].lastClaimBlock = block.number;
emit VestClaim(to, amt);
}
}
| 6,388
|
31
|
// Deposit Liquidity. token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) amt token amount./
|
function deposit(address token, uint amt) external payable returns (uint _amt) {
require(isTknAllowed[token], "token-not-listed");
require(amt > 0 || msg.value > 0, "amt-not-valid");
if (msg.value > 0) require(token == ethAddr, "not-eth-addr");
address cErc20 = tknToCTkn[token];
uint initalBal = tokenBal(cErc20);
if (token == ethAddr) {
_amt = msg.value;
CETHInterface(cErc20).mint.value(_amt)();
} else {
_amt = amt == (uint(-1)) ? TokenInterface(token).balanceOf(msg.sender) : amt;
require(TokenInterface(token).transferFrom(msg.sender, address(this), _amt), "allowance/balance?");
require(CTokenInterface(cErc20).mint(_amt) == 0, "mint-failed");
}
uint finalBal = tokenBal(cErc20);
uint ctokenAmt = sub(finalBal, initalBal);
liquidityBalance[token][msg.sender] += ctokenAmt;
emit LogDeposit(msg.sender, token, _amt, ctokenAmt);
}
|
function deposit(address token, uint amt) external payable returns (uint _amt) {
require(isTknAllowed[token], "token-not-listed");
require(amt > 0 || msg.value > 0, "amt-not-valid");
if (msg.value > 0) require(token == ethAddr, "not-eth-addr");
address cErc20 = tknToCTkn[token];
uint initalBal = tokenBal(cErc20);
if (token == ethAddr) {
_amt = msg.value;
CETHInterface(cErc20).mint.value(_amt)();
} else {
_amt = amt == (uint(-1)) ? TokenInterface(token).balanceOf(msg.sender) : amt;
require(TokenInterface(token).transferFrom(msg.sender, address(this), _amt), "allowance/balance?");
require(CTokenInterface(cErc20).mint(_amt) == 0, "mint-failed");
}
uint finalBal = tokenBal(cErc20);
uint ctokenAmt = sub(finalBal, initalBal);
liquidityBalance[token][msg.sender] += ctokenAmt;
emit LogDeposit(msg.sender, token, _amt, ctokenAmt);
}
| 34,256
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.