Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
0 | // Green certificate / | struct Certificate {
address token;
uint256 value;
}
| struct Certificate {
address token;
uint256 value;
}
| 22,714 |
38 | // System-level secure distributed random number generator. | function updateRandomness(uint[2] memory sig) public {
if (!validateAndVerify(
TrafficSystemRandom,
lastRandomness,
toBytes(lastRandomness),
BN256.G1Point(sig[0], sig[1]),
lastHandledGroup))
{
return;
}
// Update new randomness = sha3(collectively signed group signature)
lastRandomness = uint(keccak256(abi.encodePacked(sig[0], sig[1])));
lastUpdatedBlock = block.number - 1;
uint idx = lastRandomness % groupPubKeys.length;
lastHandledGroup = groupPubKeys[idx];
// Signal selected off-chain clients to collectively generate a new
// system level random number for next round.
emit LogUpdateRandom(lastRandomness, getGroupPubKey(idx));
}
| function updateRandomness(uint[2] memory sig) public {
if (!validateAndVerify(
TrafficSystemRandom,
lastRandomness,
toBytes(lastRandomness),
BN256.G1Point(sig[0], sig[1]),
lastHandledGroup))
{
return;
}
// Update new randomness = sha3(collectively signed group signature)
lastRandomness = uint(keccak256(abi.encodePacked(sig[0], sig[1])));
lastUpdatedBlock = block.number - 1;
uint idx = lastRandomness % groupPubKeys.length;
lastHandledGroup = groupPubKeys[idx];
// Signal selected off-chain clients to collectively generate a new
// system level random number for next round.
emit LogUpdateRandom(lastRandomness, getGroupPubKey(idx));
}
| 15,027 |
15 | // Supply limited to 2^128 rather than 2^256 to prevent potentialmultiplication overflow | require(_supply < 2**128);
totSupply = _supply;
sym = _symbol;
balance[msg.sender] = totSupply;
| require(_supply < 2**128);
totSupply = _supply;
sym = _symbol;
balance[msg.sender] = totSupply;
| 45,248 |
8 | // move unlocked funds between poolscan be moved only by the owner and only from zero pool - the reserve cannot use locked funds (vesting)cannot be called before vesting is funded / | function moveFunds(uint256 toPoolId, uint256 amount) external onlyOwner {
require(vestingEndDate > 0, "PoolsBase: pools not ready");
uint256 _lockedPercent = lockedPercent();
if (_lockedPercent > 0) {
require(
poolBalance[0] >= amount + vestingBase[0] * _lockedPercent / 100000,
"PoolsBase: insufficient funds"
);
} else {
require(
poolBalance[0] >= amount,
"PoolsBase: insufficient funds"
);
}
poolBalance[0] -= amount;
poolBalance[toPoolId] += amount;
emit MoveFunds(0, toPoolId, amount);
}
| function moveFunds(uint256 toPoolId, uint256 amount) external onlyOwner {
require(vestingEndDate > 0, "PoolsBase: pools not ready");
uint256 _lockedPercent = lockedPercent();
if (_lockedPercent > 0) {
require(
poolBalance[0] >= amount + vestingBase[0] * _lockedPercent / 100000,
"PoolsBase: insufficient funds"
);
} else {
require(
poolBalance[0] >= amount,
"PoolsBase: insufficient funds"
);
}
poolBalance[0] -= amount;
poolBalance[toPoolId] += amount;
emit MoveFunds(0, toPoolId, amount);
}
| 29,141 |
8 | // EVM BLOCKHASH opcode can query no further than 256 blocks into the past. Given that settleBet uses block hash of placeBet as one of complementary entropy sources, we cannot process bets older than this threshold. On rare occasions myethergames.fun croupier may fail to invoke settleBet in this timespan due to technical issues or extreme Ethereum congestion; such bets can be refunded via invoking refundBet. | uint constant BET_EXPIRATION_BLOCKS = 250;
| uint constant BET_EXPIRATION_BLOCKS = 250;
| 5,734 |
58 | // Returns the token collection name. / | function name() external view returns (string memory);
| function name() external view returns (string memory);
| 5,783 |
47 | // Issue tokens. See MonetarySupervisor but as a rule of thumb issueTo is only allowed:- on new loan (by trusted Lender contracts)- when converting old tokens using MonetarySupervisor- strictly to reserve by Stability Board (via MonetarySupervisor) | function issueTo(address to, uint amount) external restrict("MonetarySupervisor") {
balances[to] = balances[to].add(amount);
totalSupply = totalSupply.add(amount);
emit Transfer(0x0, to, amount);
emit AugmintTransfer(0x0, to, amount, "", 0);
}
| function issueTo(address to, uint amount) external restrict("MonetarySupervisor") {
balances[to] = balances[to].add(amount);
totalSupply = totalSupply.add(amount);
emit Transfer(0x0, to, amount);
emit AugmintTransfer(0x0, to, amount, "", 0);
}
| 32,048 |
132 | // e.g. 8e1717268172638 = 138145381104e17 | uint256 scaled = x.mul(y);
| uint256 scaled = x.mul(y);
| 11,563 |
17 | // the first note is the current interest note |
_loanVariables.settlementToken.confidentialTransferFrom(JOIN_SPLIT_PROOF, _proof2Outputs.get(0));
|
_loanVariables.settlementToken.confidentialTransferFrom(JOIN_SPLIT_PROOF, _proof2Outputs.get(0));
| 26,825 |
3 | // Operators | function authorizeOperator(address _operator) external;
function revokeOperator(address _operator) external;
function isOperator(address _operator, address _tokenHolder) external view returns (bool);
function authorizeOperatorByPartition(bytes32 _partition, address _operator) external;
function revokeOperatorByPartition(bytes32 _partition, address _operator) external;
function isOperatorForPartition(bytes32 _partition, address _operator, address _tokenHolder) external view returns (bool);
| function authorizeOperator(address _operator) external;
function revokeOperator(address _operator) external;
function isOperator(address _operator, address _tokenHolder) external view returns (bool);
function authorizeOperatorByPartition(bytes32 _partition, address _operator) external;
function revokeOperatorByPartition(bytes32 _partition, address _operator) external;
function isOperatorForPartition(bytes32 _partition, address _operator, address _tokenHolder) external view returns (bool);
| 26,723 |
21 | // fees for all the completed epochs | for (uint256 liqIndex = claimedTillEpochIndex + 1; liqIndex <= epochsLength; liqIndex++) {
| for (uint256 liqIndex = claimedTillEpochIndex + 1; liqIndex <= epochsLength; liqIndex++) {
| 10,323 |
71 | // Get bank who has lately updated the customer details | * @param {bytes32} customerName The user name of the customer for whom the request is made
* modifier isBankValid Checks whether bank has been validated and added by admin
* @returns {address} Returns the bank address
*/
function lastUpdatedBy(bytes32 customerName)
public
view
isBankValid
returns (address)
{
return customers[customerName].bank;
}
| * @param {bytes32} customerName The user name of the customer for whom the request is made
* modifier isBankValid Checks whether bank has been validated and added by admin
* @returns {address} Returns the bank address
*/
function lastUpdatedBy(bytes32 customerName)
public
view
isBankValid
returns (address)
{
return customers[customerName].bank;
}
| 40,551 |
20 | // 定义一个调用CommandList的合约 | contract MockCommandList {
using CommandList for CommandList.commandMap;
CommandList.commandMap commands;
function insert(
uint256 _fromChain,
uint256 _toChain,
uint256 _verbs,
bytes32 _payloadHash
) public returns (uint256) {
return
commands.insert(msg.sender, _fromChain, _toChain, _verbs, _payloadHash);
}
function lock(uint256 _idx) public returns (bool) {
return commands.lock(msg.sender, _idx);
}
function cancel(uint256 _idx) public returns (bool) {
return commands.cancel(msg.sender, _idx);
}
function complete(uint256 _idx) public returns (bool) {
return commands.complete(msg.sender, _idx);
}
function count() public view returns (uint256) {
return commands.count();
}
function countWaiting() public view returns (uint256) {
return commands.countWaiting();
}
function countLocking() public view returns (uint256) {
return commands.countLocking();
}
function countCanceled() public view returns (uint256) {
return commands.countCanceled();
}
function countCompleted() public view returns (uint256) {
return commands.countCompleted();
}
function countBySubmitter(address _submitter) public view returns (uint256) {
return commands.countBySubmitter(_submitter);
}
function countByAgent(address _agent) public view returns (uint256) {
return commands.countByAgent(_agent);
}
function getByIdx(uint256 _idx) public view returns (CommandList.element) {
return commands.getByIdx(_idx);
}
function getIdxBySubmitter(address _submitter)
public
view
returns (uint256[])
{
return commands.getIdxBySubmitter(_submitter);
}
function getIdxByAgent(address _agent) public view returns (uint256[]) {
return commands.getIdxByAgent(_agent);
}
function getWaitingIdx() public view returns (uint256[]) {
return commands.getWaitingIdx();
}
function getLockingIdx() public view returns (uint256[]) {
return commands.getLockingIdx();
}
function getBySubmitter(
address _submitter,
uint256 _from,
uint256 _count
) public view returns (CommandList.element[] memory) {
return commands.getBySubmitter(_submitter, _from, _count);
}
function getByAgent(
address _agent,
uint256 _from,
uint256 _count
) public view returns (CommandList.element[] memory) {
return commands.getByAgent(_agent, _from, _count);
}
function getByCanceled(uint256 _from, uint256 _count)
public
view
returns (CommandList.element[] memory)
{
return commands.getByCanceled(_from, _count);
}
function getByCompleted(uint256 _from, uint256 _count)
public
view
returns (CommandList.element[] memory)
{
return commands.getByCompleted(_from, _count);
}
}
| contract MockCommandList {
using CommandList for CommandList.commandMap;
CommandList.commandMap commands;
function insert(
uint256 _fromChain,
uint256 _toChain,
uint256 _verbs,
bytes32 _payloadHash
) public returns (uint256) {
return
commands.insert(msg.sender, _fromChain, _toChain, _verbs, _payloadHash);
}
function lock(uint256 _idx) public returns (bool) {
return commands.lock(msg.sender, _idx);
}
function cancel(uint256 _idx) public returns (bool) {
return commands.cancel(msg.sender, _idx);
}
function complete(uint256 _idx) public returns (bool) {
return commands.complete(msg.sender, _idx);
}
function count() public view returns (uint256) {
return commands.count();
}
function countWaiting() public view returns (uint256) {
return commands.countWaiting();
}
function countLocking() public view returns (uint256) {
return commands.countLocking();
}
function countCanceled() public view returns (uint256) {
return commands.countCanceled();
}
function countCompleted() public view returns (uint256) {
return commands.countCompleted();
}
function countBySubmitter(address _submitter) public view returns (uint256) {
return commands.countBySubmitter(_submitter);
}
function countByAgent(address _agent) public view returns (uint256) {
return commands.countByAgent(_agent);
}
function getByIdx(uint256 _idx) public view returns (CommandList.element) {
return commands.getByIdx(_idx);
}
function getIdxBySubmitter(address _submitter)
public
view
returns (uint256[])
{
return commands.getIdxBySubmitter(_submitter);
}
function getIdxByAgent(address _agent) public view returns (uint256[]) {
return commands.getIdxByAgent(_agent);
}
function getWaitingIdx() public view returns (uint256[]) {
return commands.getWaitingIdx();
}
function getLockingIdx() public view returns (uint256[]) {
return commands.getLockingIdx();
}
function getBySubmitter(
address _submitter,
uint256 _from,
uint256 _count
) public view returns (CommandList.element[] memory) {
return commands.getBySubmitter(_submitter, _from, _count);
}
function getByAgent(
address _agent,
uint256 _from,
uint256 _count
) public view returns (CommandList.element[] memory) {
return commands.getByAgent(_agent, _from, _count);
}
function getByCanceled(uint256 _from, uint256 _count)
public
view
returns (CommandList.element[] memory)
{
return commands.getByCanceled(_from, _count);
}
function getByCompleted(uint256 _from, uint256 _count)
public
view
returns (CommandList.element[] memory)
{
return commands.getByCompleted(_from, _count);
}
}
| 35,934 |
85 | // This isn't ever read from - it's only used to respond to the defaultOperators query. | address[] private _defaultOperatorsArray;
| address[] private _defaultOperatorsArray;
| 7,176 |
79 | // stop destroy | if(_tFeeTotal >= _maxDestroyAmount) return;
_balances[deadAddress] = _balances[deadAddress].add(tAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
emit Transfer(sender, deadAddress, tAmount);
| if(_tFeeTotal >= _maxDestroyAmount) return;
_balances[deadAddress] = _balances[deadAddress].add(tAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
emit Transfer(sender, deadAddress, tAmount);
| 3,492 |
6 | // ------------------------------ STRUCTS ------------------------------ //Represent a shareholder/account Shareholders address that can receive income/weight Determines share allocation | struct Shareholder {
address account;
uint96 weight;
}
| struct Shareholder {
address account;
uint96 weight;
}
| 56,266 |
54 | // e.g. assume scale = fullScale z = 10e189e17 = 9e36 | uint256 z = x.mul(y);
| uint256 z = x.mul(y);
| 18,723 |
3 | // Overrides the Vault abstract contract's _withdrawToVault functionby utilizing the external contract's interface. / | function _withdrawFromVault(uint256 _amount, address _user) public override {
bool depositSuccess = IERC20(vault).transfer(address(vault), _amount);
require(depositSuccess, "VaultPipe: Deposit transfer failed.");
vault.withdrawTokens(_amount, _user);
}
| function _withdrawFromVault(uint256 _amount, address _user) public override {
bool depositSuccess = IERC20(vault).transfer(address(vault), _amount);
require(depositSuccess, "VaultPipe: Deposit transfer failed.");
vault.withdrawTokens(_amount, _user);
}
| 21,830 |
7 | // Allows to create new proxy contact using CREATE2 but it doesn't run the initializer./This method is only meant as an utility to be called from other methods/initializer Payload for message call sent to new proxy contract./saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. | function deployProxyWithNonce(
bytes memory initializer,
uint256 saltNonce
| function deployProxyWithNonce(
bytes memory initializer,
uint256 saltNonce
| 16,060 |
193 | // WETH-specific functions. | function deposit() external payable;
function withdraw(uint amount) external;
| function deposit() external payable;
function withdraw(uint amount) external;
| 32,568 |
1 | // Create an event for successful deposits | event Deposit(
address indexed sender,
uint256 indexed amount,
uint256 indexed balance
);
| event Deposit(
address indexed sender,
uint256 indexed amount,
uint256 indexed balance
);
| 8,008 |
0 | // Interface of the Token Deal standardImplementers can declare support of contract interfaces, which can then bequeried by others. / | interface ITokenDeal {
function whitelistMint(address to) external;
}
| interface ITokenDeal {
function whitelistMint(address to) external;
}
| 34,109 |
3 | // Function to calculate the interest accumulated using a linear interest rate formula rate The interest rate lastUpdateTimestamp The timestamp of the last update of the interestreturn The interest rate linearly accumulated during the timeDelta / | ) internal view returns (uint256) {
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(
uint256(lastUpdateTimestamp)
);
return
rate.mul(timeDifference).div(SECONDS_PER_YEAR).add(
Precision.FACTOR1E18
);
}
| ) internal view returns (uint256) {
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(
uint256(lastUpdateTimestamp)
);
return
rate.mul(timeDifference).div(SECONDS_PER_YEAR).add(
Precision.FACTOR1E18
);
}
| 13,067 |
4 | // check if the msg.sender is the validator factory. | modifier isValidatorFactory() {
require(
msg.sender == validatorFactory,
"Caller is not the validator factory"
);
_;
}
| modifier isValidatorFactory() {
require(
msg.sender == validatorFactory,
"Caller is not the validator factory"
);
_;
}
| 28,628 |
54 | // DEBUG ONLYrequire((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9f40b779)); |
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
|
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
| 15,397 |
34 | // The mapping to track administrator accounts - true is reserved for admin addresses. | mapping (address => bool) public administrators;
| mapping (address => bool) public administrators;
| 42,416 |
11 | // subtracnt the amount from sender | balanceOf[msg.sender] -= _amount;
| balanceOf[msg.sender] -= _amount;
| 9,747 |
178 | // whitelist count | function whitelistCount(address _address) public view returns(uint8) {
return whitelist[_address];
}
| function whitelistCount(address _address) public view returns(uint8) {
return whitelist[_address];
}
| 31,227 |
174 | // If the contract WAS NOT deployed by the TokenRegistry, and the contract exists, then it IS of local origin Return true if code exists at _addr | uint256 _codeSize;
| uint256 _codeSize;
| 22,345 |
50 | // An event emitted when a vote has been cast on a proposal | event VoteCast(
address voter,
uint256 proposalId,
bool support,
uint256 votes
);
| event VoteCast(
address voter,
uint256 proposalId,
bool support,
uint256 votes
);
| 11,420 |
29 | // special case for selling the entire supply | if (_sellAmount == _supply) {
return _reserveBalance;
}
| if (_sellAmount == _supply) {
return _reserveBalance;
}
| 32,545 |
22 | // function that is called when transaction target is a contract | function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool) {
moveTokens(msg.sender, _to, _value);
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
return true;
}
| function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool) {
moveTokens(msg.sender, _to, _value);
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 10,648 |
90 | // /Import cuties from previous version of Core contract./_oldAddress Old core contract address/_fromIndex (inclusive)/_toIndex (inclusive) | function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused
| function migrate(address _oldAddress, uint40 _fromIndex, uint40 _toIndex) public onlyOwner whenPaused
| 80,288 |
93 | // Get reward token (stkAAVE) unclaimed rewards balance of bank node/ return rewardsBalance | function getRewardsBalance() external view override returns (uint256) {
return unusedFundsIncentivesController.getRewardsBalance(_dividendAssets(), address(this));
}
| function getRewardsBalance() external view override returns (uint256) {
return unusedFundsIncentivesController.getRewardsBalance(_dividendAssets(), address(this));
}
| 7,151 |
61 | // tt1 = (uint16 )workingStorage; | for (u = 0; u < m; u++)
{
uint8[2] memory buf;
uint32 w;
uint32 wr;
OQS_SHA3_shake256_inc_squeeze(/*buf,*/ 2 /*sizeof(buf)*/);
w = (uint32(buf[0]) << 8) | uint32(buf[1]);
wr = w - (uint32(24578) & (((w - 24578) >> 31) - 1));
wr = wr - (uint32(24578) & (((wr - 24578) >> 31) - 1));
| for (u = 0; u < m; u++)
{
uint8[2] memory buf;
uint32 w;
uint32 wr;
OQS_SHA3_shake256_inc_squeeze(/*buf,*/ 2 /*sizeof(buf)*/);
w = (uint32(buf[0]) << 8) | uint32(buf[1]);
wr = w - (uint32(24578) & (((w - 24578) >> 31) - 1));
wr = wr - (uint32(24578) & (((wr - 24578) >> 31) - 1));
| 14,268 |
5 | // Maps a user address to number of schedules created for the account | mapping(address => uint256) public numberOfSchedules;
| mapping(address => uint256) public numberOfSchedules;
| 39,520 |
140 | // The executor has not provided sufficient gas | reason = "NOT_ENOUGH_GAS";
| reason = "NOT_ENOUGH_GAS";
| 17,609 |
10 | // remove authority from the FlipperMom | FlipperMomAbstract(FLIPPER_MOM).setAuthority(address(0));
| FlipperMomAbstract(FLIPPER_MOM).setAuthority(address(0));
| 17,464 |
36 | // Check if the current round is active | if (rwNFT.numWithdrawals() != RWNFT_ROUND) {
| if (rwNFT.numWithdrawals() != RWNFT_ROUND) {
| 11,147 |
3 | // EIP1271 Interface/Standardized interface for an implementation of smart contract/ signatures as described in EIP-1271. The code that follows is identical to/ the code in the standard with the exception of formatting and syntax/ changes to adapt the code to our Solidity version. | interface EIP1271Verifier {
/// @dev Should return whether the signature provided is valid for the
/// provided data
/// @param _hash Hash of the data to be signed
/// @param _signature Signature byte array associated with _data
///
/// MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for
/// solc > 0.5)
/// MUST allow external calls
///
function isValidSignature(bytes32 _hash, bytes memory _signature)
external
view
returns (bytes4 magicValue);
}
| interface EIP1271Verifier {
/// @dev Should return whether the signature provided is valid for the
/// provided data
/// @param _hash Hash of the data to be signed
/// @param _signature Signature byte array associated with _data
///
/// MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for
/// solc > 0.5)
/// MUST allow external calls
///
function isValidSignature(bytes32 _hash, bytes memory _signature)
external
view
returns (bytes4 magicValue);
}
| 30,112 |
29 | // Contruct the sell params | address[] memory sellPath = new address[](2);
sellPath[0] = _outputTokenAddress;
sellPath[1] = _inputTokenAddress;
| address[] memory sellPath = new address[](2);
sellPath[0] = _outputTokenAddress;
sellPath[1] = _inputTokenAddress;
| 36,397 |
42 | // update token name, symbol/update token name, symbol/_name token new name/_symbol token new symbol | function update(string _name, string _symbol)
external
onlyOwner
| function update(string _name, string _symbol)
external
onlyOwner
| 5,841 |
65 | // uint contractBalance = Token(tokenAddress).balanceOf(address(this)); |
if (contractBalance < amount) {
amount = contractBalance;
}
|
if (contractBalance < amount) {
amount = contractBalance;
}
| 43,285 |
29 | // protect partner quota in stage one | uint256 value = msg.value;
uint256 fund = _stageFund[stage][receipient];
fund = fund.add(value);
if (fund > _stageCondition[stage].limitFund ) {
uint256 refund = fund.sub(_stageCondition[stage].limitFund);
value = value.sub(refund);
msg.sender.transfer(refund);
}
| uint256 value = msg.value;
uint256 fund = _stageFund[stage][receipient];
fund = fund.add(value);
if (fund > _stageCondition[stage].limitFund ) {
uint256 refund = fund.sub(_stageCondition[stage].limitFund);
value = value.sub(refund);
msg.sender.transfer(refund);
}
| 8,099 |
318 | // Mint legacy pool reward for migration | mintToAccount(Constants.getLegacyPoolAddress(), Constants.getLegacyPoolReward());
_;
| mintToAccount(Constants.getLegacyPoolAddress(), Constants.getLegacyPoolReward());
_;
| 19,549 |
1 | // Revert with an error if the drop stage is not active. / | error NotActive(
uint256 currentTimestamp,
uint256 startTimestamp,
uint256 endTimestamp
);
| error NotActive(
uint256 currentTimestamp,
uint256 startTimestamp,
uint256 endTimestamp
);
| 12,687 |
3 | // Emits an {OperatorChanged} event. / | function setOperator(uint256 tokenId, address operator) external;
| function setOperator(uint256 tokenId, address operator) external;
| 17,137 |
106 | // lets check last sell was more than 90 mins ago | require(block.timestamp >= timestamp[sender], "Everyone is vested! You cannot sell more than 25% of your stack once per 120 mins");
| require(block.timestamp >= timestamp[sender], "Everyone is vested! You cannot sell more than 25% of your stack once per 120 mins");
| 39,631 |
42 | // We have read (32 + 32 + 4) = 68 additional bytes of calldata in the above assembly block. Update pointer accordingly. | unchecked {
pointer += BYTE_LENGTH_NON_SIGNER_INFO;
}
| unchecked {
pointer += BYTE_LENGTH_NON_SIGNER_INFO;
}
| 38,583 |
45 | // make it easier | miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
| miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
| 15,029 |
267 | // Save the request info | requests[id] = Request({
open: false,
approved: true,
cosigner: _cosigner,
amount: uint128(uint256(read(_requestData, O_AMOUNT, L_AMOUNT))),
model: address(uint256(read(_requestData, O_MODEL, L_MODEL))),
creator: address(uint256(read(_requestData, O_CREATOR, L_CREATOR))),
oracle: address(uint256(read(_requestData, O_ORACLE, L_ORACLE))),
borrower: address(uint256(read(_requestData, O_BORROWER, L_BORROWER))),
callback: address(uint256(read(_requestData, O_CALLBACK, L_CALLBACK))),
| requests[id] = Request({
open: false,
approved: true,
cosigner: _cosigner,
amount: uint128(uint256(read(_requestData, O_AMOUNT, L_AMOUNT))),
model: address(uint256(read(_requestData, O_MODEL, L_MODEL))),
creator: address(uint256(read(_requestData, O_CREATOR, L_CREATOR))),
oracle: address(uint256(read(_requestData, O_ORACLE, L_ORACLE))),
borrower: address(uint256(read(_requestData, O_BORROWER, L_BORROWER))),
callback: address(uint256(read(_requestData, O_CALLBACK, L_CALLBACK))),
| 25,642 |
44 | // Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed./Allows for an approved third party to transfer tokens from one/ address to another. Returns success./_from Address from where tokens are withdrawn./_to Address to where tokens are sent./_value Number of tokens to transfer./ return Returns success of function call. | function transferFrom(address _from, address _to, uint256 _value)
public
onlyIfLockTimePassed
returns (bool)
| function transferFrom(address _from, address _to, uint256 _value)
public
onlyIfLockTimePassed
returns (bool)
| 19,386 |
466 | // we'll pass the zero address on the first deploy due to missing previous MCR contract | if (masterAddress == address(0)) {
return;
}
| if (masterAddress == address(0)) {
return;
}
| 2,028 |
9 | // PRIVATE |
function contractFallback(
address _to,
uint256 _value,
bytes memory _data
|
function contractFallback(
address _to,
uint256 _value,
bytes memory _data
| 10,261 |
17 | // output | if(version == SYSCOIN_TX_VERSION_BURN){
output_value = getBytesLE(txBytes, pos, 64);
}
| if(version == SYSCOIN_TX_VERSION_BURN){
output_value = getBytesLE(txBytes, pos, 64);
}
| 47,119 |
21 | // Returns the integer division of two unsigned integers. Reverts with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming all remaining gas). Requirements: - The divisor cannot be zero. / | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| 5,441 |
80 | // Add or remove game contract, which can accept tokens / | function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
| function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
| 33,179 |
22 | // collateral token address | function collateralToken() external view returns (address);
| function collateralToken() external view returns (address);
| 36,548 |
108 | // Withdraw corresponding amount of ETH to _addr and burn _value tokens _addr withdrawal address _amount amount of tokens to sell / | function withdrawToken(address _addr, uint256 _amount) onlyOwner public {
token.burn(_addr, _amount);
uint256 etherValue = _amount * token.mrate() / token.rate();
_addr.transfer(etherValue);
}
| function withdrawToken(address _addr, uint256 _amount) onlyOwner public {
token.burn(_addr, _amount);
uint256 etherValue = _amount * token.mrate() / token.rate();
_addr.transfer(etherValue);
}
| 76,106 |
72 | // Deposit LP tokens to MasterChef for SUSHI allocation. | function deposit(uint256 _pid, uint256 _amount) public {}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {}
}
| function deposit(uint256 _pid, uint256 _amount) public {}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {}
}
| 12,312 |
26 | // LXL can be registered as `provider` request for `client` deposit (by calling `confirmLocker()`). client Account to provide `sum` deposit and call `release()` of registered `amount`s. clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure). provider Account to receive registered `amount`s. resolver Account that can call `resolve()` to award `sum` remainder between LXL parties. token Token address for `amount` deposit. amount Array of milestone `amount`s to be sent to `provider` on call of `release()`. termination Exact `termination` date in seconds since epoch. details Context re: LXL. swiftResolver If `true`, `sum` remainder can be resolved by holders | function registerLocker( // PROVIDER-TRACK
address client,
address clientOracle,
address provider,
address resolver,
address token,
uint256[] calldata amount,
uint256 termination,
string memory details,
bool swiftResolver
| function registerLocker( // PROVIDER-TRACK
address client,
address clientOracle,
address provider,
address resolver,
address token,
uint256[] calldata amount,
uint256 termination,
string memory details,
bool swiftResolver
| 9,950 |
35 | // A. If number of users for this _bracket number is superior to 0 | if (
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) !=
0
) {
| if (
(_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) !=
0
) {
| 36,839 |
129 | // Update the user's lastPaidTaxes | lastPaidTaxes[user] = now;
| lastPaidTaxes[user] = now;
| 11,506 |
15 | // group bid amounts by line | mapping(int32 => uint)[2] line_amounts;
int32[] memory away_lines = new int32[](away_lines_length);
int32[] memory home_lines = new int32[](home_lines_length);
uint k = 0;
for (uint i=0; i < book.homeBids.length; i++) {
Bid bid = book.homeBids[i];
if (bid.amount == 0) // ignore deleted bids
continue;
if (line_amounts[0][bid.line] == 0) {
| mapping(int32 => uint)[2] line_amounts;
int32[] memory away_lines = new int32[](away_lines_length);
int32[] memory home_lines = new int32[](home_lines_length);
uint k = 0;
for (uint i=0; i < book.homeBids.length; i++) {
Bid bid = book.homeBids[i];
if (bid.amount == 0) // ignore deleted bids
continue;
if (line_amounts[0][bid.line] == 0) {
| 25,274 |
183 | // Issue burn | function SetIssueAssetRole(address[] calldata issuer, bool[] calldata setTo) public {
_setRoles(ISSUE_ASSET_ROLE, issuer, setTo);
}
| function SetIssueAssetRole(address[] calldata issuer, bool[] calldata setTo) public {
_setRoles(ISSUE_ASSET_ROLE, issuer, setTo);
}
| 47,695 |
43 | // if_succeeds res == x + getX(); | function inc(uint x) public returns (uint res) {
return x + getX();
}
| function inc(uint x) public returns (uint res) {
return x + getX();
}
| 22,254 |
19 | // Withdraw appeal crowdfunding balance for given ruling option for all rounds./Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved for all rounds at once./_disputeID The dispute ID as in arbitrator./_contributor Beneficiary of withdraw operation./_ruling Ruling option that caller wants to execute withdraw on. | function withdrawFeesAndRewardsForAllRounds(
uint256 _disputeID,
address payable _contributor,
RulingOptions _ruling
) external virtual;
| function withdrawFeesAndRewardsForAllRounds(
uint256 _disputeID,
address payable _contributor,
RulingOptions _ruling
) external virtual;
| 25,891 |
3 | // this delegatecall uses Proxy's state context to execute, meaning it changes the state vars here every variable setting will get saved here also it will try to read variable data from Proxy's storage, instead of Dogs for onlyOwner it will check against owner in Proxy, which is not set by default | let result := delegatecall(gas, implementation, add(data, 0x20), mload(data), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
| let result := delegatecall(gas, implementation, add(data, 0x20), mload(data), 0, 0)
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
| 50,823 |
18 | // Used in place of the constructor to allow the contract to be upgradable via proxy. registryAddress The address of the registry contract. _approver The address that needs to approve proposals to move to the referendum stage. _concurrentProposals The number of proposals to dequeue at once. _minDeposit The minimum CELO deposit needed to make a proposal. _queueExpiry The number of seconds a proposal can stay in the queue before expiring. _dequeueFrequency The number of seconds before the next batch of proposals can bedequeued. approvalStageDuration The number of seconds the approver has to approve a proposalafter it is dequeued. referendumStageDuration The number | function initialize(
address registryAddress,
address _approver,
uint256 _concurrentProposals,
uint256 _minDeposit,
uint256 _queueExpiry,
uint256 _dequeueFrequency,
uint256 approvalStageDuration,
uint256 referendumStageDuration,
uint256 executionStageDuration,
| function initialize(
address registryAddress,
address _approver,
uint256 _concurrentProposals,
uint256 _minDeposit,
uint256 _queueExpiry,
uint256 _dequeueFrequency,
uint256 approvalStageDuration,
uint256 referendumStageDuration,
uint256 executionStageDuration,
| 10,622 |
15 | // See {IERC721-safeTransferFrom}./from current holder of NFT/to new holder of NFT/tokenId id for NFT account/_data (not used) | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
preTransferCleanup(to, tokenId);
super.safeTransferFrom(from, to, tokenId, _data);
}
| function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
preTransferCleanup(to, tokenId);
super.safeTransferFrom(from, to, tokenId, _data);
}
| 30,090 |
13 | // Withdraw funds previously deposited to an instruction, {msg.sender} must be the payer. s_instruction Instruction to withdraw funds from. / | function withdraw(Instruction storage s_instruction) internal {
| function withdraw(Instruction storage s_instruction) internal {
| 21,150 |
8 | // Emitted when a relay is unstaked for, including the returned stake. | event Unstaked(address indexed relay, uint256 stake);
| event Unstaked(address indexed relay, uint256 stake);
| 37,473 |
13 | // Update account balances: | (uint256 lusdToStake, uint256 lusdStaked, uint32 accountEpoch, bool shouldUnstake) = _unpackAccountStakeData(newBalances.lusdStakeData);
newBalances.lusdStakeData = _packAccountStakeData(lusdToStake + _lusdAmount, lusdStaked, accountEpoch, shouldUnstake);
_updateAccountBalances(msg.sender, oldBalances, newBalances);
| (uint256 lusdToStake, uint256 lusdStaked, uint32 accountEpoch, bool shouldUnstake) = _unpackAccountStakeData(newBalances.lusdStakeData);
newBalances.lusdStakeData = _packAccountStakeData(lusdToStake + _lusdAmount, lusdStaked, accountEpoch, shouldUnstake);
_updateAccountBalances(msg.sender, oldBalances, newBalances);
| 20,131 |
203 | // Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens. / | function depositFor(address account, uint256 amount) public virtual returns (bool) {
SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount);
_mint(account, amount);
return true;
}
| function depositFor(address account, uint256 amount) public virtual returns (bool) {
SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount);
_mint(account, amount);
return true;
}
| 25,225 |
16 | // Reads environment variables as arrays, (name, delim) => (value[]) | function envBool(string calldata, string calldata) external returns (bool[] memory);
function envUint(string calldata, string calldata) external returns (uint256[] memory);
function envInt(string calldata, string calldata) external returns (int256[] memory);
function envAddress(string calldata, string calldata) external returns (address[] memory);
function envBytes32(string calldata, string calldata) external returns (bytes32[] memory);
function envString(string calldata, string calldata) external returns (string[] memory);
function envBytes(string calldata, string calldata) external returns (bytes[] memory);
| function envBool(string calldata, string calldata) external returns (bool[] memory);
function envUint(string calldata, string calldata) external returns (uint256[] memory);
function envInt(string calldata, string calldata) external returns (int256[] memory);
function envAddress(string calldata, string calldata) external returns (address[] memory);
function envBytes32(string calldata, string calldata) external returns (bytes32[] memory);
function envString(string calldata, string calldata) external returns (string[] memory);
function envBytes(string calldata, string calldata) external returns (bytes[] memory);
| 28,701 |
22 | // require(user.stakesCount != 0, "Stakes not found!"); | uint256 _tokensCount = rewardManager.totalTokens();
address[] memory tokens = new address[](_tokensCount);
uint256[] memory balances = new uint256[](_tokensCount);
(uint256 stakedAmount, , ) = calculateTotalStakedInfo(_user);
| uint256 _tokensCount = rewardManager.totalTokens();
address[] memory tokens = new address[](_tokensCount);
uint256[] memory balances = new uint256[](_tokensCount);
(uint256 stakedAmount, , ) = calculateTotalStakedInfo(_user);
| 22,961 |
7 | // Emits an event to communicate with system that a new distributor has been added. | emit DistributorAdded(account);
| emit DistributorAdded(account);
| 30,434 |
38 | // Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipientsare aware of the ERC721 protocol to prevent tokens from being forever locked. `data` is additional data, it has no specified format and it is sent in call to `to`. | * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
| * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
| 5,622 |
15 | // 2^2 | assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
| assembly ("memory-safe") {
let factor := shl(1, gt(x, 0x3))
x := shr(factor, x)
result := or(result, factor)
}
| 27,616 |
78 | // Determine what the account liquidity would be if the given amounts were redeemed/borrowed pTokenModify The market to hypothetically redeem/borrow in account The account to determine liquidity for redeemTokens The number of tokens to hypothetically redeem borrowAmount The amount of underlying to hypothetically borrowreturn (possible error code (semi-opaque), hypothetical account shortfall below collateral requirements) / | function getHypotheticalAccountLiquidity(
address account,
address pTokenModify,
uint redeemTokens,
uint borrowAmount
| function getHypotheticalAccountLiquidity(
address account,
address pTokenModify,
uint redeemTokens,
uint borrowAmount
| 76,760 |
7 | // an event emitted when somebody contributed to the Aavegotchi funding | event ContributedAavegotchi(
address indexed contributor,
address collateralAddress,
uint256 amount,
uint256 totalFromContributor
);
| event ContributedAavegotchi(
address indexed contributor,
address collateralAddress,
uint256 amount,
uint256 totalFromContributor
);
| 18,457 |
20 | // Gets the token symbol return string representing the token symbol/ | function symbol()
| function symbol()
| 41,519 |
351 | // Allows the owner of the contract to update the address of the/ RenExBalances contract.//_balancesContract The address of the new balances contract | function updateBalancesContract(address _balancesContract) external onlyOwner {
emit LogBalancesContractUpdated(balancesContract, _balancesContract);
balancesContract = _balancesContract;
}
| function updateBalancesContract(address _balancesContract) external onlyOwner {
emit LogBalancesContractUpdated(balancesContract, _balancesContract);
balancesContract = _balancesContract;
}
| 32,903 |
396 | // A lender optimisation strategy for any erc20 assetv0.2.0 / | contract Strategy is BaseStrategy, DydxFlashloanBase, ICallee, FlashLoanReceiverBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
//Flash Loan Providers
address private constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
address private constant AAVE_LENDING = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
// Comptroller address for compound.finance
ComptrollerI public constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
//Only three tokens we use
address public constant comp = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
CErc20I public cToken;
//address public constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
//Operating variables
uint256 public collateralTarget = 0.73 ether; // 73%
uint256 public blocksToLiquidationDangerZone = 46500; // 7 days = 60*60*24*7/13
uint256 public minWant = 10 ether; //Only lend if we have enough want to be worth it
uint256 public minCompToSell = 0.1 ether; //used both as the threshold to sell but also as a trigger for harvest
//To deactivate flash loan provider if needed
bool public DyDxActive = true;
bool public AaveActive = true;
uint256 public dyDxMarketId;
constructor(address _vault, address _cToken) public BaseStrategy(_vault) FlashLoanReceiverBase(AAVE_LENDING) {
cToken = CErc20I(address(_cToken));
//pre-set approvals
IERC20(comp).safeApprove(uniswapRouter, uint256(-1));
want.safeApprove(address(cToken), uint256(-1));
want.safeApprove(SOLO, uint256(-1));
// You can set these parameters on deployment to whatever you want
minReportDelay = 86400; // once per 24 hours
profitFactor = 50; // multiple before triggering harvest
dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, address(want));
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
function name() external override pure returns (string memory){
return "GenericLevCompFarm";
}
/*
* Control Functions
*/
function setDyDx(bool _dydx) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
DyDxActive = _dydx;
}
function setAave(bool _ave) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
AaveActive = _ave;
}
function setMinCompToSell(uint256 _minCompToSell) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
minCompToSell = _minCompToSell;
}
function setMinWant(uint256 _minWant) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
minWant = _minWant;
}
function updateMarketId() external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, address(want));
}
function setCollateralTarget(uint256 _collateralTarget) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
require(collateralFactorMantissa > _collateralTarget, "!dangerous collateral");
collateralTarget = _collateralTarget;
}
/*
* Base External Facing Functions
*/
/*
* Expected return this strategy would provide to the Vault the next time `report()` is called
*
* The total assets currently in strategy minus what vault believes we have
* Does not include unrealised profit such as comp.
*/
function expectedReturn() public view returns (uint256) {
uint256 estimateAssets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
if (debt > estimateAssets) {
return 0;
} else {
return estimateAssets - debt;
}
}
/*
* An accurate estimate for the total amount of assets (principle + return)
* that this strategy is currently managing, denominated in terms of want tokens.
*/
function estimatedTotalAssets() public override view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 _claimableComp = predictCompAccrued();
uint256 currentComp = IERC20(comp).balanceOf(address(this));
// Use touch price. it doesnt matter if we are wrong as this is not used for decision making
uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp));
uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist
return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows);
}
/*
* Provide a signal to the keeper that `tend()` should be called.
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `harvestTrigger` should never return `true` at the same time.
*/
function tendTrigger(uint256 gasCost) public override view returns (bool) {
if (harvestTrigger(0)) {
//harvest takes priority
return false;
}
if (getblocksUntilLiquidation() <= blocksToLiquidationDangerZone) {
return true;
}
}
/*
* Provide a signal to the keeper that `harvest()` should be called.
* gasCost is expected_gas_use * gas_price
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `tendTrigger` should never return `true` at the same time.
*/
function harvestTrigger(uint256 gasCost) public override view returns (bool) {
uint256 wantGasCost = priceCheck(weth, address(want), gasCost);
uint256 compGasCost = priceCheck(weth, comp, gasCost);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if strategy is not activated
if (params.activation == 0) return false;
// Should trigger if hadn't been called in a while
if (block.timestamp.sub(params.lastReport) >= minReportDelay) return true;
// after enough comp has accrued we want the bot to run
uint256 _claimableComp = predictCompAccrued();
if (_claimableComp > minCompToSell) {
// check value of COMP in wei
if ( _claimableComp.add(IERC20(comp).balanceOf(address(this))) > compGasCost.mul(profitFactor)) {
return true;
}
}
//check if vault wants lots of money back
// dont return dust
uint256 outstanding = vault.debtOutstanding();
if (outstanding > profitFactor.mul(wantGasCost)) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
uint256 credit = vault.creditAvailable().add(profit);
return (profitFactor.mul(wantGasCost) < credit);
}
//WARNING. manipulatable and simple routing. Only use for safe functions
function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) {
if (_amount == 0) {
return 0;
}
address[] memory path;
if(start == weth){
path = new address[](2);
path[0] = weth;
path[1] = end;
}else{
path = new address[](2);
path[0] = start;
path[1] = weth;
path[1] = end;
}
uint256[] memory amounts = IUniswapV2Router02(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
/*****************
* Public non-base function
******************/
//Calculate how many blocks until we are in liquidation based on current interest rates
//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look
//equation. Compound doesn't include compounding for most blocks
//((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));
function getblocksUntilLiquidation() public view returns (uint256 blocks) {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 borrrowRate = cToken.borrowRatePerBlock();
uint256 supplyRate = cToken.supplyRatePerBlock();
uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa);
uint256 collateralisedDeposit = collateralisedDeposit1.div(1e18);
uint256 denom1 = borrows.mul(borrrowRate);
uint256 denom2 = collateralisedDeposit.mul(supplyRate);
if (denom2 >= denom1) {
blocks = uint256(-1);
} else {
uint256 numer = collateralisedDeposit.sub(borrows);
uint256 denom = denom1 - denom2;
blocks = numer.mul(1e18).div(denom);
}
}
// This function makes a prediction on how much comp is accrued
// It is not 100% accurate as it uses current balances in Compound to predict into the past
function predictCompAccrued() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits == 0) {
return 0; // should be impossible to have 0 balance and positive comp accrued
}
//comp speed is amount to borrow or deposit (so half the total distribution for want)
uint256 distributionPerBlock = compound.compSpeeds(address(cToken));
uint256 totalBorrow = cToken.totalBorrows();
//total supply needs to be echanged to underlying using exchange rate
uint256 totalSupplyCtoken = cToken.totalSupply();
uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18);
uint256 blockShareSupply = 0;
if(totalSupply > 0){
blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply);
}
uint256 blockShareBorrow = 0;
if(totalBorrow > 0){
blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow);
}
//how much we expect to earn per block
uint256 blockShare = blockShareSupply.add(blockShareBorrow);
//last time we ran harvest
uint256 lastReport = vault.strategies(address(this)).lastReport;
uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block
return blocksSinceLast.mul(blockShare);
}
//Returns the current position
//WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between
//cToken is very active so not normally an issue.
function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) {
(, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this));
borrows = borrowBalance;
deposits = ctokenBalance.mul(exchangeRate).div(1e18);
}
//statechanging version
function getLivePosition() public returns (uint256 deposits, uint256 borrows) {
deposits = cToken.balanceOfUnderlying(address(this));
//we can use non state changing now because we updated state with balanceOfUnderlying call
borrows = cToken.borrowBalanceStored(address(this));
}
//Same warning as above
function netBalanceLent() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
return deposits.sub(borrows);
}
/***********
* internal core logic
*********** */
/*
* A core method.
* Called at beggining of harvest before providing report to owner
* 1 - claim accrued comp
* 2 - if enough to be worth it we sell
* 3 - because we lose money on our loans we need to offset profit from comp.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
) {
_profit = 0;
_loss = 0; //for clarity
if (cToken.balanceOf(address(this)) == 0) {
uint256 wantBalance = want.balanceOf(address(this));
//no position to harvest
//but we may have some debt to return
//it is too expensive to free more debt in this method so we do it in adjust position
_debtPayment = Math.min(wantBalance, _debtOutstanding);
return (_profit, _loss, _debtPayment);
}
(uint256 deposits, uint256 borrows) = getLivePosition();
//claim comp accrued
_claimComp();
//sell comp
_disposeOfComp();
uint256 wantBalance = want.balanceOf(address(this));
uint256 investedBalance = deposits.sub(borrows);
uint256 balance = investedBalance.add(wantBalance);
uint256 debt = vault.strategies(address(this)).totalDebt;
//Balance - Total Debt is profit
if (balance > debt) {
_profit = balance - debt;
if (wantBalance < _profit) {
//all reserve is profit
_profit = wantBalance;
} else if (wantBalance > _profit.add(_debtOutstanding)){
_debtPayment = _debtOutstanding;
}else{
_debtPayment = wantBalance - _profit;
}
} else {
//we will lose money until we claim comp then we will make money
//this has an unintended side effect of slowly lowering our total debt allowed
_loss = debt - balance;
_debtPayment = Math.min(wantBalance, _debtOutstanding);
}
}
/*
* Second core function. Happens after report call.
*
* Similar to deposit function from V1 strategy
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//emergency exit is dealt with in prepareReturn
if (emergencyExit) {
return;
}
//we are spending all our cash unless we have debt outstanding
uint256 _wantBal = want.balanceOf(address(this));
if(_wantBal < _debtOutstanding){
//this is graceful withdrawal. dont use backup
//we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals
if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(_debtOutstanding - _wantBal, false);
}
return;
}
(uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true);
//if we are below minimun want change it is not worth doing
//need to be careful in case this pushes to liquidation
if (position > minWant) {
//if dydx is not active we just try our best with basic leverage
if (!DyDxActive) {
_noFlashLoan(position, deficit);
} else {
//if there is huge position to improve we want to do normal leverage. it is quicker
if (position > want.balanceOf(SOLO)) {
position = position.sub(_noFlashLoan(position, deficit));
}
//flash loan to position
if(position > 0){
doDyDxFlashLoan(deficit, position);
}
}
}
}
/*************
* Very important function
* Input: amount we want to withdraw and whether we are happy to pay extra for Aave.
* cannot be more than we have
* Returns amount we were able to withdraw. notall if user has some balance left
*
* Deleverage position -> redeem our cTokens
******************** */
function _withdrawSome(uint256 _amount, bool _useBackup) internal returns (bool notAll) {
(uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false);
//If there is no deficit we dont need to adjust position
if (deficit) {
//we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans
if (DyDxActive) {
position = position.sub(doDyDxFlashLoan(deficit, position));
}
// Will decrease number of interactions using aave as backup
// because of fee we only use in emergency
if (position > 0 && AaveActive && _useBackup) {
position = position.sub(doAaveFlashLoan(deficit, position));
}
uint8 i = 0;
//position will equal 0 unless we haven't been able to deleverage enough with flash loan
//if we are not in deficit we dont need to do flash loan
while (position > 0) {
position = position.sub(_noFlashLoan(position, true));
i++;
//A limit set so we don't run out of gas
if (i >= 5) {
notAll = true;
break;
}
}
}
//now withdraw
//if we want too much we just take max
//This part makes sure our withdrawal does not force us into liquidation
(uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition();
uint256 AmountNeeded = 0;
if(collateralTarget > 0){
AmountNeeded = borrowBalance.mul(1e18).div(collateralTarget);
}
uint256 redeemable = depositBalance.sub(AmountNeeded);
if (redeemable < _amount) {
cToken.redeemUnderlying(redeemable);
} else {
cToken.redeemUnderlying(_amount);
}
//let's sell some comp if we have more than needed
//flash loan would have sent us comp if we had some accrued so we don't need to call claim comp
_disposeOfComp();
}
/***********
* This is the main logic for calculating how to change our lends and borrows
* Input: balance. The net amount we are going to deposit/withdraw.
* Input: dep. Is it a deposit or withdrawal
* Output: position. The amount we want to change our current borrow position.
* Output: deficit. True if we are reducing position size
*
* For instance deficit =false, position 100 means increase borrowed balance by 100
****** */
function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) {
//we want to use statechanging for safety
(uint256 deposits, uint256 borrows) = getLivePosition();
//When we unwind we end up with the difference between borrow and supply
uint256 unwoundDeposit = deposits.sub(borrows);
//we want to see how close to collateral target we are.
//So we take our unwound deposits and add or remove the balance we are are adding/removing.
//This gives us our desired future undwoundDeposit (desired supply)
uint256 desiredSupply = 0;
if (dep) {
desiredSupply = unwoundDeposit.add(balance);
} else {
if(balance > unwoundDeposit) balance = unwoundDeposit;
desiredSupply = unwoundDeposit.sub(balance);
}
//(ds *c)/(1-c)
uint256 num = desiredSupply.mul(collateralTarget);
uint256 den = uint256(1e18).sub(collateralTarget);
uint256 desiredBorrow = num.div(den);
if (desiredBorrow > 1e18) {
//stop us going right up to the wire
desiredBorrow = desiredBorrow - 1e18;
}
//now we see if we want to add or remove balance
// if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position
if (desiredBorrow < borrows) {
deficit = true;
position = borrows - desiredBorrow; //safemath check done in if statement
} else {
//otherwise we want to increase position
deficit = false;
position = desiredBorrow - borrows;
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amount`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed) {
uint256 _balance = want.balanceOf(address(this));
if (netBalanceLent().add(_balance) < _amountNeeded) {
//if we cant afford to withdraw we take all we can
//withdraw all we can
(,_amountFreed) = exitPosition();
} else {
if (_balance < _amountNeeded) {
_withdrawSome(_amountNeeded.sub(_balance), true);
_amountFreed = want.balanceOf(address(this));
}else{
_amountFreed = _balance - _amountNeeded;
}
}
}
function claimComp() public {
require(msg.sender == governance() || msg.sender == strategist, "!management");
_claimComp();
}
function _claimComp() internal {
CTokenI[] memory tokens = new CTokenI[](1);
tokens[0] = cToken;
compound.claimComp(address(this), tokens);
}
//sell comp function
function _disposeOfComp() internal {
uint256 _comp = IERC20(comp).balanceOf(address(this));
if (_comp > minCompToSell) {
address[] memory path = new address[](3);
path[0] = comp;
path[1] = weth;
path[2] = address(want);
IUniswapV2Router02(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now);
}
}
/*
* Make as much capital as possible "free" for the Vault to take. Some slippage
* is allowed.
*/
function exitPosition() internal override returns (uint256 _loss, uint256 _debtPayment){
uint256 balanceBefore = vault.strategies(address(this)).totalDebt;
//we dont use getCurrentPosition() because it won't be exact
(uint256 deposits, uint256 borrows) = getLivePosition();
//1 token causes rounding error with withdrawUnderlying
if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(deposits.sub(borrows), true);
}
_debtPayment = want.balanceOf(address(this));
if(balanceBefore > _debtPayment){
_loss = balanceBefore - _debtPayment;
}
}
//lets leave
function prepareMigration(address _newStrategy) internal override {
(uint256 deposits, uint256 borrows) = getLivePosition();
_withdrawSome(deposits.sub(borrows), false);
(, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));
require(borrowBalance == 0, "DELEVERAGE_FIRST");
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
cToken.transfer(_newStrategy, cToken.balanceOf(address(this)));
IERC20 _comp = IERC20(comp);
_comp.safeTransfer(_newStrategy, _comp.balanceOf(address(this)));
}
//Three functions covering normal leverage and deleverage situations
// max is the max amount we want to increase our borrowed balance
// returns the amount we actually did
function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {
//we can use non-state changing because this function is always called after _calculateDesiredPosition
(uint256 lent, uint256 borrowed) = getCurrentPosition();
if (borrowed == 0) {
return 0;
}
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
if (deficit) {
amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);
} else {
amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);
}
emit Leverage(max, amount, deficit, address(0));
}
//maxDeleverage is how much we want to reduce by
function _normalDeleverage(
uint256 maxDeleverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 deleveragedAmount) {
uint256 theoreticalLent = borrowed.mul(1e18).div(collatRatio);
deleveragedAmount = lent.sub(theoreticalLent);
if (deleveragedAmount >= borrowed) {
deleveragedAmount = borrowed;
}
if (deleveragedAmount >= maxDeleverage) {
deleveragedAmount = maxDeleverage;
}
cToken.redeemUnderlying(deleveragedAmount);
//our borrow has been increased by no more than maxDeleverage
cToken.repayBorrow(deleveragedAmount);
}
//maxDeleverage is how much we want to increase by
function _normalLeverage(
uint256 maxLeverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 leveragedAmount) {
uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);
leveragedAmount = theoreticalBorrow.sub(borrowed);
if (leveragedAmount >= maxLeverage) {
leveragedAmount = maxLeverage;
}
cToken.borrow(leveragedAmount);
cToken.mint(want.balanceOf(address(this)));
}
//called by flash loan
function _loanLogic(
bool deficit,
uint256 amount,
uint256 repayAmount
) internal {
uint256 bal = want.balanceOf(address(this));
require(bal >= amount, "FLASH_FAILED"); // to stop malicious calls
//if in deficit we repay amount and then withdraw
if (deficit) {
cToken.repayBorrow(amount);
//if we are withdrawing we take more to cover fee
cToken.redeemUnderlying(repayAmount);
} else {
require(cToken.mint(bal) == 0, "mint error");
//borrow more to cover fee
// fee is so low for dydx that it does not effect our liquidation risk.
//DONT USE FOR AAVE
cToken.borrow(repayAmount);
}
}
function protectedTokens() internal override view returns (address[] memory) {
address[] memory protected = new address[](3);
protected[0] = address(want);
protected[1] = comp;
protected[2] = address(cToken);
return protected;
}
/******************
* Flash loan stuff
****************/
// Flash loan DXDY
// amount desired is how much we are willing for position to change
function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) {
uint256 amount = amountDesired;
ISoloMargin solo = ISoloMargin(SOLO);
// Not enough want in DyDx. So we take all we can
uint256 amountInSolo = want.balanceOf(SOLO);
if (amountInSolo < amount) {
amount = amountInSolo;
}
uint256 repayAmount = amount.add(2); // we need to overcollateralise on way back
bytes memory data = abi.encode(deficit, amount, repayAmount);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(dyDxMarketId, amount);
operations[1] = _getCallAction(
// Encode custom data for callFunction
data
);
operations[2] = _getDepositAction(dyDxMarketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
emit Leverage(amountDesired, amount, deficit, SOLO);
return amount;
}
//returns our current collateralisation ratio. Should be compared with collateralTarget
function storedCollateralisation() public view returns (uint256 collat) {
(uint256 lend, uint256 borrow) = getCurrentPosition();
if (lend == 0) {
return 0;
}
collat = uint256(1e18).mul(borrow).div(lend);
}
//DyDx calls this function after doing flash loan
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount, uint256 repayAmount) = abi.decode(data, (bool, uint256, uint256));
require(msg.sender == SOLO, "NOT_SOLO");
_loanLogic(deficit, amount, repayAmount);
}
function doAaveFlashLoan(bool deficit, uint256 _flashBackUpAmount) internal returns (uint256 amount) {
//we do not want to do aave flash loans for leveraging up. Fee could put us into liquidation
if (!deficit) {
return _flashBackUpAmount;
}
ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());
uint256 availableLiquidity = want.balanceOf(address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3));
if (availableLiquidity < _flashBackUpAmount) {
amount = availableLiquidity;
} else {
amount = _flashBackUpAmount;
}
require(amount <= _flashBackUpAmount); // dev: "incorrect amount"
bytes memory data = abi.encode(deficit, amount);
lendingPool.flashLoan(address(this), address(want), amount, data);
emit Leverage(_flashBackUpAmount, amount, deficit, AAVE_LENDING);
}
//Aave calls this function after doing flash loan
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
(bool deficit, uint256 amount) = abi.decode(_params, (bool, uint256));
require(msg.sender == addressesProvider.getLendingPool(), "NOT_AAVE");
_loanLogic(deficit, amount, amount.add(_fee));
// return the flash loan plus Aave's flash loan fee back to the lending pool
uint256 totalDebt = _amount.add(_fee);
transferFundsBackToPoolInternal(_reserve, totalDebt);
}
} | contract Strategy is BaseStrategy, DydxFlashloanBase, ICallee, FlashLoanReceiverBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// @notice emitted when trying to do Flash Loan. flashLoan address is 0x00 when no flash loan used
event Leverage(uint256 amountRequested, uint256 amountGiven, bool deficit, address flashLoan);
//Flash Loan Providers
address private constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
address private constant AAVE_LENDING = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
// Comptroller address for compound.finance
ComptrollerI public constant compound = ComptrollerI(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
//Only three tokens we use
address public constant comp = address(0xc00e94Cb662C3520282E6f5717214004A7f26888);
CErc20I public cToken;
//address public constant DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
//Operating variables
uint256 public collateralTarget = 0.73 ether; // 73%
uint256 public blocksToLiquidationDangerZone = 46500; // 7 days = 60*60*24*7/13
uint256 public minWant = 10 ether; //Only lend if we have enough want to be worth it
uint256 public minCompToSell = 0.1 ether; //used both as the threshold to sell but also as a trigger for harvest
//To deactivate flash loan provider if needed
bool public DyDxActive = true;
bool public AaveActive = true;
uint256 public dyDxMarketId;
constructor(address _vault, address _cToken) public BaseStrategy(_vault) FlashLoanReceiverBase(AAVE_LENDING) {
cToken = CErc20I(address(_cToken));
//pre-set approvals
IERC20(comp).safeApprove(uniswapRouter, uint256(-1));
want.safeApprove(address(cToken), uint256(-1));
want.safeApprove(SOLO, uint256(-1));
// You can set these parameters on deployment to whatever you want
minReportDelay = 86400; // once per 24 hours
profitFactor = 50; // multiple before triggering harvest
dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, address(want));
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
function name() external override pure returns (string memory){
return "GenericLevCompFarm";
}
/*
* Control Functions
*/
function setDyDx(bool _dydx) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
DyDxActive = _dydx;
}
function setAave(bool _ave) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
AaveActive = _ave;
}
function setMinCompToSell(uint256 _minCompToSell) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
minCompToSell = _minCompToSell;
}
function setMinWant(uint256 _minWant) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
minWant = _minWant;
}
function updateMarketId() external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, address(want));
}
function setCollateralTarget(uint256 _collateralTarget) external {
require(msg.sender == governance() || msg.sender == strategist, "!management"); // dev: not governance or strategist
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
require(collateralFactorMantissa > _collateralTarget, "!dangerous collateral");
collateralTarget = _collateralTarget;
}
/*
* Base External Facing Functions
*/
/*
* Expected return this strategy would provide to the Vault the next time `report()` is called
*
* The total assets currently in strategy minus what vault believes we have
* Does not include unrealised profit such as comp.
*/
function expectedReturn() public view returns (uint256) {
uint256 estimateAssets = estimatedTotalAssets();
uint256 debt = vault.strategies(address(this)).totalDebt;
if (debt > estimateAssets) {
return 0;
} else {
return estimateAssets - debt;
}
}
/*
* An accurate estimate for the total amount of assets (principle + return)
* that this strategy is currently managing, denominated in terms of want tokens.
*/
function estimatedTotalAssets() public override view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 _claimableComp = predictCompAccrued();
uint256 currentComp = IERC20(comp).balanceOf(address(this));
// Use touch price. it doesnt matter if we are wrong as this is not used for decision making
uint256 estimatedWant = priceCheck(comp, address(want),_claimableComp.add(currentComp));
uint256 conservativeWant = estimatedWant.mul(9).div(10); //10% pessimist
return want.balanceOf(address(this)).add(deposits).add(conservativeWant).sub(borrows);
}
/*
* Provide a signal to the keeper that `tend()` should be called.
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `harvestTrigger` should never return `true` at the same time.
*/
function tendTrigger(uint256 gasCost) public override view returns (bool) {
if (harvestTrigger(0)) {
//harvest takes priority
return false;
}
if (getblocksUntilLiquidation() <= blocksToLiquidationDangerZone) {
return true;
}
}
/*
* Provide a signal to the keeper that `harvest()` should be called.
* gasCost is expected_gas_use * gas_price
* (keepers are always reimbursed by yEarn)
*
* NOTE: this call and `tendTrigger` should never return `true` at the same time.
*/
function harvestTrigger(uint256 gasCost) public override view returns (bool) {
uint256 wantGasCost = priceCheck(weth, address(want), gasCost);
uint256 compGasCost = priceCheck(weth, comp, gasCost);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if strategy is not activated
if (params.activation == 0) return false;
// Should trigger if hadn't been called in a while
if (block.timestamp.sub(params.lastReport) >= minReportDelay) return true;
// after enough comp has accrued we want the bot to run
uint256 _claimableComp = predictCompAccrued();
if (_claimableComp > minCompToSell) {
// check value of COMP in wei
if ( _claimableComp.add(IERC20(comp).balanceOf(address(this))) > compGasCost.mul(profitFactor)) {
return true;
}
}
//check if vault wants lots of money back
// dont return dust
uint256 outstanding = vault.debtOutstanding();
if (outstanding > profitFactor.mul(wantGasCost)) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
uint256 credit = vault.creditAvailable().add(profit);
return (profitFactor.mul(wantGasCost) < credit);
}
//WARNING. manipulatable and simple routing. Only use for safe functions
function priceCheck(address start, address end, uint256 _amount) public view returns (uint256) {
if (_amount == 0) {
return 0;
}
address[] memory path;
if(start == weth){
path = new address[](2);
path[0] = weth;
path[1] = end;
}else{
path = new address[](2);
path[0] = start;
path[1] = weth;
path[1] = end;
}
uint256[] memory amounts = IUniswapV2Router02(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
/*****************
* Public non-base function
******************/
//Calculate how many blocks until we are in liquidation based on current interest rates
//WARNING does not include compounding so the estimate becomes more innacurate the further ahead we look
//equation. Compound doesn't include compounding for most blocks
//((deposits*colateralThreshold - borrows) / (borrows*borrowrate - deposits*colateralThreshold*interestrate));
function getblocksUntilLiquidation() public view returns (uint256 blocks) {
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
(uint256 deposits, uint256 borrows) = getCurrentPosition();
uint256 borrrowRate = cToken.borrowRatePerBlock();
uint256 supplyRate = cToken.supplyRatePerBlock();
uint256 collateralisedDeposit1 = deposits.mul(collateralFactorMantissa);
uint256 collateralisedDeposit = collateralisedDeposit1.div(1e18);
uint256 denom1 = borrows.mul(borrrowRate);
uint256 denom2 = collateralisedDeposit.mul(supplyRate);
if (denom2 >= denom1) {
blocks = uint256(-1);
} else {
uint256 numer = collateralisedDeposit.sub(borrows);
uint256 denom = denom1 - denom2;
blocks = numer.mul(1e18).div(denom);
}
}
// This function makes a prediction on how much comp is accrued
// It is not 100% accurate as it uses current balances in Compound to predict into the past
function predictCompAccrued() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
if (deposits == 0) {
return 0; // should be impossible to have 0 balance and positive comp accrued
}
//comp speed is amount to borrow or deposit (so half the total distribution for want)
uint256 distributionPerBlock = compound.compSpeeds(address(cToken));
uint256 totalBorrow = cToken.totalBorrows();
//total supply needs to be echanged to underlying using exchange rate
uint256 totalSupplyCtoken = cToken.totalSupply();
uint256 totalSupply = totalSupplyCtoken.mul(cToken.exchangeRateStored()).div(1e18);
uint256 blockShareSupply = 0;
if(totalSupply > 0){
blockShareSupply = deposits.mul(distributionPerBlock).div(totalSupply);
}
uint256 blockShareBorrow = 0;
if(totalBorrow > 0){
blockShareBorrow = borrows.mul(distributionPerBlock).div(totalBorrow);
}
//how much we expect to earn per block
uint256 blockShare = blockShareSupply.add(blockShareBorrow);
//last time we ran harvest
uint256 lastReport = vault.strategies(address(this)).lastReport;
uint256 blocksSinceLast= (block.timestamp.sub(lastReport)).div(13); //roughly 13 seconds per block
return blocksSinceLast.mul(blockShare);
}
//Returns the current position
//WARNING - this returns just the balance at last time someone touched the cToken token. Does not accrue interst in between
//cToken is very active so not normally an issue.
function getCurrentPosition() public view returns (uint256 deposits, uint256 borrows) {
(, uint256 ctokenBalance, uint256 borrowBalance, uint256 exchangeRate) = cToken.getAccountSnapshot(address(this));
borrows = borrowBalance;
deposits = ctokenBalance.mul(exchangeRate).div(1e18);
}
//statechanging version
function getLivePosition() public returns (uint256 deposits, uint256 borrows) {
deposits = cToken.balanceOfUnderlying(address(this));
//we can use non state changing now because we updated state with balanceOfUnderlying call
borrows = cToken.borrowBalanceStored(address(this));
}
//Same warning as above
function netBalanceLent() public view returns (uint256) {
(uint256 deposits, uint256 borrows) = getCurrentPosition();
return deposits.sub(borrows);
}
/***********
* internal core logic
*********** */
/*
* A core method.
* Called at beggining of harvest before providing report to owner
* 1 - claim accrued comp
* 2 - if enough to be worth it we sell
* 3 - because we lose money on our loans we need to offset profit from comp.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
) {
_profit = 0;
_loss = 0; //for clarity
if (cToken.balanceOf(address(this)) == 0) {
uint256 wantBalance = want.balanceOf(address(this));
//no position to harvest
//but we may have some debt to return
//it is too expensive to free more debt in this method so we do it in adjust position
_debtPayment = Math.min(wantBalance, _debtOutstanding);
return (_profit, _loss, _debtPayment);
}
(uint256 deposits, uint256 borrows) = getLivePosition();
//claim comp accrued
_claimComp();
//sell comp
_disposeOfComp();
uint256 wantBalance = want.balanceOf(address(this));
uint256 investedBalance = deposits.sub(borrows);
uint256 balance = investedBalance.add(wantBalance);
uint256 debt = vault.strategies(address(this)).totalDebt;
//Balance - Total Debt is profit
if (balance > debt) {
_profit = balance - debt;
if (wantBalance < _profit) {
//all reserve is profit
_profit = wantBalance;
} else if (wantBalance > _profit.add(_debtOutstanding)){
_debtPayment = _debtOutstanding;
}else{
_debtPayment = wantBalance - _profit;
}
} else {
//we will lose money until we claim comp then we will make money
//this has an unintended side effect of slowly lowering our total debt allowed
_loss = debt - balance;
_debtPayment = Math.min(wantBalance, _debtOutstanding);
}
}
/*
* Second core function. Happens after report call.
*
* Similar to deposit function from V1 strategy
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//emergency exit is dealt with in prepareReturn
if (emergencyExit) {
return;
}
//we are spending all our cash unless we have debt outstanding
uint256 _wantBal = want.balanceOf(address(this));
if(_wantBal < _debtOutstanding){
//this is graceful withdrawal. dont use backup
//we use more than 1 because withdrawunderlying causes problems with 1 token due to different decimals
if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(_debtOutstanding - _wantBal, false);
}
return;
}
(uint256 position, bool deficit) = _calculateDesiredPosition(_wantBal - _debtOutstanding, true);
//if we are below minimun want change it is not worth doing
//need to be careful in case this pushes to liquidation
if (position > minWant) {
//if dydx is not active we just try our best with basic leverage
if (!DyDxActive) {
_noFlashLoan(position, deficit);
} else {
//if there is huge position to improve we want to do normal leverage. it is quicker
if (position > want.balanceOf(SOLO)) {
position = position.sub(_noFlashLoan(position, deficit));
}
//flash loan to position
if(position > 0){
doDyDxFlashLoan(deficit, position);
}
}
}
}
/*************
* Very important function
* Input: amount we want to withdraw and whether we are happy to pay extra for Aave.
* cannot be more than we have
* Returns amount we were able to withdraw. notall if user has some balance left
*
* Deleverage position -> redeem our cTokens
******************** */
function _withdrawSome(uint256 _amount, bool _useBackup) internal returns (bool notAll) {
(uint256 position, bool deficit) = _calculateDesiredPosition(_amount, false);
//If there is no deficit we dont need to adjust position
if (deficit) {
//we do a flash loan to give us a big gap. from here on out it is cheaper to use normal deleverage. Use Aave for extremely large loans
if (DyDxActive) {
position = position.sub(doDyDxFlashLoan(deficit, position));
}
// Will decrease number of interactions using aave as backup
// because of fee we only use in emergency
if (position > 0 && AaveActive && _useBackup) {
position = position.sub(doAaveFlashLoan(deficit, position));
}
uint8 i = 0;
//position will equal 0 unless we haven't been able to deleverage enough with flash loan
//if we are not in deficit we dont need to do flash loan
while (position > 0) {
position = position.sub(_noFlashLoan(position, true));
i++;
//A limit set so we don't run out of gas
if (i >= 5) {
notAll = true;
break;
}
}
}
//now withdraw
//if we want too much we just take max
//This part makes sure our withdrawal does not force us into liquidation
(uint256 depositBalance, uint256 borrowBalance) = getCurrentPosition();
uint256 AmountNeeded = 0;
if(collateralTarget > 0){
AmountNeeded = borrowBalance.mul(1e18).div(collateralTarget);
}
uint256 redeemable = depositBalance.sub(AmountNeeded);
if (redeemable < _amount) {
cToken.redeemUnderlying(redeemable);
} else {
cToken.redeemUnderlying(_amount);
}
//let's sell some comp if we have more than needed
//flash loan would have sent us comp if we had some accrued so we don't need to call claim comp
_disposeOfComp();
}
/***********
* This is the main logic for calculating how to change our lends and borrows
* Input: balance. The net amount we are going to deposit/withdraw.
* Input: dep. Is it a deposit or withdrawal
* Output: position. The amount we want to change our current borrow position.
* Output: deficit. True if we are reducing position size
*
* For instance deficit =false, position 100 means increase borrowed balance by 100
****** */
function _calculateDesiredPosition(uint256 balance, bool dep) internal returns (uint256 position, bool deficit) {
//we want to use statechanging for safety
(uint256 deposits, uint256 borrows) = getLivePosition();
//When we unwind we end up with the difference between borrow and supply
uint256 unwoundDeposit = deposits.sub(borrows);
//we want to see how close to collateral target we are.
//So we take our unwound deposits and add or remove the balance we are are adding/removing.
//This gives us our desired future undwoundDeposit (desired supply)
uint256 desiredSupply = 0;
if (dep) {
desiredSupply = unwoundDeposit.add(balance);
} else {
if(balance > unwoundDeposit) balance = unwoundDeposit;
desiredSupply = unwoundDeposit.sub(balance);
}
//(ds *c)/(1-c)
uint256 num = desiredSupply.mul(collateralTarget);
uint256 den = uint256(1e18).sub(collateralTarget);
uint256 desiredBorrow = num.div(den);
if (desiredBorrow > 1e18) {
//stop us going right up to the wire
desiredBorrow = desiredBorrow - 1e18;
}
//now we see if we want to add or remove balance
// if the desired borrow is less than our current borrow we are in deficit. so we want to reduce position
if (desiredBorrow < borrows) {
deficit = true;
position = borrows - desiredBorrow; //safemath check done in if statement
} else {
//otherwise we want to increase position
deficit = false;
position = desiredBorrow - borrows;
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amount`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed) {
uint256 _balance = want.balanceOf(address(this));
if (netBalanceLent().add(_balance) < _amountNeeded) {
//if we cant afford to withdraw we take all we can
//withdraw all we can
(,_amountFreed) = exitPosition();
} else {
if (_balance < _amountNeeded) {
_withdrawSome(_amountNeeded.sub(_balance), true);
_amountFreed = want.balanceOf(address(this));
}else{
_amountFreed = _balance - _amountNeeded;
}
}
}
function claimComp() public {
require(msg.sender == governance() || msg.sender == strategist, "!management");
_claimComp();
}
function _claimComp() internal {
CTokenI[] memory tokens = new CTokenI[](1);
tokens[0] = cToken;
compound.claimComp(address(this), tokens);
}
//sell comp function
function _disposeOfComp() internal {
uint256 _comp = IERC20(comp).balanceOf(address(this));
if (_comp > minCompToSell) {
address[] memory path = new address[](3);
path[0] = comp;
path[1] = weth;
path[2] = address(want);
IUniswapV2Router02(uniswapRouter).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now);
}
}
/*
* Make as much capital as possible "free" for the Vault to take. Some slippage
* is allowed.
*/
function exitPosition() internal override returns (uint256 _loss, uint256 _debtPayment){
uint256 balanceBefore = vault.strategies(address(this)).totalDebt;
//we dont use getCurrentPosition() because it won't be exact
(uint256 deposits, uint256 borrows) = getLivePosition();
//1 token causes rounding error with withdrawUnderlying
if(cToken.balanceOf(address(this)) > 1){
_withdrawSome(deposits.sub(borrows), true);
}
_debtPayment = want.balanceOf(address(this));
if(balanceBefore > _debtPayment){
_loss = balanceBefore - _debtPayment;
}
}
//lets leave
function prepareMigration(address _newStrategy) internal override {
(uint256 deposits, uint256 borrows) = getLivePosition();
_withdrawSome(deposits.sub(borrows), false);
(, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));
require(borrowBalance == 0, "DELEVERAGE_FIRST");
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
cToken.transfer(_newStrategy, cToken.balanceOf(address(this)));
IERC20 _comp = IERC20(comp);
_comp.safeTransfer(_newStrategy, _comp.balanceOf(address(this)));
}
//Three functions covering normal leverage and deleverage situations
// max is the max amount we want to increase our borrowed balance
// returns the amount we actually did
function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {
//we can use non-state changing because this function is always called after _calculateDesiredPosition
(uint256 lent, uint256 borrowed) = getCurrentPosition();
if (borrowed == 0) {
return 0;
}
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
if (deficit) {
amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);
} else {
amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);
}
emit Leverage(max, amount, deficit, address(0));
}
//maxDeleverage is how much we want to reduce by
function _normalDeleverage(
uint256 maxDeleverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 deleveragedAmount) {
uint256 theoreticalLent = borrowed.mul(1e18).div(collatRatio);
deleveragedAmount = lent.sub(theoreticalLent);
if (deleveragedAmount >= borrowed) {
deleveragedAmount = borrowed;
}
if (deleveragedAmount >= maxDeleverage) {
deleveragedAmount = maxDeleverage;
}
cToken.redeemUnderlying(deleveragedAmount);
//our borrow has been increased by no more than maxDeleverage
cToken.repayBorrow(deleveragedAmount);
}
//maxDeleverage is how much we want to increase by
function _normalLeverage(
uint256 maxLeverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 leveragedAmount) {
uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);
leveragedAmount = theoreticalBorrow.sub(borrowed);
if (leveragedAmount >= maxLeverage) {
leveragedAmount = maxLeverage;
}
cToken.borrow(leveragedAmount);
cToken.mint(want.balanceOf(address(this)));
}
//called by flash loan
function _loanLogic(
bool deficit,
uint256 amount,
uint256 repayAmount
) internal {
uint256 bal = want.balanceOf(address(this));
require(bal >= amount, "FLASH_FAILED"); // to stop malicious calls
//if in deficit we repay amount and then withdraw
if (deficit) {
cToken.repayBorrow(amount);
//if we are withdrawing we take more to cover fee
cToken.redeemUnderlying(repayAmount);
} else {
require(cToken.mint(bal) == 0, "mint error");
//borrow more to cover fee
// fee is so low for dydx that it does not effect our liquidation risk.
//DONT USE FOR AAVE
cToken.borrow(repayAmount);
}
}
function protectedTokens() internal override view returns (address[] memory) {
address[] memory protected = new address[](3);
protected[0] = address(want);
protected[1] = comp;
protected[2] = address(cToken);
return protected;
}
/******************
* Flash loan stuff
****************/
// Flash loan DXDY
// amount desired is how much we are willing for position to change
function doDyDxFlashLoan(bool deficit, uint256 amountDesired) internal returns (uint256) {
uint256 amount = amountDesired;
ISoloMargin solo = ISoloMargin(SOLO);
// Not enough want in DyDx. So we take all we can
uint256 amountInSolo = want.balanceOf(SOLO);
if (amountInSolo < amount) {
amount = amountInSolo;
}
uint256 repayAmount = amount.add(2); // we need to overcollateralise on way back
bytes memory data = abi.encode(deficit, amount, repayAmount);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(dyDxMarketId, amount);
operations[1] = _getCallAction(
// Encode custom data for callFunction
data
);
operations[2] = _getDepositAction(dyDxMarketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
emit Leverage(amountDesired, amount, deficit, SOLO);
return amount;
}
//returns our current collateralisation ratio. Should be compared with collateralTarget
function storedCollateralisation() public view returns (uint256 collat) {
(uint256 lend, uint256 borrow) = getCurrentPosition();
if (lend == 0) {
return 0;
}
collat = uint256(1e18).mul(borrow).div(lend);
}
//DyDx calls this function after doing flash loan
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount, uint256 repayAmount) = abi.decode(data, (bool, uint256, uint256));
require(msg.sender == SOLO, "NOT_SOLO");
_loanLogic(deficit, amount, repayAmount);
}
function doAaveFlashLoan(bool deficit, uint256 _flashBackUpAmount) internal returns (uint256 amount) {
//we do not want to do aave flash loans for leveraging up. Fee could put us into liquidation
if (!deficit) {
return _flashBackUpAmount;
}
ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());
uint256 availableLiquidity = want.balanceOf(address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3));
if (availableLiquidity < _flashBackUpAmount) {
amount = availableLiquidity;
} else {
amount = _flashBackUpAmount;
}
require(amount <= _flashBackUpAmount); // dev: "incorrect amount"
bytes memory data = abi.encode(deficit, amount);
lendingPool.flashLoan(address(this), address(want), amount, data);
emit Leverage(_flashBackUpAmount, amount, deficit, AAVE_LENDING);
}
//Aave calls this function after doing flash loan
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
) external override {
(bool deficit, uint256 amount) = abi.decode(_params, (bool, uint256));
require(msg.sender == addressesProvider.getLendingPool(), "NOT_AAVE");
_loanLogic(deficit, amount, amount.add(_fee));
// return the flash loan plus Aave's flash loan fee back to the lending pool
uint256 totalDebt = _amount.add(_fee);
transferFundsBackToPoolInternal(_reserve, totalDebt);
}
} | 42,693 |
20 | // Mints stablecoins to this contract | function addReserves(uint256 amount, address stablecoin) external onlyOwner onlyValidTokens(stablecoin) {
_addReserves(amount, stablecoin);
}
| function addReserves(uint256 amount, address stablecoin) external onlyOwner onlyValidTokens(stablecoin) {
_addReserves(amount, stablecoin);
}
| 28,937 |
5 | // Return if deposit cannot be made. | msg.sender.send(msg.value);
return false;
| msg.sender.send(msg.value);
return false;
| 50,780 |
241 | // Batch confiscate to a maximum of 256 addresses._confiscatees array addresses who's funds are being confiscated_receivers array addresses who's receiving the funds_values array of values of funds being confiscated/ | function batchConfiscate(address[] memory _confiscatees, address[] memory _receivers, uint256[] memory _values) public returns (bool) {
require(_confiscatees.length == _values.length && _receivers.length == _values.length, "SygnumToken: confiscatees, recipients and values are not equal.");
require(_confiscatees.length < BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for(uint256 i = 0; i < _confiscatees.length; i++) {
confiscate(_confiscatees[i], _receivers[i], _values[i]);
}
}
| function batchConfiscate(address[] memory _confiscatees, address[] memory _receivers, uint256[] memory _values) public returns (bool) {
require(_confiscatees.length == _values.length && _receivers.length == _values.length, "SygnumToken: confiscatees, recipients and values are not equal.");
require(_confiscatees.length < BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for(uint256 i = 0; i < _confiscatees.length; i++) {
confiscate(_confiscatees[i], _receivers[i], _values[i]);
}
}
| 4,903 |
112 | // decrement Hat supply counter | --hatSupply[uint256(id)];
emit TransferSingle(msg.sender, from, address(0), id, amount);
| --hatSupply[uint256(id)];
emit TransferSingle(msg.sender, from, address(0), id, amount);
| 36,594 |
3 | // Function to unlock timelocked tokensIf block.timestap passed tokens are sent to owner and lock is removed from database / | function unlock() external
| function unlock() external
| 5,387 |
20 | // remove staker from array |
if (_stakedAmount[_msgSender()] == 0) {
for (uint256 i=0; i < _stakers.length; i++) {
if (_stakers[i] == _msgSender()) {
_stakers[i] = _stakers[_stakers.length.sub(1)];
_stakers.pop();
|
if (_stakedAmount[_msgSender()] == 0) {
for (uint256 i=0; i < _stakers.length; i++) {
if (_stakers[i] == _msgSender()) {
_stakers[i] = _stakers[_stakers.length.sub(1)];
_stakers.pop();
| 2,744 |
8 | // Uniswap V3 | function exactInputSingle(IBNPLSwapMarket.ExactInputSingleParams calldata params)
external
payable
override
returns (uint256 amountOut)
| function exactInputSingle(IBNPLSwapMarket.ExactInputSingleParams calldata params)
external
payable
override
returns (uint256 amountOut)
| 40,416 |
215 | // After a pack is bought with ETH, we call this to attribute the sale to the buyer's referrer./_buyer The user who bought the pack./_amount The price of the pack bought, in wei. | function _attributeSale(address _buyer, uint256 _amount) internal {
address referrer = referrers[_buyer];
// Can only attribute a sale to a valid referrer.
// Referral commissions only accrue if the referrer has bought a pack.
if (referrer == address(0) || packsBought[referrer] == 0) {
return;
}
referralSaleCount[referrer]++;
// The first 8 referral sales each unlock a bonus card.
// Any sales past the first 8 generate referral commission.
if (referralSaleCount[referrer] > bonusCards.length) {
uint256 commission = _amount * PERCENT_COMMISSION / 100;
totalCommissionOwed += commission;
referralCommissionEarned[referrer] += commission;
}
emit SaleAttributed(referrer, _buyer, _amount);
}
| function _attributeSale(address _buyer, uint256 _amount) internal {
address referrer = referrers[_buyer];
// Can only attribute a sale to a valid referrer.
// Referral commissions only accrue if the referrer has bought a pack.
if (referrer == address(0) || packsBought[referrer] == 0) {
return;
}
referralSaleCount[referrer]++;
// The first 8 referral sales each unlock a bonus card.
// Any sales past the first 8 generate referral commission.
if (referralSaleCount[referrer] > bonusCards.length) {
uint256 commission = _amount * PERCENT_COMMISSION / 100;
totalCommissionOwed += commission;
referralCommissionEarned[referrer] += commission;
}
emit SaleAttributed(referrer, _buyer, _amount);
}
| 29,415 |
282 | // ERC1155AzukiERC-721 Marketplace with tokens and royalties support / | contract ERC1155Marketplace is ERC1155YuzuInternal, ReentrancyGuard {
using Address for address;
// admin address, the owner of the marketplace
address public admin;
// commission rate is a value from 0 to 100
uint256 public commissionRate;
// royalties commission rate is a value from 0 to 100
uint256 public royaltiesCommissionRate;
// nft item creators list, used to pay royalties
mapping(uint256 => address) public creators;
// a sale object
struct Sale {
uint256 qty; // qty for sale
uint256 price; // price
address user; // seller
address wallet; // seller wallet
}
// opened sales by tokenIds
mapping(uint256 => Sale[]) public openSales;
// length of the array
mapping(uint256 => uint256) public openSalesLength;
// a buy offer object
struct Offer {
uint256 qty; // qty for buying
uint256 price; // buy price
address user; // buyer
}
// opened offers by tokenIds
mapping(uint256 => Offer[]) public openOffers;
// length of the array
mapping(uint256 => uint256) public openOffersLength;
event Bid( uint256 indexed tokenId, address indexed from, uint256 qty, uint256 price);
event Sell( uint256 indexed tokenId, address indexed to, uint256 qty, uint256 price);
event Commission( uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event Royalty( uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event Buy( uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event CancelSale(uint256 indexed tokenId, uint256 index);
event CancelBid(uint256 indexed tokenId, uint256 index);
event Change(address beneficiary, uint256 value);
constructor(
address _owner, address _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate,
string memory name, string memory symbol, bool _anyoneCanMint, string memory uri)
ERC1155YuzuInternal(_owner, uri, name, symbol, _anyoneCanMint)
{
require(_commissionRate + _royaltiesCommissionRate < 100, "Azuki: total commissions should be lower than 100");
admin = _admin;
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
}
/**
* Any user can sell X items at Y price each, valid ownership and qty of the sell will be handled by the UI
* All selling options are shown as “Listings” in the UI
* Any user can buy W items at Y price, of one listing, they cannot combine two listings in one transaction, given that W>0 and W<=Y
* Restrictions:
* Limit the sell to owned items, the user cannot sell items do not have
*/
function sell(uint256 tokenId, uint256 qty, uint256 price, address wallet) external {
// Limit the sell to owned items, the user cannot sell items do not have
require(balanceOf(_msgSender(), tokenId) >= qty, "Azuki: you do not have enough tokens to sell");
// set approval for all items of the user is not set already
if (!isApprovedForAll(_msgSender(), address(this))) {
setApprovalForAll(address(this), true);
}
// add the selling option to openSales
Sale memory sale = Sale(qty, price, _msgSender(), wallet);
// An owner can add only one selling listing for one item at a time, new listings for one item will replace the old ones
openSales[tokenId].push(sale);
openSalesLength[tokenId] = openSales[tokenId].length;
emit Sell(tokenId, _msgSender(), qty, price);
}
/**
* Return the extra funds sent to the contract
*/
function returnTheChange(uint256 total) internal {
if(msg.value > total) {
(bool success, ) = _msgSender().call{value:msg.value - total}("");
require(success, "Transfer failed.");
emit Change(_msgSender(), msg.value - total);
}
}
/**
* Buy an NTF item, specifying qty to buy and index offer
* Funds are transferred from the caller user directly, previous approval required
*/
function buy(uint256 tokenId, uint256 index, uint256 qty) payable external nonReentrant {
// validate user
require(openSales[tokenId][index].user != _msgSender() , "Azuki: the user cannot buy his own offer");
uint256 total = qty * openSales[tokenId][index].price;
// require enough funds
require(msg.value >= total, "Azuki: payment is too low");
// return the change
returnTheChange(total);
/**
* distribute funds between owner, creator and admin
* This function will transfer the funds from the buyer, which must have previously approve the funds to the contract, to the beneficiaries of the sale
*/
distributeFunds(total, _msgSender(), openSales[tokenId][index].wallet, tokenId);
// transfer ownership
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
callOptionalReturn(this, abi.encodeWithSelector(this.safeTransferFrom.selector, openSales[tokenId][index].user, _msgSender(), tokenId, qty, "0x"));
// substract items sold
openSales[tokenId][index].qty -= qty;
// remove the offer and reorder the array
if (openSales[tokenId][index].qty == 0) {
openSales[tokenId][index] = openSales[tokenId][openSales[tokenId].length-1];
openSales[tokenId].pop();
openSalesLength[tokenId] = openSales[tokenId].length;
}
}
// cancel the sale
function cancelSale(uint256 tokenId, uint256 index) external {
// Only the original bidder can cancel his bids
require(openSales[tokenId][index].user == _msgSender(), "Azuki: only the original seller can cancel his sales");
// remove the sale
openSales[tokenId][index] = openSales[tokenId][openSales[tokenId].length-1];
openSales[tokenId].pop();
openSalesLength[tokenId] = openSales[tokenId].length;
emit CancelSale(tokenId, index);
}
/**
* Any user can make an offer of X items at Y price each
* Funds of the offer are stored on the contract
* All offers are shown as “Offers” in the UI
* Restrictions
* A buyer cannot add an offer bigger than the total supply
*/
function bid(uint256 tokenId, uint256 qty, uint256 price) external payable nonReentrant {
require(qty>0, "Iksasumi: qty has to be positive");
require(price>0, "Iksasumi: price has to be positive");
require(qty <= totalSupply(tokenId), "Iksasumi: not enough items for sale");
// transfer qty * price tokens to the contract
uint256 total = qty * price;
// require enough funds
require(msg.value >= total, "Azuki: payment is too low");
// return the change
returnTheChange(total);
// record the offer
Offer memory theBid = Offer(qty, price, _msgSender());
openOffers[tokenId].push(theBid);
openOffersLength[tokenId] = openOffers[tokenId].length;
emit Bid(tokenId, _msgSender(), qty, price);
}
// cancel the offer and return funds
function cancelBid(uint256 tokenId, uint256 index) external nonReentrant {
// Only the original bidder can cancel his bids
require(openOffers[tokenId][index].user == _msgSender(), "Azuki: only the original bidder can cancel his bids");
// save the total
uint256 total = openOffers[tokenId][index].qty * openOffers[tokenId][index].price;
// remove the bid
openOffers[tokenId][index] = openOffers[tokenId][openOffers[tokenId].length-1];
openOffers[tokenId].pop();
openOffersLength[tokenId] = openOffers[tokenId].length;
// return the funds
(bool success, ) = _msgSender().call{value:total}("");
require(success, "Transfer failed.");
emit CancelBid(tokenId, index);
}
// owner accepts the bid and distribute the funds
function acceptBid(uint256 tokenId, uint256 index, uint256 qty) external nonReentrant {
// validate user
require(openOffers[tokenId][index].user != _msgSender() , "Azuki: the user cannot accept his own bid");
// set approval for all items of the user is not set already
if (!isApprovedForAll(_msgSender(), address(this))) {
setApprovalForAll(address(this), true);
}
// transfer item to bidder
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
callOptionalReturn(this, abi.encodeWithSelector(this.safeTransferFrom.selector, _msgSender(), openOffers[tokenId][index].user, tokenId, qty, "0x"));
/**
* distribute funds between owner, creator and admin
* This function will transfer the funds from the contract, which must have previously sent to the contract, to the beneficiaries of the sale
*/
distributeFunds(qty * openOffers[tokenId][index].price, openOffers[tokenId][index].user, _msgSender(), tokenId);
// substract items sold
openOffers[tokenId][index].qty -= qty;
// remove the offer and reorder the array
if (openOffers[tokenId][index].qty == 0) {
openOffers[tokenId][index] = openOffers[tokenId][openOffers[tokenId].length-1];
openOffers[tokenId].pop();
openOffersLength[tokenId] = openOffers[tokenId].length;
}
}
/**
* do the funds distribution between owner, creator and admin
* @param totalPrice the total value to distribute
* @param from if useTransferFrom is true then the "from" is the origin of the funds, if false, then the "from" is only used for logs purposes
* @param to is the owner of the token on sale / bid
* @param tokenId is the token being sold
*/
function distributeFunds(uint256 totalPrice, address from, address to, uint256 tokenId) internal {
// calculate amounts
uint256 amount4admin = totalPrice * commissionRate / 100;
uint256 amount4creator = totalPrice * royaltiesCommissionRate / 100;
uint256 amount4owner = totalPrice - amount4admin - amount4creator;
// to owner
(bool success, ) = to.call{value:amount4owner}("");
require(success, "Transfer failed.");
emit Buy(tokenId, from, to, amount4owner);
// to creator
if (amount4creator>0) {
(bool success2, ) = creators[tokenId].call{value:amount4creator}("");
require(success2, "Transfer failed.");
emit Royalty(tokenId, from, creators[tokenId], amount4creator);
}
// to admin
if (amount4admin>0) {
(bool success3, ) = admin.call{value:amount4admin}("");
require(success3, "Transfer failed.");
emit Commission(tokenId, from, admin, amount4admin);
}
}
/// Overrides minting function to keep track of item creators
function _mint(address to, uint256 tokenId, uint256 amount, bytes memory data) override internal {
creators[tokenId] = _msgSender();
super._mint(to, tokenId, amount, data);
}
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) override internal {
super._mintBatch(to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
creators[ids[i]] = _msgSender();
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC1155 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "Azuki: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "Azuki: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "Azuki: ERC20 operation did not succeed");
}
}
// update contract fields
function updateAdmin(address _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, bool _anyoneCanMint) external onlyOwner() {
require(_commissionRate + _royaltiesCommissionRate < 100, "Azuki: total commissions should be lower than 100");
admin = _admin;
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
anyoneCanMint = _anyoneCanMint;
}
}
| contract ERC1155Marketplace is ERC1155YuzuInternal, ReentrancyGuard {
using Address for address;
// admin address, the owner of the marketplace
address public admin;
// commission rate is a value from 0 to 100
uint256 public commissionRate;
// royalties commission rate is a value from 0 to 100
uint256 public royaltiesCommissionRate;
// nft item creators list, used to pay royalties
mapping(uint256 => address) public creators;
// a sale object
struct Sale {
uint256 qty; // qty for sale
uint256 price; // price
address user; // seller
address wallet; // seller wallet
}
// opened sales by tokenIds
mapping(uint256 => Sale[]) public openSales;
// length of the array
mapping(uint256 => uint256) public openSalesLength;
// a buy offer object
struct Offer {
uint256 qty; // qty for buying
uint256 price; // buy price
address user; // buyer
}
// opened offers by tokenIds
mapping(uint256 => Offer[]) public openOffers;
// length of the array
mapping(uint256 => uint256) public openOffersLength;
event Bid( uint256 indexed tokenId, address indexed from, uint256 qty, uint256 price);
event Sell( uint256 indexed tokenId, address indexed to, uint256 qty, uint256 price);
event Commission( uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event Royalty( uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event Buy( uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event CancelSale(uint256 indexed tokenId, uint256 index);
event CancelBid(uint256 indexed tokenId, uint256 index);
event Change(address beneficiary, uint256 value);
constructor(
address _owner, address _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate,
string memory name, string memory symbol, bool _anyoneCanMint, string memory uri)
ERC1155YuzuInternal(_owner, uri, name, symbol, _anyoneCanMint)
{
require(_commissionRate + _royaltiesCommissionRate < 100, "Azuki: total commissions should be lower than 100");
admin = _admin;
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
}
/**
* Any user can sell X items at Y price each, valid ownership and qty of the sell will be handled by the UI
* All selling options are shown as “Listings” in the UI
* Any user can buy W items at Y price, of one listing, they cannot combine two listings in one transaction, given that W>0 and W<=Y
* Restrictions:
* Limit the sell to owned items, the user cannot sell items do not have
*/
function sell(uint256 tokenId, uint256 qty, uint256 price, address wallet) external {
// Limit the sell to owned items, the user cannot sell items do not have
require(balanceOf(_msgSender(), tokenId) >= qty, "Azuki: you do not have enough tokens to sell");
// set approval for all items of the user is not set already
if (!isApprovedForAll(_msgSender(), address(this))) {
setApprovalForAll(address(this), true);
}
// add the selling option to openSales
Sale memory sale = Sale(qty, price, _msgSender(), wallet);
// An owner can add only one selling listing for one item at a time, new listings for one item will replace the old ones
openSales[tokenId].push(sale);
openSalesLength[tokenId] = openSales[tokenId].length;
emit Sell(tokenId, _msgSender(), qty, price);
}
/**
* Return the extra funds sent to the contract
*/
function returnTheChange(uint256 total) internal {
if(msg.value > total) {
(bool success, ) = _msgSender().call{value:msg.value - total}("");
require(success, "Transfer failed.");
emit Change(_msgSender(), msg.value - total);
}
}
/**
* Buy an NTF item, specifying qty to buy and index offer
* Funds are transferred from the caller user directly, previous approval required
*/
function buy(uint256 tokenId, uint256 index, uint256 qty) payable external nonReentrant {
// validate user
require(openSales[tokenId][index].user != _msgSender() , "Azuki: the user cannot buy his own offer");
uint256 total = qty * openSales[tokenId][index].price;
// require enough funds
require(msg.value >= total, "Azuki: payment is too low");
// return the change
returnTheChange(total);
/**
* distribute funds between owner, creator and admin
* This function will transfer the funds from the buyer, which must have previously approve the funds to the contract, to the beneficiaries of the sale
*/
distributeFunds(total, _msgSender(), openSales[tokenId][index].wallet, tokenId);
// transfer ownership
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
callOptionalReturn(this, abi.encodeWithSelector(this.safeTransferFrom.selector, openSales[tokenId][index].user, _msgSender(), tokenId, qty, "0x"));
// substract items sold
openSales[tokenId][index].qty -= qty;
// remove the offer and reorder the array
if (openSales[tokenId][index].qty == 0) {
openSales[tokenId][index] = openSales[tokenId][openSales[tokenId].length-1];
openSales[tokenId].pop();
openSalesLength[tokenId] = openSales[tokenId].length;
}
}
// cancel the sale
function cancelSale(uint256 tokenId, uint256 index) external {
// Only the original bidder can cancel his bids
require(openSales[tokenId][index].user == _msgSender(), "Azuki: only the original seller can cancel his sales");
// remove the sale
openSales[tokenId][index] = openSales[tokenId][openSales[tokenId].length-1];
openSales[tokenId].pop();
openSalesLength[tokenId] = openSales[tokenId].length;
emit CancelSale(tokenId, index);
}
/**
* Any user can make an offer of X items at Y price each
* Funds of the offer are stored on the contract
* All offers are shown as “Offers” in the UI
* Restrictions
* A buyer cannot add an offer bigger than the total supply
*/
function bid(uint256 tokenId, uint256 qty, uint256 price) external payable nonReentrant {
require(qty>0, "Iksasumi: qty has to be positive");
require(price>0, "Iksasumi: price has to be positive");
require(qty <= totalSupply(tokenId), "Iksasumi: not enough items for sale");
// transfer qty * price tokens to the contract
uint256 total = qty * price;
// require enough funds
require(msg.value >= total, "Azuki: payment is too low");
// return the change
returnTheChange(total);
// record the offer
Offer memory theBid = Offer(qty, price, _msgSender());
openOffers[tokenId].push(theBid);
openOffersLength[tokenId] = openOffers[tokenId].length;
emit Bid(tokenId, _msgSender(), qty, price);
}
// cancel the offer and return funds
function cancelBid(uint256 tokenId, uint256 index) external nonReentrant {
// Only the original bidder can cancel his bids
require(openOffers[tokenId][index].user == _msgSender(), "Azuki: only the original bidder can cancel his bids");
// save the total
uint256 total = openOffers[tokenId][index].qty * openOffers[tokenId][index].price;
// remove the bid
openOffers[tokenId][index] = openOffers[tokenId][openOffers[tokenId].length-1];
openOffers[tokenId].pop();
openOffersLength[tokenId] = openOffers[tokenId].length;
// return the funds
(bool success, ) = _msgSender().call{value:total}("");
require(success, "Transfer failed.");
emit CancelBid(tokenId, index);
}
// owner accepts the bid and distribute the funds
function acceptBid(uint256 tokenId, uint256 index, uint256 qty) external nonReentrant {
// validate user
require(openOffers[tokenId][index].user != _msgSender() , "Azuki: the user cannot accept his own bid");
// set approval for all items of the user is not set already
if (!isApprovedForAll(_msgSender(), address(this))) {
setApprovalForAll(address(this), true);
}
// transfer item to bidder
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
callOptionalReturn(this, abi.encodeWithSelector(this.safeTransferFrom.selector, _msgSender(), openOffers[tokenId][index].user, tokenId, qty, "0x"));
/**
* distribute funds between owner, creator and admin
* This function will transfer the funds from the contract, which must have previously sent to the contract, to the beneficiaries of the sale
*/
distributeFunds(qty * openOffers[tokenId][index].price, openOffers[tokenId][index].user, _msgSender(), tokenId);
// substract items sold
openOffers[tokenId][index].qty -= qty;
// remove the offer and reorder the array
if (openOffers[tokenId][index].qty == 0) {
openOffers[tokenId][index] = openOffers[tokenId][openOffers[tokenId].length-1];
openOffers[tokenId].pop();
openOffersLength[tokenId] = openOffers[tokenId].length;
}
}
/**
* do the funds distribution between owner, creator and admin
* @param totalPrice the total value to distribute
* @param from if useTransferFrom is true then the "from" is the origin of the funds, if false, then the "from" is only used for logs purposes
* @param to is the owner of the token on sale / bid
* @param tokenId is the token being sold
*/
function distributeFunds(uint256 totalPrice, address from, address to, uint256 tokenId) internal {
// calculate amounts
uint256 amount4admin = totalPrice * commissionRate / 100;
uint256 amount4creator = totalPrice * royaltiesCommissionRate / 100;
uint256 amount4owner = totalPrice - amount4admin - amount4creator;
// to owner
(bool success, ) = to.call{value:amount4owner}("");
require(success, "Transfer failed.");
emit Buy(tokenId, from, to, amount4owner);
// to creator
if (amount4creator>0) {
(bool success2, ) = creators[tokenId].call{value:amount4creator}("");
require(success2, "Transfer failed.");
emit Royalty(tokenId, from, creators[tokenId], amount4creator);
}
// to admin
if (amount4admin>0) {
(bool success3, ) = admin.call{value:amount4admin}("");
require(success3, "Transfer failed.");
emit Commission(tokenId, from, admin, amount4admin);
}
}
/// Overrides minting function to keep track of item creators
function _mint(address to, uint256 tokenId, uint256 amount, bytes memory data) override internal {
creators[tokenId] = _msgSender();
super._mint(to, tokenId, amount, data);
}
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) override internal {
super._mintBatch(to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
creators[ids[i]] = _msgSender();
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC1155 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "Azuki: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "Azuki: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "Azuki: ERC20 operation did not succeed");
}
}
// update contract fields
function updateAdmin(address _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, bool _anyoneCanMint) external onlyOwner() {
require(_commissionRate + _royaltiesCommissionRate < 100, "Azuki: total commissions should be lower than 100");
admin = _admin;
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
anyoneCanMint = _anyoneCanMint;
}
}
| 6,018 |
22 | // Withdrawal mode data. | uint32[] public withdrawalMode;
| uint32[] public withdrawalMode;
| 16,184 |
2 | // Struct for books/ | struct Book {
string title;
string author;
string img;
uint bookid;
uint rental;
State state;
address payable lender;
address payable borrower;
}
| struct Book {
string title;
string author;
string img;
uint bookid;
uint rental;
State state;
address payable lender;
address payable borrower;
}
| 19,781 |
115 | // All financial functions are stripped from struct for visibility | mapping(uint256 => address) public projectIdToArtistAddress;
mapping(uint256 => string) public projectIdToCurrencySymbol;
mapping(uint256 => address) public projectIdToCurrencyAddress;
mapping(uint256 => uint256) public projectIdToPricePerTokenInWei;
mapping(uint256 => address) public projectIdToAdditionalPayee;
mapping(uint256 => uint256) public projectIdToAdditionalPayeePercentage;
mapping(uint256 => uint256) public projectIdToSecondaryMarketRoyaltyPercentage;
address public artblocksAddress;
uint256 public artblocksPercentage = 10;
| mapping(uint256 => address) public projectIdToArtistAddress;
mapping(uint256 => string) public projectIdToCurrencySymbol;
mapping(uint256 => address) public projectIdToCurrencyAddress;
mapping(uint256 => uint256) public projectIdToPricePerTokenInWei;
mapping(uint256 => address) public projectIdToAdditionalPayee;
mapping(uint256 => uint256) public projectIdToAdditionalPayeePercentage;
mapping(uint256 => uint256) public projectIdToSecondaryMarketRoyaltyPercentage;
address public artblocksAddress;
uint256 public artblocksPercentage = 10;
| 34,073 |
71 | // Check that SignedMintValidationParams have been initialized; if not, this is an invalid signer. | if (signedMintValidationParams.maxMaxTotalMintableByWallet == 0) {
revert InvalidSignature(signer);
}
| if (signedMintValidationParams.maxMaxTotalMintableByWallet == 0) {
revert InvalidSignature(signer);
}
| 30,208 |
84 | // subsidy controller checks payouts since last subsidy and resets counter return payoutSinceLastSubsidy_ uint / | function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) {
require( msg.sender == subsidyRouter, "Only subsidy controller" );
payoutSinceLastSubsidy_ = payoutSinceLastSubsidy;
payoutSinceLastSubsidy = 0;
}
| function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) {
require( msg.sender == subsidyRouter, "Only subsidy controller" );
payoutSinceLastSubsidy_ = payoutSinceLastSubsidy;
payoutSinceLastSubsidy = 0;
}
| 31,168 |
232 | // Borrows are repaid by another user (possibly the borrower). payer the account paying off the borrow borrower the account with the debt being payed off repayAmount the amount of undelrying tokens being returnedreturn (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. / | function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = bController.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_BCONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrowToken event */
emit RepayBorrowToken(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
bController.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
| function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = bController.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_BCONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrowToken event */
emit RepayBorrowToken(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
bController.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
| 12,298 |
75 | // Update the given pool's Ramp allocation point. Can only be called by the owner. | function set(uint256 _poolId, uint256 _rampPerBlock, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
poolInfo[_poolId].rampPerBlock = _rampPerBlock;
}
| function set(uint256 _poolId, uint256 _rampPerBlock, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
poolInfo[_poolId].rampPerBlock = _rampPerBlock;
}
| 18,318 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.