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
|
|---|---|---|---|---|
21
|
// Mints batch of new SqwidERC1155 tokens and adds them to the marketplace. /
|
function mintBatch(
uint256[] memory amounts,
string[] memory tokenURIs,
string[] calldata mimeTypes,
address[] memory royaltyRecipients,
uint256[] memory royaltyValues
|
function mintBatch(
uint256[] memory amounts,
string[] memory tokenURIs,
string[] calldata mimeTypes,
address[] memory royaltyRecipients,
uint256[] memory royaltyValues
| 19,685
|
14
|
// Convenience function for encoding claim data
|
function encodeClaim(Claim calldata claim) external pure returns (bytes memory encoded, bytes32 hash) {
encoded = abi.encodePacked(claim.index, claim.account, claim.cycle, claim.claim.tokens, claim.cumulativeAmounts);
hash = keccak256(encoded);
}
|
function encodeClaim(Claim calldata claim) external pure returns (bytes memory encoded, bytes32 hash) {
encoded = abi.encodePacked(claim.index, claim.account, claim.cycle, claim.claim.tokens, claim.cumulativeAmounts);
hash = keccak256(encoded);
}
| 7,176
|
38
|
// depositing into, or getting info for, the created market uses this ID
|
id_ = markets.length;
markets.push(
Market({
quoteToken: _quoteToken,
capacityInQuote: _booleans[0],
capacity: _market[0],
totalDebt: targetDebt,
maxPayout: maxPayout,
purchased: 0,
|
id_ = markets.length;
markets.push(
Market({
quoteToken: _quoteToken,
capacityInQuote: _booleans[0],
capacity: _market[0],
totalDebt: targetDebt,
maxPayout: maxPayout,
purchased: 0,
| 15,440
|
180
|
// Iron Bank /simple logic. do we get more apr than iron bank charges?if so, is that still true with increased pos?if not, should be reduce?made harder because we can't assume iron bank debt curve. So need to increment
|
function internalCreditOfficer() public view returns (bool borrowMore, uint256 amount) {
if(emergencyExit){
return(false, ironBankOutstandingDebtStored());
}
//how much credit we have
(, uint256 liquidity, uint256 shortfall) = ironBank.getAccountLiquidity(address(this));
uint256 underlyingPrice = ironBank.oracle().getUnderlyingPrice(address(ironBankToken));
if(underlyingPrice == 0){
return (false, 0);
}
liquidity = liquidity.mul(1e18).div(underlyingPrice);
shortfall = shortfall.mul(1e18).div(underlyingPrice);
//repay debt if iron bank wants its money back
if(shortfall > 0){
//note we only borrow 1 asset so can assume all our shortfall is from it
return(false, shortfall-1); //remove 1 incase of rounding errors
}
uint256 liquidityAvailable = want.balanceOf(address(ironBankToken));
uint256 remainingCredit = Math.min(liquidity, liquidityAvailable);
//our current supply rate.
//we only calculate once because it is expensive
uint256 currentSR = currentSupplyRate();
//iron bank borrow rate
uint256 ironBankBR = ironBankBorrowRate(0, true);
uint256 outstandingDebt = ironBankOutstandingDebtStored();
//we have internal credit limit. it is function on our own assets invested
//this means we can always repay our debt from our capital
uint256 maxCreditDesired = vault.strategies(address(this)).totalDebt.mul(maxIronBankLeverage);
//minIncrement must be > 0
if(maxCreditDesired <= step){
return (false, 0);
}
//we move in 10% increments
uint256 minIncrement = maxCreditDesired.div(step);
//we start at 1 to save some gas
uint256 increment = 1;
// if we have too much debt we return
//overshoot incase of dust
if(maxCreditDesired.mul(11).div(10) < outstandingDebt){
borrowMore = false;
amount = outstandingDebt - maxCreditDesired;
}
//if sr is > iron bank we borrow more. else return
else if(currentSR > ironBankBR){
remainingCredit = Math.min(maxCreditDesired - outstandingDebt, remainingCredit);
while(minIncrement.mul(increment) <= remainingCredit){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), false);
if(currentSR <= ironBankBR){
break;
}
increment++;
}
borrowMore = true;
amount = minIncrement.mul(increment-1);
}else{
while(minIncrement.mul(increment) <= outstandingDebt){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), true);
//we do increment before the if statement here
increment++;
if(currentSR > ironBankBR){
break;
}
}
borrowMore = false;
//special case to repay all
if(increment == 1){
amount = outstandingDebt;
}else{
amount = minIncrement.mul(increment - 1);
}
}
//we dont play with dust:
if (amount < debtThreshold) {
amount = 0;
}
}
|
function internalCreditOfficer() public view returns (bool borrowMore, uint256 amount) {
if(emergencyExit){
return(false, ironBankOutstandingDebtStored());
}
//how much credit we have
(, uint256 liquidity, uint256 shortfall) = ironBank.getAccountLiquidity(address(this));
uint256 underlyingPrice = ironBank.oracle().getUnderlyingPrice(address(ironBankToken));
if(underlyingPrice == 0){
return (false, 0);
}
liquidity = liquidity.mul(1e18).div(underlyingPrice);
shortfall = shortfall.mul(1e18).div(underlyingPrice);
//repay debt if iron bank wants its money back
if(shortfall > 0){
//note we only borrow 1 asset so can assume all our shortfall is from it
return(false, shortfall-1); //remove 1 incase of rounding errors
}
uint256 liquidityAvailable = want.balanceOf(address(ironBankToken));
uint256 remainingCredit = Math.min(liquidity, liquidityAvailable);
//our current supply rate.
//we only calculate once because it is expensive
uint256 currentSR = currentSupplyRate();
//iron bank borrow rate
uint256 ironBankBR = ironBankBorrowRate(0, true);
uint256 outstandingDebt = ironBankOutstandingDebtStored();
//we have internal credit limit. it is function on our own assets invested
//this means we can always repay our debt from our capital
uint256 maxCreditDesired = vault.strategies(address(this)).totalDebt.mul(maxIronBankLeverage);
//minIncrement must be > 0
if(maxCreditDesired <= step){
return (false, 0);
}
//we move in 10% increments
uint256 minIncrement = maxCreditDesired.div(step);
//we start at 1 to save some gas
uint256 increment = 1;
// if we have too much debt we return
//overshoot incase of dust
if(maxCreditDesired.mul(11).div(10) < outstandingDebt){
borrowMore = false;
amount = outstandingDebt - maxCreditDesired;
}
//if sr is > iron bank we borrow more. else return
else if(currentSR > ironBankBR){
remainingCredit = Math.min(maxCreditDesired - outstandingDebt, remainingCredit);
while(minIncrement.mul(increment) <= remainingCredit){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), false);
if(currentSR <= ironBankBR){
break;
}
increment++;
}
borrowMore = true;
amount = minIncrement.mul(increment-1);
}else{
while(minIncrement.mul(increment) <= outstandingDebt){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), true);
//we do increment before the if statement here
increment++;
if(currentSR > ironBankBR){
break;
}
}
borrowMore = false;
//special case to repay all
if(increment == 1){
amount = outstandingDebt;
}else{
amount = minIncrement.mul(increment - 1);
}
}
//we dont play with dust:
if (amount < debtThreshold) {
amount = 0;
}
}
| 4,538
|
1
|
// fee schedule, can be changed by governance, in bips performance fee is on any gains, base fee is on AUM/yearly
|
uint256 public constant max = 10000;
uint256 public performanceToTreasury = 1000;
uint256 public performanceToFarmer = 1000;
uint256 public baseToTreasury = 100;
uint256 public baseToFarmer = 100;
|
uint256 public constant max = 10000;
uint256 public performanceToTreasury = 1000;
uint256 public performanceToFarmer = 1000;
uint256 public baseToTreasury = 100;
uint256 public baseToFarmer = 100;
| 4,653
|
139
|
// solhint-disable func-name-mixedcase
|
function NAME() external view returns (string memory);
function VERSION() external view returns (string memory);
|
function NAME() external view returns (string memory);
function VERSION() external view returns (string memory);
| 40,067
|
131
|
// add to imbalance
|
conversionRatesContract.recordImbalance(
destToken,
int256(destAmount),
0,
block.number
);
|
conversionRatesContract.recordImbalance(
destToken,
int256(destAmount),
0,
block.number
);
| 24,280
|
32
|
// Smallest investment is 0.00001 ether
|
uint256 amountOfWei = msg.value;
require(amountOfWei >= 10000000000000);
uint256 amountOfMTP = 0;
uint256 absLowTimeBonusLimit = 0;
uint256 absMidTimeBonusLimit = 0;
uint256 absHighTimeBonusLimit = 0;
uint256 totalMTPAvailable = 0;
|
uint256 amountOfWei = msg.value;
require(amountOfWei >= 10000000000000);
uint256 amountOfMTP = 0;
uint256 absLowTimeBonusLimit = 0;
uint256 absMidTimeBonusLimit = 0;
uint256 absHighTimeBonusLimit = 0;
uint256 totalMTPAvailable = 0;
| 15,186
|
42
|
// MANAGER ONLY. Changes manager; We allow null addresses in case the manager wishes to wind down the SetToken.Modules may rely on the manager state, so only changable when unlocked /
|
function setManager(address _manager) external onlyManager {
require(!isLocked, "Only when unlocked");
address oldManager = manager;
manager = _manager;
emit ManagerEdited(_manager, oldManager);
}
|
function setManager(address _manager) external onlyManager {
require(!isLocked, "Only when unlocked");
address oldManager = manager;
manager = _manager;
emit ManagerEdited(_manager, oldManager);
}
| 35,005
|
23
|
// accept token into timelock_for address of future tokenholder_timestamp lock timestamp return result of operation: true if success/
|
function accept(address _for, uint _timestamp, uint _tvalue) public returns(bool){
require(_for != address(0));
require(_for != address(this));
require(_timestamp > getTimestamp_());
require(_tvalue > 0);
uint _contractBalance = contractBalance_();
uint _balance = balance[_for][_timestamp];
uint _totalBalance = totalBalance;
require(token.transferFrom(msg.sender, this, _tvalue));
uint _value = contractBalance_().sub(_contractBalance);
balance[_for][_timestamp] = _balance.add(_value);
totalBalance = _totalBalance.add(_value);
emit Lock(msg.sender, _for, _timestamp, _value);
return true;
}
|
function accept(address _for, uint _timestamp, uint _tvalue) public returns(bool){
require(_for != address(0));
require(_for != address(this));
require(_timestamp > getTimestamp_());
require(_tvalue > 0);
uint _contractBalance = contractBalance_();
uint _balance = balance[_for][_timestamp];
uint _totalBalance = totalBalance;
require(token.transferFrom(msg.sender, this, _tvalue));
uint _value = contractBalance_().sub(_contractBalance);
balance[_for][_timestamp] = _balance.add(_value);
totalBalance = _totalBalance.add(_value);
emit Lock(msg.sender, _for, _timestamp, _value);
return true;
}
| 45,674
|
76
|
// Allows to add a contract to handle fallback calls./Only fallback calls without value and with data will be forwarded./This can only be done via a Safe transaction./handler contract to handle fallback calls.
|
function setFallbackHandler(address handler) public authorized {
internalSetFallbackHandler(handler);
emit ChangedFallbackHandler(handler);
}
|
function setFallbackHandler(address handler) public authorized {
internalSetFallbackHandler(handler);
emit ChangedFallbackHandler(handler);
}
| 51,466
|
7
|
// This is an access control role for entities that may spend tokens /
|
abstract contract SpenderRole {
using EnumerableSet for EnumerableSet.AddressSet;
event SpenderAdded(address indexed account);
event SpenderRemoved(address indexed account);
EnumerableSet.AddressSet private _spenders;
constructor() {
_addSpender(msg.sender);
}
modifier onlySpender() {
require(isSpender(msg.sender));
_;
}
function isSpender(address account) public view returns (bool) {
return _spenders.contains(account);
}
function addSpender(address account) public onlySpender {
_addSpender(account);
}
function renounceSpender() public {
_removeSpender(msg.sender);
}
function _addSpender(address account) internal {
_spenders.add(account);
emit SpenderAdded(account);
}
function _removeSpender(address account) internal {
_spenders.remove(account);
emit SpenderRemoved(account);
}
}
|
abstract contract SpenderRole {
using EnumerableSet for EnumerableSet.AddressSet;
event SpenderAdded(address indexed account);
event SpenderRemoved(address indexed account);
EnumerableSet.AddressSet private _spenders;
constructor() {
_addSpender(msg.sender);
}
modifier onlySpender() {
require(isSpender(msg.sender));
_;
}
function isSpender(address account) public view returns (bool) {
return _spenders.contains(account);
}
function addSpender(address account) public onlySpender {
_addSpender(account);
}
function renounceSpender() public {
_removeSpender(msg.sender);
}
function _addSpender(address account) internal {
_spenders.add(account);
emit SpenderAdded(account);
}
function _removeSpender(address account) internal {
_spenders.remove(account);
emit SpenderRemoved(account);
}
}
| 14,055
|
95
|
// Manages forging
|
contract ItemForge is ItemMarket {
event Forge(uint256 forgedItemID);
///@notice Forge items together
function forgeItems(uint256 _parentItemID, uint256 _childItemID) external
onlyOwnerOfItem(_parentItemID)
onlyOwnerOfItem(_childItemID)
ifItemForSaleThenCancelSale(_parentItemID)
ifItemForSaleThenCancelSale(_childItemID) {
//checks if items are not the same
require(_parentItemID != _childItemID);
Item storage parentItem = items[_parentItemID];
Item storage childItem = items[_childItemID];
//take child item off, because child item will be burned
if(childItem.onChamp){
takeOffItem(childItem.onChampId, childItem.itemType);
}
//update parent item
parentItem.attackPower = (parentItem.attackPower > childItem.attackPower) ? parentItem.attackPower : childItem.attackPower;
parentItem.defencePower = (parentItem.defencePower > childItem.defencePower) ? parentItem.defencePower : childItem.defencePower;
parentItem.cooldownReduction = (parentItem.cooldownReduction > childItem.cooldownReduction) ? parentItem.cooldownReduction : childItem.cooldownReduction;
parentItem.itemRarity = uint8(6);
//burn child item
transferItem(msg.sender, address(0), _childItemID);
emit Forge(_parentItemID);
}
}
|
contract ItemForge is ItemMarket {
event Forge(uint256 forgedItemID);
///@notice Forge items together
function forgeItems(uint256 _parentItemID, uint256 _childItemID) external
onlyOwnerOfItem(_parentItemID)
onlyOwnerOfItem(_childItemID)
ifItemForSaleThenCancelSale(_parentItemID)
ifItemForSaleThenCancelSale(_childItemID) {
//checks if items are not the same
require(_parentItemID != _childItemID);
Item storage parentItem = items[_parentItemID];
Item storage childItem = items[_childItemID];
//take child item off, because child item will be burned
if(childItem.onChamp){
takeOffItem(childItem.onChampId, childItem.itemType);
}
//update parent item
parentItem.attackPower = (parentItem.attackPower > childItem.attackPower) ? parentItem.attackPower : childItem.attackPower;
parentItem.defencePower = (parentItem.defencePower > childItem.defencePower) ? parentItem.defencePower : childItem.defencePower;
parentItem.cooldownReduction = (parentItem.cooldownReduction > childItem.cooldownReduction) ? parentItem.cooldownReduction : childItem.cooldownReduction;
parentItem.itemRarity = uint8(6);
//burn child item
transferItem(msg.sender, address(0), _childItemID);
emit Forge(_parentItemID);
}
}
| 65,499
|
9
|
// uint256 maxIssue = 10000001018; uint256 basePrice = 20001018; 1 ETH = 2000 TCV
|
emit Received(msg.sender, msg.value);
require(msg.value > 0);
uint256 remainingVotes = balanceOf(owner);
require(balanceOf(owner) > 0, "All TCV already sold.");
uint256 weiSent = msg.value; // Calculate tokens to sell
uint256 votesBought = (weiSent * basePrice) / (1 ether);
uint256 returnWei = 0;
console.log("Wei received: %s", weiSent);
console.log("TCV requested: %s", votesBought);
|
emit Received(msg.sender, msg.value);
require(msg.value > 0);
uint256 remainingVotes = balanceOf(owner);
require(balanceOf(owner) > 0, "All TCV already sold.");
uint256 weiSent = msg.value; // Calculate tokens to sell
uint256 votesBought = (weiSent * basePrice) / (1 ether);
uint256 returnWei = 0;
console.log("Wei received: %s", weiSent);
console.log("TCV requested: %s", votesBought);
| 25,758
|
4
|
// restarts the contract after a shutdown
|
function restart() external {
require(msg.sender == owner, "Only the owner can shutdown the contract");
isShutdown = false;
}
|
function restart() external {
require(msg.sender == owner, "Only the owner can shutdown the contract");
isShutdown = false;
}
| 8,300
|
35
|
// Base contract for ContractRegistry clients/
|
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures";
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant NON_STANDARD_TOKEN_REGISTRY = "NonStandardTokenRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
bytes32 internal constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit";
bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory";
bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
IContractRegistry public registry; // address of the current contract-registry
IContractRegistry public prevRegistry; // address of the previous contract-registry
bool public adminOnly; // only an administrator can update the contract-registry
/**
* @dev verifies that the caller is mapped to the given contract name
*
* @param _contractName contract name
*/
modifier only(bytes32 _contractName) {
require(msg.sender == addressOf(_contractName));
_;
}
/**
* @dev initializes a new ContractRegistryClient instance
*
* @param _registry address of a contract-registry contract
*/
constructor(IContractRegistry _registry) internal validAddress(_registry) {
registry = IContractRegistry(_registry);
prevRegistry = IContractRegistry(_registry);
}
/**
* @dev updates to the new contract-registry
*/
function updateRegistry() public {
// verify that this function is permitted
require(!adminOnly || isAdmin());
// get the new contract-registry
address newRegistry = addressOf(CONTRACT_REGISTRY);
// verify that the new contract-registry is different and not zero
require(newRegistry != address(registry) && newRegistry != address(0));
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0));
// save a backup of the current contract-registry before replacing it
prevRegistry = registry;
// replace the current contract-registry with the new contract-registry
registry = IContractRegistry(newRegistry);
}
/**
* @dev restores the previous contract-registry
*/
function restoreRegistry() public {
// verify that this function is permitted
require(isAdmin());
// restore the previous contract-registry
registry = prevRegistry;
}
/**
* @dev restricts the permission to update the contract-registry
*
* @param _adminOnly indicates whether or not permission is restricted to administrator only
*/
function restrictRegistryUpdate(bool _adminOnly) public {
// verify that this function is permitted
require(adminOnly != _adminOnly && isAdmin());
// change the permission to update the contract-registry
adminOnly = _adminOnly;
}
/**
* @dev returns whether or not the caller is an administrator
*/
function isAdmin() internal view returns (bool) {
return msg.sender == owner;
}
/**
* @dev returns the address associated with the given contract name
*
* @param _contractName contract name
*
* @return contract address
*/
function addressOf(bytes32 _contractName) internal view returns (address) {
return registry.addressOf(_contractName);
}
}
|
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_FEATURES = "ContractFeatures";
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant NON_STANDARD_TOKEN_REGISTRY = "NonStandardTokenRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
bytes32 internal constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit";
bytes32 internal constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory";
bytes32 internal constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant BANCOR_CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant BANCOR_CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
IContractRegistry public registry; // address of the current contract-registry
IContractRegistry public prevRegistry; // address of the previous contract-registry
bool public adminOnly; // only an administrator can update the contract-registry
/**
* @dev verifies that the caller is mapped to the given contract name
*
* @param _contractName contract name
*/
modifier only(bytes32 _contractName) {
require(msg.sender == addressOf(_contractName));
_;
}
/**
* @dev initializes a new ContractRegistryClient instance
*
* @param _registry address of a contract-registry contract
*/
constructor(IContractRegistry _registry) internal validAddress(_registry) {
registry = IContractRegistry(_registry);
prevRegistry = IContractRegistry(_registry);
}
/**
* @dev updates to the new contract-registry
*/
function updateRegistry() public {
// verify that this function is permitted
require(!adminOnly || isAdmin());
// get the new contract-registry
address newRegistry = addressOf(CONTRACT_REGISTRY);
// verify that the new contract-registry is different and not zero
require(newRegistry != address(registry) && newRegistry != address(0));
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(IContractRegistry(newRegistry).addressOf(CONTRACT_REGISTRY) != address(0));
// save a backup of the current contract-registry before replacing it
prevRegistry = registry;
// replace the current contract-registry with the new contract-registry
registry = IContractRegistry(newRegistry);
}
/**
* @dev restores the previous contract-registry
*/
function restoreRegistry() public {
// verify that this function is permitted
require(isAdmin());
// restore the previous contract-registry
registry = prevRegistry;
}
/**
* @dev restricts the permission to update the contract-registry
*
* @param _adminOnly indicates whether or not permission is restricted to administrator only
*/
function restrictRegistryUpdate(bool _adminOnly) public {
// verify that this function is permitted
require(adminOnly != _adminOnly && isAdmin());
// change the permission to update the contract-registry
adminOnly = _adminOnly;
}
/**
* @dev returns whether or not the caller is an administrator
*/
function isAdmin() internal view returns (bool) {
return msg.sender == owner;
}
/**
* @dev returns the address associated with the given contract name
*
* @param _contractName contract name
*
* @return contract address
*/
function addressOf(bytes32 _contractName) internal view returns (address) {
return registry.addressOf(_contractName);
}
}
| 14,694
|
7
|
// This extension is shared, not single-creator. So we must ensurethat a claim's initializer is an admin on the creator contract creatorContractAddressthe address of the creator contract to check the admin against /
|
modifier creatorAdminRequired(address creatorContractAddress) {
require(IAdminControl(creatorContractAddress).isAdmin(msg.sender), "Wallet is not an administrator for contract");
_;
}
|
modifier creatorAdminRequired(address creatorContractAddress) {
require(IAdminControl(creatorContractAddress).isAdmin(msg.sender), "Wallet is not an administrator for contract");
_;
}
| 12,810
|
56
|
// 5. Total mAsset is the difference between values
|
totalmAssets = k0 - k1;
|
totalmAssets = k0 - k1;
| 48,219
|
81
|
// return the current total amount of tokens staked by all users /
|
function totalStaked() external view returns (uint256);
|
function totalStaked() external view returns (uint256);
| 19,792
|
104
|
// Override this function.This version is to keep track of BaseRelayRecipient you are usingin your contract. /
|
function versionRecipient() external pure override returns (string memory) {
return "2";
}
|
function versionRecipient() external pure override returns (string memory) {
return "2";
}
| 65,390
|
18
|
// Loop once to get the total count.
|
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_curEntry = entries[_curEntry.next];
_size++;
}
|
Entry memory _curEntry = entries[0x0];
while (_curEntry.next > 0) {
_curEntry = entries[_curEntry.next];
_size++;
}
| 21,630
|
7
|
// Removes an existing extension from the router.
|
function removeExtension(string memory _extensionName) external {
require(_canSetExtension(), "BaseRouter: caller not authorized.");
_removeExtension(_extensionName);
}
|
function removeExtension(string memory _extensionName) external {
require(_canSetExtension(), "BaseRouter: caller not authorized.");
_removeExtension(_extensionName);
}
| 10,201
|
11
|
// deprecated - but useful to reset a list of addresses to be able to presale mint again./
|
function initPresaleMerkleWalletList(address[] memory walletList) external onlyOwner {
for (uint i; i < walletList.length; i++) {
presaleMerkleWalletList[walletList[i]] = false;
}
}
|
function initPresaleMerkleWalletList(address[] memory walletList) external onlyOwner {
for (uint i; i < walletList.length; i++) {
presaleMerkleWalletList[walletList[i]] = false;
}
}
| 68,035
|
11
|
// This probably isn't necessary, but it doesn't hurt.
|
require(
appDataB.variable.allocationId == allocationId,
'Indexer turn: allocationId must match'
);
require(
recoverAttestationSigner(appDataB) == allocationId,
'Indexer Attestation: must be signed with the allocationId'
);
|
require(
appDataB.variable.allocationId == allocationId,
'Indexer turn: allocationId must match'
);
require(
recoverAttestationSigner(appDataB) == allocationId,
'Indexer Attestation: must be signed with the allocationId'
);
| 55,494
|
9
|
// Nonces for each VRF key from which randomness has been requested. Must stay in sync with VRFCoordinator[_keyHash][this]
|
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
|
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
| 6,697
|
15
|
// Our contract inherits from ERC721, which is the standard NFT contract!
|
contract TCAGame is ERC721 {
struct CharacterAttributes {
uint characterIndex;
string name;
string imageURI;
uint hp;
uint maxHp;
uint attackDamage;
}
// The tokenId is the NFTs unique identifier, it's just a number that goes
// 0, 1, 2, 3, etc.
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
CharacterAttributes[] defaultCharacters;
// We create a mapping from the nft's tokenId => that NFTs attributes.
mapping(uint256 => CharacterAttributes) public nftHolderAttributes;
// A mapping from an address => the NFTs tokenId. Gives me an ez way
// to store the owner of the NFT and reference it later.
mapping(address => uint256) public nftHolders;
constructor(
string[] memory characterNames,
string[] memory characterImageURIs,
uint[] memory characterHp,
uint[] memory characterAttackDmg
// Below, you can also see I added some special identifier symbols for our NFT.
// This is the name and symbol for our token, ex Ethereum and ETH. I just call mine
// Heroes and HERO. Remember, an NFT is just a token!
)
ERC721("Daron", "DAR")
{
for(uint i = 0; i < characterNames.length; i += 1) {
defaultCharacters.push(CharacterAttributes({
characterIndex: i,
name: characterNames[i],
imageURI: characterImageURIs[i],
hp: characterHp[i],
maxHp: characterHp[i],
attackDamage: characterAttackDmg[i]
}));
CharacterAttributes memory c = defaultCharacters[i];
// Hardhat's use of console.log() allows up to 4 parameters in any order of following types: uint, string, bool, address
console.log("Done initializing %s w/ HP %s, img %s", c.name, c.hp, c.imageURI);
}
// I increment _tokenIds here so that my first NFT has an ID of 1.
// More on this in the lesson!
_tokenIds.increment();
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
CharacterAttributes memory charAttributes = nftHolderAttributes[_tokenId];
string memory strHp = Strings.toString(charAttributes.hp);
string memory strMaxHp = Strings.toString(charAttributes.maxHp);
string memory strAttackDamage = Strings.toString(charAttributes.attackDamage);
string memory json = Base64.encode(
abi.encodePacked(
'{"name": "',
charAttributes.name,
' -- NFT #: ',
Strings.toString(_tokenId),
'", "description": "A NFT to play in the game TCA Metaverse!", "image": "',
charAttributes.imageURI,
'", "attributes": [ { "trait_type": "Health Points", "value": ',strHp,', "max_value":',strMaxHp,'}, { "trait_type": "Attack Damage", "value": ',
strAttackDamage,'} ]}'
)
);
string memory output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
}
// Users would be able to hit this function and get their NFT based on the
// characterId they send in!
function mintCharacterNFT(uint _characterIndex) external {
// Get current tokenId (starts at 1 since we incremented in the constructor).
uint256 newItemId = _tokenIds.current();
// The magical function! Assigns the tokenId to the caller's wallet address.
_safeMint(msg.sender, newItemId);
// We map the tokenId => their character attributes. More on this in
// the lesson below.
nftHolderAttributes[newItemId] = CharacterAttributes({
characterIndex: _characterIndex,
name: defaultCharacters[_characterIndex].name,
imageURI: defaultCharacters[_characterIndex].imageURI,
hp: defaultCharacters[_characterIndex].hp,
maxHp: defaultCharacters[_characterIndex].maxHp,
attackDamage: defaultCharacters[_characterIndex].attackDamage
});
console.log("Minted NFT Daron w/ tokenId %s and characterIndex %s", newItemId, _characterIndex);
// Keep an easy way to see who owns what NFT.
nftHolders[msg.sender] = newItemId;
// Increment the tokenId for the next person that uses it.
_tokenIds.increment();
}
}
|
contract TCAGame is ERC721 {
struct CharacterAttributes {
uint characterIndex;
string name;
string imageURI;
uint hp;
uint maxHp;
uint attackDamage;
}
// The tokenId is the NFTs unique identifier, it's just a number that goes
// 0, 1, 2, 3, etc.
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
CharacterAttributes[] defaultCharacters;
// We create a mapping from the nft's tokenId => that NFTs attributes.
mapping(uint256 => CharacterAttributes) public nftHolderAttributes;
// A mapping from an address => the NFTs tokenId. Gives me an ez way
// to store the owner of the NFT and reference it later.
mapping(address => uint256) public nftHolders;
constructor(
string[] memory characterNames,
string[] memory characterImageURIs,
uint[] memory characterHp,
uint[] memory characterAttackDmg
// Below, you can also see I added some special identifier symbols for our NFT.
// This is the name and symbol for our token, ex Ethereum and ETH. I just call mine
// Heroes and HERO. Remember, an NFT is just a token!
)
ERC721("Daron", "DAR")
{
for(uint i = 0; i < characterNames.length; i += 1) {
defaultCharacters.push(CharacterAttributes({
characterIndex: i,
name: characterNames[i],
imageURI: characterImageURIs[i],
hp: characterHp[i],
maxHp: characterHp[i],
attackDamage: characterAttackDmg[i]
}));
CharacterAttributes memory c = defaultCharacters[i];
// Hardhat's use of console.log() allows up to 4 parameters in any order of following types: uint, string, bool, address
console.log("Done initializing %s w/ HP %s, img %s", c.name, c.hp, c.imageURI);
}
// I increment _tokenIds here so that my first NFT has an ID of 1.
// More on this in the lesson!
_tokenIds.increment();
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
CharacterAttributes memory charAttributes = nftHolderAttributes[_tokenId];
string memory strHp = Strings.toString(charAttributes.hp);
string memory strMaxHp = Strings.toString(charAttributes.maxHp);
string memory strAttackDamage = Strings.toString(charAttributes.attackDamage);
string memory json = Base64.encode(
abi.encodePacked(
'{"name": "',
charAttributes.name,
' -- NFT #: ',
Strings.toString(_tokenId),
'", "description": "A NFT to play in the game TCA Metaverse!", "image": "',
charAttributes.imageURI,
'", "attributes": [ { "trait_type": "Health Points", "value": ',strHp,', "max_value":',strMaxHp,'}, { "trait_type": "Attack Damage", "value": ',
strAttackDamage,'} ]}'
)
);
string memory output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
}
// Users would be able to hit this function and get their NFT based on the
// characterId they send in!
function mintCharacterNFT(uint _characterIndex) external {
// Get current tokenId (starts at 1 since we incremented in the constructor).
uint256 newItemId = _tokenIds.current();
// The magical function! Assigns the tokenId to the caller's wallet address.
_safeMint(msg.sender, newItemId);
// We map the tokenId => their character attributes. More on this in
// the lesson below.
nftHolderAttributes[newItemId] = CharacterAttributes({
characterIndex: _characterIndex,
name: defaultCharacters[_characterIndex].name,
imageURI: defaultCharacters[_characterIndex].imageURI,
hp: defaultCharacters[_characterIndex].hp,
maxHp: defaultCharacters[_characterIndex].maxHp,
attackDamage: defaultCharacters[_characterIndex].attackDamage
});
console.log("Minted NFT Daron w/ tokenId %s and characterIndex %s", newItemId, _characterIndex);
// Keep an easy way to see who owns what NFT.
nftHolders[msg.sender] = newItemId;
// Increment the tokenId for the next person that uses it.
_tokenIds.increment();
}
}
| 18,952
|
366
|
// Initializes the BoiChillClub NFT. name_ The name of the token. symbol_ The symbol of the token. baseUri_ The base URI for token metadata. paymentToken_ The address of the payment token. amount_ The amount of payment token required for each purchase. /
|
constructor(
string memory name_,
string memory symbol_,
string memory baseUri_,
address paymentToken_,
uint256 amount_
) ERC721(name_, symbol_) {
address sender = _msgSender();
_setBaseURI(baseUri_);
_setupPrimarySaleRecipient(sender);
|
constructor(
string memory name_,
string memory symbol_,
string memory baseUri_,
address paymentToken_,
uint256 amount_
) ERC721(name_, symbol_) {
address sender = _msgSender();
_setBaseURI(baseUri_);
_setupPrimarySaleRecipient(sender);
| 40,029
|
4
|
// uniswap
|
uint256 public lastTradingFeeDistribution;
uint256 public sixMonthLock;
address public tokenRecipient;
|
uint256 public lastTradingFeeDistribution;
uint256 public sixMonthLock;
address public tokenRecipient;
| 43,254
|
40
|
// Trade start check
|
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
|
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
| 33,902
|
52
|
// similar to a nonce that avoids replay attacks this allows a single execution every x seconds for a given subscription subscriptionHash=> next valid block number
|
mapping(bytes32 => uint256) public nextValidTimestamp;
|
mapping(bytes32 => uint256) public nextValidTimestamp;
| 49,959
|
4
|
// YOU WON
|
if (racerScore[msg.sender] >= SCORE_TO_WIN) {
msg.sender.transfer(this.balance);
}
|
if (racerScore[msg.sender] >= SCORE_TO_WIN) {
msg.sender.transfer(this.balance);
}
| 28,190
|
111
|
// approve sender as they have paid the required amount
|
_approvePurchaser(msg.sender, _tokenId);
|
_approvePurchaser(msg.sender, _tokenId);
| 5,178
|
72
|
// Set a Trading Ruleonly callable by the owner of the contract1 senderToken = priceCoef10^(-priceExp)signerTokensenderToken address Address of an ERC-20 token the delegate would sendsignerToken address Address of an ERC-20 token the consumer would sendmaxSenderAmount uint256 Maximum amount of ERC-20 token the delegate would sendpriceCoef uint256 Whole number that will be multiplied by 10^(-priceExp) - the price coefficientpriceExp uint256 Exponent of the price to indicate location of the decimal priceCoef10^(-priceExp)/
|
function setRule(
address senderToken,
address signerToken,
uint256 maxSenderAmount,
uint256 priceCoef,
uint256 priceExp
|
function setRule(
address senderToken,
address signerToken,
uint256 maxSenderAmount,
uint256 priceCoef,
uint256 priceExp
| 10,195
|
30
|
// Re-insert trove in to the sorted list
|
uint newNICR = _getNewNominalICRFromTroveChange(vars.coll, vars.debt, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease);
sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);
emit TroveUpdated(_borrower, vars.newDebt, vars.newColl, vars.stake, BorrowerOperation.adjustTrove);
emit LUSDBorrowingFeePaid(msg.sender, vars.LUSDFee);
|
uint newNICR = _getNewNominalICRFromTroveChange(vars.coll, vars.debt, vars.collChange, vars.isCollIncrease, vars.netDebtChange, _isDebtIncrease);
sortedTroves.reInsert(_borrower, newNICR, _upperHint, _lowerHint);
emit TroveUpdated(_borrower, vars.newDebt, vars.newColl, vars.stake, BorrowerOperation.adjustTrove);
emit LUSDBorrowingFeePaid(msg.sender, vars.LUSDFee);
| 14,278
|
235
|
// IBEP20
|
function getOwner() external view override returns (address) {
return owner();
}
|
function getOwner() external view override returns (address) {
return owner();
}
| 42,665
|
9
|
// function to buy property tokens availaible for selling
|
function purchasePropertyTokens(address buyer,uint voucher_token_offered,address property_token_owner,uint property_id) public {
require(property_token_sell[property_token_owner][property_id] >= voucher_token_offered);
require(getVoucherBalance(buyer)>=voucher_token_offered);
ERC20 _erc20_property_token_instance = _property.token_prop(property_token_owner,property_id);
require(voucher_token_offered <= _erc20_property_token_instance._balances(property_token_owner));
erc.transfer(buyer,property_token_owner,voucher_token_offered);
_erc20_property_token_instance.transfer(property_token_owner,buyer,voucher_token_offered);
_property.addProperties(buyer,_property.properties(property_id-1));
_property.addToken_Prop(buyer,property_id,_erc20_property_token_instance);
property_token_sell[property_token_owner][property_id] -= voucher_token_offered;
uint256 _ind = index_of_property_in_array[property_token_owner][property_id];
if(property_token_sell[property_token_owner][property_id] != 0){
token_details[_ind].quantity -= voucher_token_offered;
}
else
{
total_Properties_tokens_for_sell--;
delete token_details[_ind];
delete index_of_property_in_array[property_token_owner][property_id];
}
}
|
function purchasePropertyTokens(address buyer,uint voucher_token_offered,address property_token_owner,uint property_id) public {
require(property_token_sell[property_token_owner][property_id] >= voucher_token_offered);
require(getVoucherBalance(buyer)>=voucher_token_offered);
ERC20 _erc20_property_token_instance = _property.token_prop(property_token_owner,property_id);
require(voucher_token_offered <= _erc20_property_token_instance._balances(property_token_owner));
erc.transfer(buyer,property_token_owner,voucher_token_offered);
_erc20_property_token_instance.transfer(property_token_owner,buyer,voucher_token_offered);
_property.addProperties(buyer,_property.properties(property_id-1));
_property.addToken_Prop(buyer,property_id,_erc20_property_token_instance);
property_token_sell[property_token_owner][property_id] -= voucher_token_offered;
uint256 _ind = index_of_property_in_array[property_token_owner][property_id];
if(property_token_sell[property_token_owner][property_id] != 0){
token_details[_ind].quantity -= voucher_token_offered;
}
else
{
total_Properties_tokens_for_sell--;
delete token_details[_ind];
delete index_of_property_in_array[property_token_owner][property_id];
}
}
| 27,327
|
225
|
// Emitted when `account` is granted `role`. `sender` is the account that originated the contract call, an admin role
|
* bearer except when using {_setupRole}.
*/
event RoleGranted(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
|
* bearer except when using {_setupRole}.
*/
event RoleGranted(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(
bytes32 indexed role,
address indexed account,
address indexed sender
);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
| 6,472
|
64
|
// Disable whitelisting /
|
function disableWhitelist() public onlyOwner {
whitelistEnabled = false;
}
|
function disableWhitelist() public onlyOwner {
whitelistEnabled = false;
}
| 29,810
|
166
|
// Stop trasfer fee payment for tokens. return true if the operation was successful./
|
function finishTransferFeePayment() public onlyOwner returns(bool finished) {
require(!transferFeePaymentFinished, "transfer fee finished");
transferFeePaymentFinished = true;
emit LogTransferFeePaymentFinished(msg.sender);
return true;
}
|
function finishTransferFeePayment() public onlyOwner returns(bool finished) {
require(!transferFeePaymentFinished, "transfer fee finished");
transferFeePaymentFinished = true;
emit LogTransferFeePaymentFinished(msg.sender);
return true;
}
| 25,616
|
228
|
// revoke a mint request, Delete the mintOperation index of the request (visible in the RequestMint event accompanying the original request)/
|
function revokeMint(uint256 _index) external onlyMintKeyOrOwner {
delete mintOperations[_index];
emit RevokeMint(_index);
}
|
function revokeMint(uint256 _index) external onlyMintKeyOrOwner {
delete mintOperations[_index];
emit RevokeMint(_index);
}
| 1,109
|
179
|
// We need ownership to create subnodes
|
require(_ens.owner(_rootNode) == address(this), ERROR_NO_NODE_OWNERSHIP);
ens = _ens;
rootNode = _rootNode;
|
require(_ens.owner(_rootNode) == address(this), ERROR_NO_NODE_OWNERSHIP);
ens = _ens;
rootNode = _rootNode;
| 16,437
|
37
|
// Withdraws staked tokens from the pool/amount The amount of tokens to withdraw
|
function withdraw(uint256 amount) external {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (amount == 0) {
return;
}
/// -----------------------------------------------------------------------
/// Storage loads
/// -----------------------------------------------------------------------
uint256 accountBalance = balanceOf[msg.sender];
uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable();
uint256 totalSupply_ = totalSupply;
uint256 rewardPerToken_ = _rewardPerToken(
totalSupply_,
lastTimeRewardApplicable_,
rewardRate
);
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue rewards
rewardPerTokenStored = rewardPerToken_;
lastUpdateTime = lastTimeRewardApplicable_;
rewards[msg.sender] = _earned(
msg.sender,
accountBalance,
rewardPerToken_,
rewards[msg.sender]
);
userRewardPerTokenPaid[msg.sender] = rewardPerToken_;
// withdraw stake
balanceOf[msg.sender] = accountBalance - amount;
// total supply has 1:1 relationship with staked amounts
// so can't ever underflow
unchecked {
totalSupply = totalSupply_ - amount;
}
/// -----------------------------------------------------------------------
/// Effects
/// -----------------------------------------------------------------------
stakeToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
|
function withdraw(uint256 amount) external {
/// -----------------------------------------------------------------------
/// Validation
/// -----------------------------------------------------------------------
if (amount == 0) {
return;
}
/// -----------------------------------------------------------------------
/// Storage loads
/// -----------------------------------------------------------------------
uint256 accountBalance = balanceOf[msg.sender];
uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable();
uint256 totalSupply_ = totalSupply;
uint256 rewardPerToken_ = _rewardPerToken(
totalSupply_,
lastTimeRewardApplicable_,
rewardRate
);
/// -----------------------------------------------------------------------
/// State updates
/// -----------------------------------------------------------------------
// accrue rewards
rewardPerTokenStored = rewardPerToken_;
lastUpdateTime = lastTimeRewardApplicable_;
rewards[msg.sender] = _earned(
msg.sender,
accountBalance,
rewardPerToken_,
rewards[msg.sender]
);
userRewardPerTokenPaid[msg.sender] = rewardPerToken_;
// withdraw stake
balanceOf[msg.sender] = accountBalance - amount;
// total supply has 1:1 relationship with staked amounts
// so can't ever underflow
unchecked {
totalSupply = totalSupply_ - amount;
}
/// -----------------------------------------------------------------------
/// Effects
/// -----------------------------------------------------------------------
stakeToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
| 14,676
|
345
|
// Expiratory time now becomes the current time (emergency shutdown time). Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
|
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePrice(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
|
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePrice(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
| 34,888
|
38
|
// address _token
|
) public {
require(hardCap > minimalGoal);
require(openingTime < closingTime);
//token = BlockchainBikeToken(_token);
crowdsale = address(this);
forSale = 0xf6ACFDba39D8F786D0D2781A1D20C82E47adF8b7;
ecoSystemFund = 0x5A77aAE15258a2a4445C701d63dbE74016F7e629;
founders = 0xA80A449514541aeEcd3e17BECcC74a86e3de6bfA;
team = 0x309d62B8eaDF717b76296326CA35bB8f2D996B1a;
advisers = 0xc4319217ca328F7518c463D6D3e78f68acc5B076;
bounty = 0x3605e4E99efFaB70D0C84aA2beA530683824246f;
affiliate = 0x1709365100eD9B7c417E0dF0fdc32027af1DAff1;
/*forSale = _forSale;
ecoSystemFund = _ecoSystemFund;
founders = _founders;
team = _team;
advisers = _advisers;
bounty = _bountry;
affiliate = _affiliate;*/
balances[team] = totalSupply * 28 / 100;
balances[founders] = totalSupply * 12 / 100;
balances[bounty] = totalSupply * 1 / 100;
balances[affiliate] = totalSupply * 1 / 100;
balances[advisers] = totalSupply * 1 / 100;
balances[ecoSystemFund] = totalSupply * 5 / 100;
balances[forSale] = totalSupply * 52 / 100;
emit Transfer(0x0, team, balances[team]);
emit Transfer(0x0, founders, balances[founders]);
emit Transfer(0x0, bounty, balances[bounty]);
emit Transfer(0x0, affiliate, balances[affiliate]);
emit Transfer(0x0, advisers, balances[advisers]);
emit Transfer(0x0, ecoSystemFund, balances[ecoSystemFund]);
emit Transfer(0x0, forSale, balances[forSale]);
}
|
) public {
require(hardCap > minimalGoal);
require(openingTime < closingTime);
//token = BlockchainBikeToken(_token);
crowdsale = address(this);
forSale = 0xf6ACFDba39D8F786D0D2781A1D20C82E47adF8b7;
ecoSystemFund = 0x5A77aAE15258a2a4445C701d63dbE74016F7e629;
founders = 0xA80A449514541aeEcd3e17BECcC74a86e3de6bfA;
team = 0x309d62B8eaDF717b76296326CA35bB8f2D996B1a;
advisers = 0xc4319217ca328F7518c463D6D3e78f68acc5B076;
bounty = 0x3605e4E99efFaB70D0C84aA2beA530683824246f;
affiliate = 0x1709365100eD9B7c417E0dF0fdc32027af1DAff1;
/*forSale = _forSale;
ecoSystemFund = _ecoSystemFund;
founders = _founders;
team = _team;
advisers = _advisers;
bounty = _bountry;
affiliate = _affiliate;*/
balances[team] = totalSupply * 28 / 100;
balances[founders] = totalSupply * 12 / 100;
balances[bounty] = totalSupply * 1 / 100;
balances[affiliate] = totalSupply * 1 / 100;
balances[advisers] = totalSupply * 1 / 100;
balances[ecoSystemFund] = totalSupply * 5 / 100;
balances[forSale] = totalSupply * 52 / 100;
emit Transfer(0x0, team, balances[team]);
emit Transfer(0x0, founders, balances[founders]);
emit Transfer(0x0, bounty, balances[bounty]);
emit Transfer(0x0, affiliate, balances[affiliate]);
emit Transfer(0x0, advisers, balances[advisers]);
emit Transfer(0x0, ecoSystemFund, balances[ecoSystemFund]);
emit Transfer(0x0, forSale, balances[forSale]);
}
| 14,218
|
189
|
// add x^16(33! / 16!)
|
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000052b6b54569976310000;
|
xi = (xi * _x) >> _precision;
res += xi * 0x000000000000052b6b54569976310000;
| 38,892
|
126
|
// Prevent overflow when dividing INT256_MIN by -1 https:github.com/RequestNetwork/requestNetwork/issues/43
|
require(!(a == - 2**255 && b == -1) && (b > 0));
return a / b;
|
require(!(a == - 2**255 && b == -1) && (b > 0));
return a / b;
| 23,185
|
4
|
// Array that stores all possible grades for the team.
|
uint8[] public momoGrades;
|
uint8[] public momoGrades;
| 11,670
|
63
|
// Group is intact after fn call/_tokenId The ID of the Token purchase group
|
function distributeInterest(uint256 _tokenId) external onlyCOO payable {
var group = tokenIndexToGroup[_tokenId];
var amount = msg.value;
var excess = amount;
// Safety check to make sure group exists and had purchased the token
require(group.exists);
require(group.purchasePrice > 0);
require(amount > 0);
for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) {
address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i];
// calculate contributor's interest proceeds and add to their withdrawable balance
uint256 userProceeds = uint256(SafeMath.div(SafeMath.mul(amount,
tokenIndexToGroup[_tokenId].addressToContribution[userAdd]),
tokenIndexToGroup[_tokenId].contributedBalance));
userAddressToContributor[userAdd].withdrawableBalance += userProceeds;
excess -= userProceeds;
InterestDeposited(_tokenId, userAdd, userProceeds);
}
commissionBalance += excess;
Commission(_tokenId, excess);
} */
|
function distributeInterest(uint256 _tokenId) external onlyCOO payable {
var group = tokenIndexToGroup[_tokenId];
var amount = msg.value;
var excess = amount;
// Safety check to make sure group exists and had purchased the token
require(group.exists);
require(group.purchasePrice > 0);
require(amount > 0);
for (uint i = 0; i < tokenIndexToGroup[_tokenId].contributorArr.length; i++) {
address userAdd = tokenIndexToGroup[_tokenId].contributorArr[i];
// calculate contributor's interest proceeds and add to their withdrawable balance
uint256 userProceeds = uint256(SafeMath.div(SafeMath.mul(amount,
tokenIndexToGroup[_tokenId].addressToContribution[userAdd]),
tokenIndexToGroup[_tokenId].contributedBalance));
userAddressToContributor[userAdd].withdrawableBalance += userProceeds;
excess -= userProceeds;
InterestDeposited(_tokenId, userAdd, userProceeds);
}
commissionBalance += excess;
Commission(_tokenId, excess);
} */
| 29,798
|
20
|
// --test price = 0.00025
|
uint256 price = 250000000000000;
return price;
|
uint256 price = 250000000000000;
return price;
| 19,836
|
43
|
// Mint HYSI token with deposited 3CRV. This function goes through all the steps necessary to mint an optimal amount of HYSI minAmountToMint_ The expected min amount of hysi to mint. If hysiAmount is lower than minAmountToMint_ the transaction will revert. This function deposits 3CRV in the underlying Metapool and deposits these LP token to get yToken which in turn are used to mint HYSI This process leaves some leftovers which are partially used in the next mint batches. In order to get 3CRV we can implement a zap to move stables into the curve tri-pool keeperIncentive(0) checks if the msg.sender
|
function batchMint(uint256 minAmountToMint_) external keeperIncentive(0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
(block.timestamp.sub(lastMintedAt) >= batchCooldown) ||
(batch.suppliedTokenBalance >= mintThreshold),
"can not execute batch action yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantity of yToken for one HYSI
(
address[] memory tokenAddresses,
uint256[] memory quantities
) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(
setToken,
1e18
);
//Total value of leftover yToken valued in 3CRV
uint256 totalLeftoverIn3Crv;
//Individual yToken leftovers valued in 3CRV
uint256[] memory leftoversIn3Crv = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
//Check how many crvLPToken are needed to mint one yToken
uint256 yTokenInCrvToken = YearnVault(tokenAddresses[i]).pricePerShare();
//Check how many 3CRV are needed to mint one crvLPToken
uint256 crvLPTokenIn3Crv = uint256(2e18).sub(
curvePoolTokenPairs[tokenAddresses[i]]
.curveMetaPool
.calc_withdraw_one_coin(1e18, 1)
);
//Calculate how many 3CRV are needed to mint one yToken
uint256 yTokenIn3Crv = yTokenInCrvToken.mul(crvLPTokenIn3Crv).div(1e18);
//Calculate how much the yToken leftover are worth in 3CRV
uint256 leftoverIn3Crv = YearnVault(tokenAddresses[i])
.balanceOf(address(this))
.mul(yTokenIn3Crv)
.div(1e18);
//Add the leftover value to the array of leftovers for later use
leftoversIn3Crv[i] = leftoverIn3Crv;
//Add the leftover value to the total leftover value
totalLeftoverIn3Crv = totalLeftoverIn3Crv.add(leftoverIn3Crv);
}
//Calculate the total value of supplied token + leftovers in 3CRV
uint256 suppliedTokenBalancePlusLeftovers = batch.suppliedTokenBalance.add(
totalLeftoverIn3Crv
);
for (uint256 i; i < tokenAddresses.length; i++) {
//Calculate the pool allocation by dividing the suppliedTokenBalance by 4 and take leftovers into account
uint256 poolAllocation = suppliedTokenBalancePlusLeftovers.div(4).sub(
leftoversIn3Crv[i]
);
//Pool 3CRV to get crvLPToken
_sendToCurve(
poolAllocation,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(
address(this)
),
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken,
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of hysi that we can mint with our balances of yToken
uint256 hysiAmount = YearnVault(tokenAddresses[0])
.balanceOf(address(this))
.mul(1e18)
.div(quantities[0]);
for (uint256 i = 1; i < tokenAddresses.length; i++) {
hysiAmount = Math.min(
hysiAmount,
YearnVault(tokenAddresses[i]).balanceOf(address(this)).mul(1e18).div(
quantities[i]
)
);
}
require(hysiAmount >= minAmountToMint_, "slippage too high");
//Mint HYSI
setBasicIssuanceModule.issue(setToken, hysiAmount, address(this));
//Save the minted amount HYSI as claimable token for the batch
batch.claimableTokenBalance = hysiAmount;
//Set claimable to true so users can claim their HYSI
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(
currentMintBatchId,
batch.suppliedTokenBalance,
hysiAmount
);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
|
function batchMint(uint256 minAmountToMint_) external keeperIncentive(0) {
Batch storage batch = batches[currentMintBatchId];
//Check if there was enough time between the last batch minting and this attempt...
//...or if enough 3CRV was deposited to make the minting worthwhile
//This is to prevent excessive gas consumption and costs as we will pay keeper to call this function
require(
(block.timestamp.sub(lastMintedAt) >= batchCooldown) ||
(batch.suppliedTokenBalance >= mintThreshold),
"can not execute batch action yet"
);
//Check if the Batch got already processed -- should technically not be possible
require(batch.claimable == false, "already minted");
//Check if this contract has enough 3CRV -- should technically not be necessary
require(
threeCrv.balanceOf(address(this)) >= batch.suppliedTokenBalance,
"account has insufficient balance of token to mint"
);
//Get the quantity of yToken for one HYSI
(
address[] memory tokenAddresses,
uint256[] memory quantities
) = setBasicIssuanceModule.getRequiredComponentUnitsForIssue(
setToken,
1e18
);
//Total value of leftover yToken valued in 3CRV
uint256 totalLeftoverIn3Crv;
//Individual yToken leftovers valued in 3CRV
uint256[] memory leftoversIn3Crv = new uint256[](quantities.length);
for (uint256 i; i < tokenAddresses.length; i++) {
//Check how many crvLPToken are needed to mint one yToken
uint256 yTokenInCrvToken = YearnVault(tokenAddresses[i]).pricePerShare();
//Check how many 3CRV are needed to mint one crvLPToken
uint256 crvLPTokenIn3Crv = uint256(2e18).sub(
curvePoolTokenPairs[tokenAddresses[i]]
.curveMetaPool
.calc_withdraw_one_coin(1e18, 1)
);
//Calculate how many 3CRV are needed to mint one yToken
uint256 yTokenIn3Crv = yTokenInCrvToken.mul(crvLPTokenIn3Crv).div(1e18);
//Calculate how much the yToken leftover are worth in 3CRV
uint256 leftoverIn3Crv = YearnVault(tokenAddresses[i])
.balanceOf(address(this))
.mul(yTokenIn3Crv)
.div(1e18);
//Add the leftover value to the array of leftovers for later use
leftoversIn3Crv[i] = leftoverIn3Crv;
//Add the leftover value to the total leftover value
totalLeftoverIn3Crv = totalLeftoverIn3Crv.add(leftoverIn3Crv);
}
//Calculate the total value of supplied token + leftovers in 3CRV
uint256 suppliedTokenBalancePlusLeftovers = batch.suppliedTokenBalance.add(
totalLeftoverIn3Crv
);
for (uint256 i; i < tokenAddresses.length; i++) {
//Calculate the pool allocation by dividing the suppliedTokenBalance by 4 and take leftovers into account
uint256 poolAllocation = suppliedTokenBalancePlusLeftovers.div(4).sub(
leftoversIn3Crv[i]
);
//Pool 3CRV to get crvLPToken
_sendToCurve(
poolAllocation,
curvePoolTokenPairs[tokenAddresses[i]].curveMetaPool
);
//Deposit crvLPToken to get yToken
_sendToYearn(
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken.balanceOf(
address(this)
),
curvePoolTokenPairs[tokenAddresses[i]].crvLPToken,
YearnVault(tokenAddresses[i])
);
//Approve yToken for minting
YearnVault(tokenAddresses[i]).safeIncreaseAllowance(
address(setBasicIssuanceModule),
YearnVault(tokenAddresses[i]).balanceOf(address(this))
);
}
//Get the minimum amount of hysi that we can mint with our balances of yToken
uint256 hysiAmount = YearnVault(tokenAddresses[0])
.balanceOf(address(this))
.mul(1e18)
.div(quantities[0]);
for (uint256 i = 1; i < tokenAddresses.length; i++) {
hysiAmount = Math.min(
hysiAmount,
YearnVault(tokenAddresses[i]).balanceOf(address(this)).mul(1e18).div(
quantities[i]
)
);
}
require(hysiAmount >= minAmountToMint_, "slippage too high");
//Mint HYSI
setBasicIssuanceModule.issue(setToken, hysiAmount, address(this));
//Save the minted amount HYSI as claimable token for the batch
batch.claimableTokenBalance = hysiAmount;
//Set claimable to true so users can claim their HYSI
batch.claimable = true;
//Update lastMintedAt for cooldown calculations
lastMintedAt = block.timestamp;
emit BatchMinted(
currentMintBatchId,
batch.suppliedTokenBalance,
hysiAmount
);
//Create the next mint batch
_generateNextBatch(currentMintBatchId, BatchType.Mint);
}
| 12,241
|
27
|
// Base factory for contracts whose creation code is so large that the factory cannot hold it. This happens whenthe contract's creation code grows close to 24kB. Note that this factory cannot help with contracts that have a runtime (deployed) bytecode larger than 24kB. /
|
abstract contract BaseSplitCodeFactory {
// The contract's creation code is stored as code in two separate addresses, and retrieved via `extcodecopy`. This
// means this factory supports contracts with creation code of up to 48kB.
// We rely on inline-assembly to achieve this, both to make the entire operation highly gas efficient, and because
// `extcodecopy` is not available in Solidity.
// solhint-disable no-inline-assembly
address private immutable _creationCodeContractA;
uint256 private immutable _creationCodeSizeA;
address private immutable _creationCodeContractB;
uint256 private immutable _creationCodeSizeB;
/**
* @dev The creation code of a contract Foo can be obtained inside Solidity with `type(Foo).creationCode`.
*/
constructor(bytes memory creationCode) {
uint256 creationCodeSize = creationCode.length;
// We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents
// (A), and another with the remaining half (B).
// We store the lengths in both immutable and stack variables, since immutable variables cannot be read during
// construction.
uint256 creationCodeSizeA = creationCodeSize / 2;
_creationCodeSizeA = creationCodeSizeA;
uint256 creationCodeSizeB = creationCodeSize - creationCodeSizeA;
_creationCodeSizeB = creationCodeSizeB;
// To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with
// the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving
// `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place.
// Memory: [ code length ] [ A.data ] [ B.data ]
// Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore
// the original length.
bytes memory creationCodeA;
assembly {
creationCodeA := creationCode
mstore(creationCodeA, creationCodeSizeA)
}
// Memory: [ A.length ] [ A.data ] [ B.data ]
// ^ creationCodeA
_creationCodeContractA = CodeDeployer.deploy(creationCodeA);
// Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new'
// memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last
// byte to later restore it.
bytes memory creationCodeB;
bytes32 lastByteA;
assembly {
// `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's
// last 32 bytes.
creationCodeB := add(creationCode, creationCodeSizeA)
lastByteA := mload(creationCodeB)
mstore(creationCodeB, creationCodeSizeB)
}
// Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ]
// ^ creationCodeA ^ creationCodeB
_creationCodeContractB = CodeDeployer.deploy(creationCodeB);
// We now restore the original contents of `creationCode` by writing back the original length and A's last byte.
assembly {
mstore(creationCodeA, creationCodeSize)
mstore(creationCodeB, lastByteA)
}
}
/**
* @dev Returns the two addresses where the creation code of the contract crated by this factory is stored.
*/
function getCreationCodeContracts() public view returns (address contractA, address contractB) {
return (_creationCodeContractA, _creationCodeContractB);
}
/**
* @dev Returns the creation code of the contract this factory creates.
*/
function getCreationCode() public view returns (bytes memory) {
return _getCreationCodeWithArgs("");
}
/**
* @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`.
*/
function _getCreationCodeWithArgs(bytes memory constructorArgs) private view returns (bytes memory code) {
// This function exists because `abi.encode()` cannot be instructed to place its result at a specific address.
// We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but
// cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code,
// which would be prohibitively expensive.
// Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the
// creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be
// overly long) right after the end of the creation code.
// Immutable variables cannot be used in assembly, so we store them in the stack first.
address creationCodeContractA = _creationCodeContractA;
uint256 creationCodeSizeA = _creationCodeSizeA;
address creationCodeContractB = _creationCodeContractB;
uint256 creationCodeSizeB = _creationCodeSizeB;
uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB;
uint256 constructorArgsSize = constructorArgs.length;
uint256 codeSize = creationCodeSize + constructorArgsSize;
assembly {
// First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of
// `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length.
code := mload(0x40)
mstore(0x40, add(code, add(codeSize, 32)))
// We now store the length of the code plus constructor arguments.
mstore(code, codeSize)
// Next, we concatenate the creation code stored in A and B.
let dataStart := add(code, 32)
extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA)
extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB)
}
// Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this
// copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`.
uint256 constructorArgsDataPtr;
uint256 constructorArgsCodeDataPtr;
assembly {
constructorArgsDataPtr := add(constructorArgs, 32)
constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize)
}
_memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize);
}
/**
* @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the
* contract's constructor arguments, in order.
*/
function _create(bytes memory constructorArgs) internal virtual returns (address) {
bytes memory creationCode = _getCreationCodeWithArgs(constructorArgs);
address destination;
assembly {
destination := create(0, add(creationCode, 32), mload(creationCode))
}
if (destination == address(0)) {
// Bubble up inner revert reason
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
return destination;
}
// From
// https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol
function _memcpy(
uint256 dest,
uint256 src,
uint256 len
) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint256 mask = 256**(32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
|
abstract contract BaseSplitCodeFactory {
// The contract's creation code is stored as code in two separate addresses, and retrieved via `extcodecopy`. This
// means this factory supports contracts with creation code of up to 48kB.
// We rely on inline-assembly to achieve this, both to make the entire operation highly gas efficient, and because
// `extcodecopy` is not available in Solidity.
// solhint-disable no-inline-assembly
address private immutable _creationCodeContractA;
uint256 private immutable _creationCodeSizeA;
address private immutable _creationCodeContractB;
uint256 private immutable _creationCodeSizeB;
/**
* @dev The creation code of a contract Foo can be obtained inside Solidity with `type(Foo).creationCode`.
*/
constructor(bytes memory creationCode) {
uint256 creationCodeSize = creationCode.length;
// We are going to deploy two contracts: one with approximately the first half of `creationCode`'s contents
// (A), and another with the remaining half (B).
// We store the lengths in both immutable and stack variables, since immutable variables cannot be read during
// construction.
uint256 creationCodeSizeA = creationCodeSize / 2;
_creationCodeSizeA = creationCodeSizeA;
uint256 creationCodeSizeB = creationCodeSize - creationCodeSizeA;
_creationCodeSizeB = creationCodeSizeB;
// To deploy the contracts, we're going to use `CodeDeployer.deploy()`, which expects a memory array with
// the code to deploy. Note that we cannot simply create arrays for A and B's code by copying or moving
// `creationCode`'s contents as they are expected to be very large (> 24kB), so we must operate in-place.
// Memory: [ code length ] [ A.data ] [ B.data ]
// Creating A's array is simple: we simply replace `creationCode`'s length with A's length. We'll later restore
// the original length.
bytes memory creationCodeA;
assembly {
creationCodeA := creationCode
mstore(creationCodeA, creationCodeSizeA)
}
// Memory: [ A.length ] [ A.data ] [ B.data ]
// ^ creationCodeA
_creationCodeContractA = CodeDeployer.deploy(creationCodeA);
// Creating B's array is a bit more involved: since we cannot move B's contents, we are going to create a 'new'
// memory array starting at A's last 32 bytes, which will be replaced with B's length. We'll back-up this last
// byte to later restore it.
bytes memory creationCodeB;
bytes32 lastByteA;
assembly {
// `creationCode` points to the array's length, not data, so by adding A's length to it we arrive at A's
// last 32 bytes.
creationCodeB := add(creationCode, creationCodeSizeA)
lastByteA := mload(creationCodeB)
mstore(creationCodeB, creationCodeSizeB)
}
// Memory: [ A.length ] [ A.data[ : -1] ] [ B.length ][ B.data ]
// ^ creationCodeA ^ creationCodeB
_creationCodeContractB = CodeDeployer.deploy(creationCodeB);
// We now restore the original contents of `creationCode` by writing back the original length and A's last byte.
assembly {
mstore(creationCodeA, creationCodeSize)
mstore(creationCodeB, lastByteA)
}
}
/**
* @dev Returns the two addresses where the creation code of the contract crated by this factory is stored.
*/
function getCreationCodeContracts() public view returns (address contractA, address contractB) {
return (_creationCodeContractA, _creationCodeContractB);
}
/**
* @dev Returns the creation code of the contract this factory creates.
*/
function getCreationCode() public view returns (bytes memory) {
return _getCreationCodeWithArgs("");
}
/**
* @dev Returns the creation code that will result in a contract being deployed with `constructorArgs`.
*/
function _getCreationCodeWithArgs(bytes memory constructorArgs) private view returns (bytes memory code) {
// This function exists because `abi.encode()` cannot be instructed to place its result at a specific address.
// We need for the ABI-encoded constructor arguments to be located immediately after the creation code, but
// cannot rely on `abi.encodePacked()` to perform concatenation as that would involve copying the creation code,
// which would be prohibitively expensive.
// Instead, we compute the creation code in a pre-allocated array that is large enough to hold *both* the
// creation code and the constructor arguments, and then copy the ABI-encoded arguments (which should not be
// overly long) right after the end of the creation code.
// Immutable variables cannot be used in assembly, so we store them in the stack first.
address creationCodeContractA = _creationCodeContractA;
uint256 creationCodeSizeA = _creationCodeSizeA;
address creationCodeContractB = _creationCodeContractB;
uint256 creationCodeSizeB = _creationCodeSizeB;
uint256 creationCodeSize = creationCodeSizeA + creationCodeSizeB;
uint256 constructorArgsSize = constructorArgs.length;
uint256 codeSize = creationCodeSize + constructorArgsSize;
assembly {
// First, we allocate memory for `code` by retrieving the free memory pointer and then moving it ahead of
// `code` by the size of the creation code plus constructor arguments, and 32 bytes for the array length.
code := mload(0x40)
mstore(0x40, add(code, add(codeSize, 32)))
// We now store the length of the code plus constructor arguments.
mstore(code, codeSize)
// Next, we concatenate the creation code stored in A and B.
let dataStart := add(code, 32)
extcodecopy(creationCodeContractA, dataStart, 0, creationCodeSizeA)
extcodecopy(creationCodeContractB, add(dataStart, creationCodeSizeA), 0, creationCodeSizeB)
}
// Finally, we copy the constructorArgs to the end of the array. Unfortunately there is no way to avoid this
// copy, as it is not possible to tell Solidity where to store the result of `abi.encode()`.
uint256 constructorArgsDataPtr;
uint256 constructorArgsCodeDataPtr;
assembly {
constructorArgsDataPtr := add(constructorArgs, 32)
constructorArgsCodeDataPtr := add(add(code, 32), creationCodeSize)
}
_memcpy(constructorArgsCodeDataPtr, constructorArgsDataPtr, constructorArgsSize);
}
/**
* @dev Deploys a contract with constructor arguments. To create `constructorArgs`, call `abi.encode()` with the
* contract's constructor arguments, in order.
*/
function _create(bytes memory constructorArgs) internal virtual returns (address) {
bytes memory creationCode = _getCreationCodeWithArgs(constructorArgs);
address destination;
assembly {
destination := create(0, add(creationCode, 32), mload(creationCode))
}
if (destination == address(0)) {
// Bubble up inner revert reason
// solhint-disable-next-line no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
return destination;
}
// From
// https://github.com/Arachnid/solidity-stringutils/blob/b9a6f6615cf18a87a823cbc461ce9e140a61c305/src/strings.sol
function _memcpy(
uint256 dest,
uint256 src,
uint256 len
) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint256 mask = 256**(32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
}
| 26,008
|
392
|
// check for existance
|
require(_configSet.contains(configID), "not config");
|
require(_configSet.contains(configID), "not config");
| 73,150
|
117
|
// private function to distribute WETH rewards
|
function distributeDivsEth(uint amount) private {
require(amount > 0 && totalTokens > 0, "distributeDivsEth failed!");
totalEthDivPoints = totalEthDivPoints.add(amount.mul(pointMultiplier).div(totalTokens));
emit EthRewardsDisbursed(amount);
}
|
function distributeDivsEth(uint amount) private {
require(amount > 0 && totalTokens > 0, "distributeDivsEth failed!");
totalEthDivPoints = totalEthDivPoints.add(amount.mul(pointMultiplier).div(totalTokens));
emit EthRewardsDisbursed(amount);
}
| 37,589
|
0
|
// Creates and initializes V3 Pools/Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that/ require the pool to exist.
|
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96)
external
payable
returns (address pool);
}
|
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96)
external
payable
returns (address pool);
}
| 17,781
|
7
|
// Create a pool (proxied) poolBeacon Pool beacon contract params Pool parametersreturn Pool address /
|
function createProxied(address poolBeacon, bytes calldata params) external returns (address);
|
function createProxied(address poolBeacon, bytes calldata params) external returns (address);
| 13,616
|
64
|
// Apply discount if purchasing 5 bees
|
if (_amount == 5) {
price -= beesParams.discountPrice;
}
|
if (_amount == 5) {
price -= beesParams.discountPrice;
}
| 28,394
|
169
|
// Internal function that transfer tokens from one address to another./ Update magnifiedRewardCorrections to keep rewards unchanged./from The address to transfer from./to The address to transfer to./value The amount to be transferred.
|
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedRewardPerShare.mul(value).toInt256Safe();
magnifiedRewardCorrections[from] = magnifiedRewardCorrections[from].add(_magCorrection);
magnifiedRewardCorrections[to] = magnifiedRewardCorrections[to].sub(_magCorrection);
}
|
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedRewardPerShare.mul(value).toInt256Safe();
magnifiedRewardCorrections[from] = magnifiedRewardCorrections[from].add(_magCorrection);
magnifiedRewardCorrections[to] = magnifiedRewardCorrections[to].sub(_magCorrection);
}
| 68,426
|
18
|
// Get contract balance /
|
function getBalance() public view returns(uint256 balance) {
return address(this).balance;
}
|
function getBalance() public view returns(uint256 balance) {
return address(this).balance;
}
| 15,466
|
0
|
// transferOwners: (transferData, transferID) => address owner might change state map implementation in the future mapping(struct => mapping(uint => address)) public transferOwners;
|
mapping(bytes => mapping(uint => address)) public transferOwners;
|
mapping(bytes => mapping(uint => address)) public transferOwners;
| 45,339
|
45
|
// Transfer control over deployment to the home address correspondingto a given key to the null address, which will prevent it from beingdeployed to again in the future. The caller must be designated as thecurrent controller of the corresponding home address (with the initialcontroller set to the address corresponding to the first 20 bytes of thekey) - This condition can be checked by calling `getHomeAddressInformation`with the same key. key bytes32 The unique value used to derive the home address. /
|
function relinquishControl(bytes32 key)
|
function relinquishControl(bytes32 key)
| 23,013
|
0
|
// address of the uniswap v2 router
|
address private constant UNISWAP_V2_ROUTER =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
|
address private constant UNISWAP_V2_ROUTER =
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
| 17,905
|
4
|
// If allowance is unlimited by `permit`, `approve`, or `increaseAllowance` function, don't adjust it. But the expiration date must be empty or in the future. Note that the expiration timestamp can have a 900-second error: https:github.com/ethereum/wiki/blob/c02254611f218f43cbb07517ca8e5d00fd6d6d75/Block-Protocol-2.0.md
|
require(
|
require(
| 31,515
|
39
|
// AMOs should only be giving back canonical tokens
|
function receiveBackViaAMO(address canonical_token_address, uint256 token_amount, bool do_bridging) external validCanonicalToken(canonical_token_address) validAMO(msg.sender) {
// Pull in the tokens from the AMO
TransferHelper.safeTransferFrom(canonical_token_address, msg.sender, address(this), token_amount);
// Get the token type
uint256 token_type = getTokenType(canonical_token_address);
_receiveBack(msg.sender, token_type, token_amount, do_bridging, true);
}
|
function receiveBackViaAMO(address canonical_token_address, uint256 token_amount, bool do_bridging) external validCanonicalToken(canonical_token_address) validAMO(msg.sender) {
// Pull in the tokens from the AMO
TransferHelper.safeTransferFrom(canonical_token_address, msg.sender, address(this), token_amount);
// Get the token type
uint256 token_type = getTokenType(canonical_token_address);
_receiveBack(msg.sender, token_type, token_amount, do_bridging, true);
}
| 5,607
|
24
|
// For increasing or decreasing the max supply ba character type
|
function setMaxSupply(uint16 _characterType, uint16 _maxSupply)
public
onlyOwner
|
function setMaxSupply(uint16 _characterType, uint16 _maxSupply)
public
onlyOwner
| 41,350
|
35
|
// External //Lets the governor call anything on behalf of the contract._destination The destination of the call._amount The value sent with the call._data The data sent with the call. /
|
function executeGovernorProposal(address _destination, uint _amount, bytes _data) external onlyByGovernor {
require(_destination.call.value(_amount)(_data)); // solium-disable-line security/no-call-value
}
|
function executeGovernorProposal(address _destination, uint _amount, bytes _data) external onlyByGovernor {
require(_destination.call.value(_amount)(_data)); // solium-disable-line security/no-call-value
}
| 32,254
|
13
|
// See divDecimal for uint256. /
|
function divDecimalUint128(uint128 x, uint128 y) internal pure returns (uint128) {
return (x * UNIT_UINT128) / y;
}
|
function divDecimalUint128(uint128 x, uint128 y) internal pure returns (uint128) {
return (x * UNIT_UINT128) / y;
}
| 26,214
|
243
|
// Transfer tokens.
|
if (from == address(this)) {
LibERC20Token.transfer(
token,
to,
amount
);
} else {
|
if (from == address(this)) {
LibERC20Token.transfer(
token,
to,
amount
);
} else {
| 49,090
|
122
|
// isSwapify
|
bool public swapiFy;
|
bool public swapiFy;
| 76,079
|
8
|
// Emit event
|
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
|
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
| 34,634
|
104
|
// verify the pool is of the expected type
|
require(
_pool.POOL_UID() == 0x620bbda48b8ff3098da2f0033cbf499115c61efdd5dcd2db05346782df6218e7,
"unexpected POOL_UID"
);
|
require(
_pool.POOL_UID() == 0x620bbda48b8ff3098da2f0033cbf499115c61efdd5dcd2db05346782df6218e7,
"unexpected POOL_UID"
);
| 49,713
|
7
|
// 100 sb = 1 Euro There are 10 billion Euro worth in SB-coins in total 1SBC = 1 Euro
|
_totalSupply = 1000000000000;
balances[msg.sender] = _totalSupply;
_name = "Saarbrücken Coin";
_symbol = "SBC";
_decimals = 2;
create_products();
|
_totalSupply = 1000000000000;
balances[msg.sender] = _totalSupply;
_name = "Saarbrücken Coin";
_symbol = "SBC";
_decimals = 2;
create_products();
| 6,214
|
181
|
// Play.
|
buyout(_gameIndex, startNewGameIfIdle, x, y);
|
buyout(_gameIndex, startNewGameIfIdle, x, y);
| 17,952
|
10
|
// Add call to mint $CELL on other side of bridge
|
calls[currIndex] = abi.encodeWithSelector(this.mintCell.selector, reflection[cellToken], msg.sender, cellAmount);
|
calls[currIndex] = abi.encodeWithSelector(this.mintCell.selector, reflection[cellToken], msg.sender, cellAmount);
| 33,812
|
2
|
// Game Length (TODO: Change to 1 weeks)
|
gameLength = 1 weeks;
|
gameLength = 1 weeks;
| 22,742
|
465
|
// Sets a new price piggyDistribution for the comptroller Admin function to set a new piggy distributionreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
|
function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) {
IPiggyDistribution oldPiggyDistribution = piggyDistribution;
piggyDistribution = newPiggyDistribution;
emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution);
return uint(Error.NO_ERROR);
}
|
function _setPiggyDistribution(IPiggyDistribution newPiggyDistribution) public onlyOwner returns (uint) {
IPiggyDistribution oldPiggyDistribution = piggyDistribution;
piggyDistribution = newPiggyDistribution;
emit NewPiggyDistribution(oldPiggyDistribution, newPiggyDistribution);
return uint(Error.NO_ERROR);
}
| 46,109
|
57
|
// Pre: Emergency situation that requires contribution period to stop./ Post: Contributing not possible anymore.
|
function halt() only_foundation { halted = true; }
/// Pre: Emergency situation resolved.
/// Post: Contributing becomes possible again.
function unhalt() only_foundation { halted = false; }
/// Pre: Restricted to foundation.
/// Post: New address set. To halt contribution and/or change minter in FolioNinjaToken contract.
function changeFoundationAddress(address newFoundationAddress) only_foundation { FOUNDATION_WALLET = newFoundationAddress; }
/// Pre: Restricted to foundation.
/// Post: New address set. To change beneficiary of contributions
function changeDevAddress(address newDevAddress) only_foundation { DEV_WALLET = newDevAddress; }
}
|
function halt() only_foundation { halted = true; }
/// Pre: Emergency situation resolved.
/// Post: Contributing becomes possible again.
function unhalt() only_foundation { halted = false; }
/// Pre: Restricted to foundation.
/// Post: New address set. To halt contribution and/or change minter in FolioNinjaToken contract.
function changeFoundationAddress(address newFoundationAddress) only_foundation { FOUNDATION_WALLET = newFoundationAddress; }
/// Pre: Restricted to foundation.
/// Post: New address set. To change beneficiary of contributions
function changeDevAddress(address newDevAddress) only_foundation { DEV_WALLET = newDevAddress; }
}
| 20,714
|
16
|
// Contract which oversees inter-cToken operations /
|
ComptrollerInterface public comptroller;
|
ComptrollerInterface public comptroller;
| 12,446
|
251
|
// Reserves the name if isReserve is set to true, de-reserves if set to false /
|
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
|
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
| 67,725
|
92
|
// An event thats emitted when a delegate account's vote balance changes
|
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
|
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
| 32,416
|
58
|
// handling impermanent loss case
|
impermanentLossShare = (_totalBalance.mul(100)).div(netTotalGamePrincipal);
netTotalGamePrincipal = _totalBalance;
|
impermanentLossShare = (_totalBalance.mul(100)).div(netTotalGamePrincipal);
netTotalGamePrincipal = _totalBalance;
| 7,002
|
160
|
// Check if cumulative voting rights exceeds 50% of total voting rights
|
require(
netVotingRights >= _cumulativeTokenLocked.div(2),
"CerticolDAO: cumulative voting rights did not exceeds 50% of total voting rights"
);
|
require(
netVotingRights >= _cumulativeTokenLocked.div(2),
"CerticolDAO: cumulative voting rights did not exceeds 50% of total voting rights"
);
| 51,514
|
10
|
// In case there is no registry
|
if (checkpoints.length == 0) {
return (
address(parentDelegation) == address(0) ?
address(0) : parentDelegation.delegatedToAt(_who, _block)
);
}
|
if (checkpoints.length == 0) {
return (
address(parentDelegation) == address(0) ?
address(0) : parentDelegation.delegatedToAt(_who, _block)
);
}
| 45,859
|
107
|
// Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Returns the name of the token. /
|
function name() public virtual pure returns (string memory);
|
function name() public virtual pure returns (string memory);
| 18,817
|
53
|
// Returns a positive number if `other` comes lexicographically after`self`, a negative number if it comes before, or zero if thecontents of the two bytes are equal. Comparison is done per-rune,on unicode codepoints.self The first bytes to compare.offset The offset of self.lenThe length of self.other The second bytes to compare.otheroffset The offset of the other string.otherlenThe length of the other string. return The result of the comparison./
|
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {
uint shortest = len;
if (otherlen < len)
shortest = otherlen;
uint selfptr;
uint otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask;
if (shortest > 32) {
mask = uint256(- 1); // aka 0xffffff....
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(len) - int(otherlen);
}
|
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {
uint shortest = len;
if (otherlen < len)
shortest = otherlen;
uint selfptr;
uint otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint mask;
if (shortest > 32) {
mask = uint256(- 1); // aka 0xffffff....
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(len) - int(otherlen);
}
| 4,964
|
7
|
// Creates a new token for `to`. Its token ID will be automatically
|
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint");
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
_mint(to, _tokenIdTracker.current());
_tokenIdTracker.increment();
}
|
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint");
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
_mint(to, _tokenIdTracker.current());
_tokenIdTracker.increment();
}
| 6,388
|
67
|
// we can stop only not started and not completed crowdsale
|
if (started) {
require(!isFailed());
require(!isSuccessful());
}
|
if (started) {
require(!isFailed());
require(!isSuccessful());
}
| 44,566
|
185
|
// term 0:
|
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BONE);
uint term = BONE;
uint sum = term;
bool negative = false;
|
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BONE);
uint term = BONE;
uint sum = term;
bool negative = false;
| 10,525
|
9
|
// Called by the requester to make a full request, which provides/ all of its parameters as arguments and does not refer to a template/`fulfillAddress` is not allowed to be the address of this/ contract. This is not actually needed to protect users that use the/ protocol as intended, but it is done for good measure./airnode Airnode address/endpointId Endpoint ID (allowed to be `bytes32(0)`)/sponsor Sponsor address/sponsorWallet Sponsor wallet that is requested to fulfill/ the request/fulfillAddress Address that will be called to fulfill/fulfillFunctionId Signature of the function that will be called/ to fulfill/parameters All request parameters/ return requestId Request ID
|
function makeFullRequest(
address airnode,
bytes32 endpointId,
address sponsor,
address sponsorWallet,
address fulfillAddress,
bytes4 fulfillFunctionId,
bytes calldata parameters
|
function makeFullRequest(
address airnode,
bytes32 endpointId,
address sponsor,
address sponsorWallet,
address fulfillAddress,
bytes4 fulfillFunctionId,
bytes calldata parameters
| 15,071
|
161
|
// Reviewer(s) / Contributor(s) Travis Moore: https:github.com/FortisFortuna Sam Kazemian: https:github.com/samkazemian Drake Evans:https:github.com/DrakeEvans Jack Corddry: https:github.com/corddry Justin Moore: https:github.com/0xJM/Fraxswap Router Multihop/Router for swapping across the majority of the FRAX liquidity
|
contract FraxswapRouterMultihop is ReentrancyGuard, Ownable {
using SafeCast for uint256;
using SafeCast for int256;
IWETH WETH9;
address FRAX;
constructor(IWETH _WETH9, address _FRAX) {
WETH9 = _WETH9;
FRAX = _FRAX;
}
/// @notice modifier for checking deadline
modifier checkDeadline(uint256 deadline) {
require(block.timestamp <= deadline, "Transaction too old");
_;
}
/// @notice only accept ETH via fallback from the WETH contract
receive() external payable {
assert(msg.sender == address(WETH9));
}
/// ---------------------------
/// --------- Public ----------
/// ---------------------------
/// @notice Main external swap function
/// @param params all parameters for this swap
/// @return amountOut output amount from this swap
function swap(FraxswapParams memory params)
external
payable
nonReentrant
checkDeadline(params.deadline)
returns (uint256 amountOut)
{
if (params.tokenIn == address(0)) {
// ETH sent in via msg.value
require(msg.value == params.amountIn, "FSR:II"); // Insufficient input ETH
} else {
if (params.v != 0) {
// use permit instead of approval
uint256 amount = params.approveMax
? type(uint256).max
: params.amountIn;
IERC20Permit(params.tokenIn).permit(
msg.sender,
address(this),
amount,
params.deadline,
params.v,
params.r,
params.s
);
}
// Pull tokens into the Router Contract
TransferHelper.safeTransferFrom(
params.tokenIn,
msg.sender,
address(this),
params.amountIn
);
}
FraxswapRoute memory route = abi.decode(params.route, (FraxswapRoute));
route.tokenOut = params.tokenIn;
route.amountOut = params.amountIn;
for (uint256 i; i < route.nextHops.length; ++i) {
FraxswapRoute memory nextRoute = abi.decode(
route.nextHops[i],
(FraxswapRoute)
);
executeAllHops(route, nextRoute);
}
bool outputETH = params.tokenOut == address(0); // save gas
amountOut = outputETH
? address(this).balance
: IERC20(params.tokenOut).balanceOf(address(this));
// Check output amounts and send to recipient (IMPORTANT CHECK)
require(amountOut >= params.amountOutMinimum, "FSR:IO"); // Insufficient output
if (outputETH) {
// sending ETH
(bool success, ) = payable(params.recipient).call{value: amountOut}(
""
);
require(success, "FSR:Invalid transfer");
} else {
TransferHelper.safeTransfer(
params.tokenOut,
params.recipient,
amountOut
);
}
emit Routed(
params.tokenIn,
params.tokenOut,
params.amountIn,
amountOut
);
}
/// @notice Uniswap V3 callback function
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external {
require(amount0Delta > 0 || amount1Delta > 0);
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
if (!data.directFundThisPool) {
// it isn't directly funded we pay from the router address
TransferHelper.safeTransfer(
data.tokenIn,
msg.sender,
uint256(amount0Delta > 0 ? amount0Delta : amount1Delta)
);
}
}
/// ---------------------------
/// --------- Internal --------
/// ---------------------------
/// @notice Function that will execute a particular swap step
/// @param prevRoute previous hop of the route
/// @param route current hop of the route
/// @param step swap to execute
/// @return amountOut actual output from this swap step
function executeSwap(
FraxswapRoute memory prevRoute,
FraxswapRoute memory route,
FraxswapStepData memory step
) internal returns (uint256 amountOut) {
uint256 amountIn = getAmountForPct(
step.percentOfHop,
route.percentOfHop,
prevRoute.amountOut
);
if (step.swapType < 2) {
// Fraxswap/Uni v2
bool zeroForOne = prevRoute.tokenOut < step.tokenOut;
if (step.swapType == 0) {
// Execute virtual orders for Fraxswap
PoolInterface(step.pool).executeVirtualOrders(block.timestamp);
}
if (step.extraParam1 == 1) {
// Fraxswap V2 has getAmountOut in the pair (different fees)
amountOut = PoolInterface(step.pool).getAmountOut(
amountIn,
prevRoute.tokenOut
);
} else {
// use the reserves and helper function for Uniswap V2 and Fraxswap V1
(uint112 reserve0, uint112 reserve1, ) = IUniswapV2Pair(
step.pool
).getReserves();
amountOut = getAmountOut(
amountIn,
zeroForOne ? reserve0 : reserve1,
zeroForOne ? reserve1 : reserve0
);
}
if (step.directFundThisPool == 0) {
// this pool is funded by router
TransferHelper.safeTransfer(
prevRoute.tokenOut,
step.pool,
amountIn
);
}
IUniswapV2Pair(step.pool).swap(
zeroForOne ? 0 : amountOut,
zeroForOne ? amountOut : 0,
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this),
new bytes(0)
);
} else if (step.swapType == 2) {
// Uni v3
bool zeroForOne = prevRoute.tokenOut < step.tokenOut;
(int256 amount0, int256 amount1) = IUniswapV3Pool(step.pool).swap(
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this),
zeroForOne,
amountIn.toInt256(),
zeroForOne
? 4295128740
: 1461446703485210103287273052203988822378723970341, // Do not fail because of price
abi.encode(
SwapCallbackData({
tokenIn: prevRoute.tokenOut,
directFundThisPool: step.directFundThisPool == 1
})
)
);
amountOut = uint256(zeroForOne ? -amount1 : -amount0);
} else if (step.swapType == 3) {
// Curve exchange V2
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
PoolInterface(step.pool).exchange(
step.extraParam1,
step.extraParam2,
amountIn,
0
);
amountOut = IERC20(step.tokenOut).balanceOf(address(this));
} else if (step.swapType == 4) {
// Curve exchange, with returns
uint256 value = 0;
if (prevRoute.tokenOut == address(WETH9)) {
// WETH send as ETH
WETH9.withdraw(amountIn);
value = amountIn;
} else {
TransferHelper.safeApprove(
prevRoute.tokenOut,
step.pool,
amountIn
);
}
amountOut = PoolInterface(step.pool).exchange{value: value}(
int128(int256(step.extraParam1)),
int128(int256(step.extraParam2)),
amountIn,
0
);
if (route.tokenOut == address(WETH9)) {
// Wrap the received ETH as WETH
WETH9.deposit{value: amountOut}();
}
} else if (step.swapType == 5) {
// Curve exchange_underlying
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
amountOut = PoolInterface(step.pool).exchange_underlying(
int128(int256(step.extraParam1)),
int128(int256(step.extraParam2)),
amountIn,
0
);
} else if (step.swapType == 6) {
// Saddle
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
amountOut = PoolInterface(step.pool).swap(
uint8(step.extraParam1),
uint8(step.extraParam2),
amountIn,
0,
block.timestamp
);
} else if (step.swapType == 7) {
// FPIController
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
if (prevRoute.tokenOut == FRAX) {
amountOut = PoolInterface(step.pool).mintFPI(amountIn, 0);
} else {
amountOut = PoolInterface(step.pool).redeemFPI(amountIn, 0);
}
} else if (step.swapType == 8) {
// Fraxlend
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
amountOut = PoolInterface(step.pool).deposit(
amountIn,
address(this)
);
} else if (step.swapType == 9) {
// FrxETHMinter
if (step.extraParam1 == 0 && prevRoute.tokenOut == address(WETH9)) {
// Unwrap WETH
WETH9.withdraw(amountIn);
}
PoolInterface(step.pool).submitAndGive{value: amountIn}(
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this)
);
amountOut = amountIn; // exchange 1 for 1
} else if (step.swapType == 10) {
// WETH
if (prevRoute.tokenOut == address(WETH9)) {
// Unwrap WETH
WETH9.withdraw(amountIn);
} else {
// Wrap the ETH
WETH9.deposit{value: amountIn}();
}
amountOut = amountIn; // exchange 1 for 1
} else if (step.swapType == 999) {
// Generic Pool
if (step.directFundThisPool == 0) {
// this pool is funded by router
TransferHelper.safeTransfer(
prevRoute.tokenOut,
step.pool,
amountIn
);
}
amountOut = PoolInterface(step.pool).swap(
prevRoute.tokenOut,
route.tokenOut,
amountIn,
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this)
);
}
emit Swapped(
step.pool,
prevRoute.tokenOut,
step.tokenOut,
amountIn,
amountOut
);
}
/// @notice Function that will loop through and execute swap steps
/// @param prevRoute previous hop of the route
/// @param route current hop of the route
function executeAllStepsForRoute(
FraxswapRoute memory prevRoute,
FraxswapRoute memory route
) internal {
for (uint256 j; j < route.steps.length; ++j) {
FraxswapStepData memory step = abi.decode(
route.steps[j],
(FraxswapStepData)
);
route.amountOut += executeSwap(prevRoute, route, step);
}
}
/// @notice Function that will loop through and execute route hops and execute all steps for each hop
/// @param prevRoute previous hop of the route
/// @param route current hop of the route
function executeAllHops(
FraxswapRoute memory prevRoute,
FraxswapRoute memory route
) internal {
executeAllStepsForRoute(prevRoute, route);
for (uint256 i; i < route.nextHops.length; ++i) {
FraxswapRoute memory nextRoute = abi.decode(
route.nextHops[i],
(FraxswapRoute)
);
executeAllHops(route, nextRoute);
}
}
/// ---------------------------
/// ------ Views / Pure -------
/// ---------------------------
/// @notice Utility function to build an encoded hop of route
/// @param tokenOut output token address
/// @param percentOfHop amount of output tokens from the previous hop going into this hop
/// @param steps list of swaps from the same input token to the same output token
/// @param nextHops next hops from this one, the next hops' input token is the tokenOut
/// @return out encoded FraxswapRoute
function encodeRoute(
address tokenOut,
uint256 percentOfHop,
bytes[] memory steps,
bytes[] memory nextHops
) external pure returns (bytes memory out) {
FraxswapRoute memory route;
route.tokenOut = tokenOut;
route.amountOut = 0;
route.percentOfHop = percentOfHop;
route.steps = steps;
route.nextHops = nextHops;
out = abi.encode(route);
}
/// @notice Utility function to build an encoded step
/// @param swapType type of the swap performed (Uniswap V2, Fraxswap,Curve, etc)
/// @param directFundNextPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param directFundThisPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param tokenOut the target token of the step. output token address
/// @param pool address of the pool to use in the step
/// @param extraParam1 extra data used in the step
/// @param extraParam2 extra data used in the step
/// @param percentOfHop percentage of all of the steps in this route (hop)
/// @return out encoded FraxswapStepData
function encodeStep(
uint8 swapType,
uint8 directFundNextPool,
uint8 directFundThisPool,
address tokenOut,
address pool,
uint256 extraParam1,
uint256 extraParam2,
uint256 percentOfHop
) external pure returns (bytes memory out) {
FraxswapStepData memory step;
step.swapType = swapType;
step.directFundNextPool = directFundNextPool;
step.directFundThisPool = directFundThisPool;
step.tokenOut = tokenOut;
step.pool = pool;
step.extraParam1 = extraParam1;
step.extraParam2 = extraParam2;
step.percentOfHop = percentOfHop;
out = abi.encode(step);
}
/// @notice Utility function to calculate the amount given the percentage of hop and route 10000 = 100%
/// @return amountOut amount of input token
function getAmountForPct(
uint256 pctOfHop1,
uint256 pctOfHop2,
uint256 amountIn
) internal pure returns (uint256 amountOut) {
return (pctOfHop1 * pctOfHop2 * amountIn) / 100_000_000;
}
/// @notice Utility function to get the next pool to directly fund
/// @return nextPoolAddress address of the next pool
function getNextDirectFundingPool(FraxswapRoute memory route)
internal
pure
returns (address nextPoolAddress)
{
require(
route.steps.length == 1 && route.nextHops.length == 1,
"FSR: DFRoutes"
); // directFunding
FraxswapRoute memory nextRoute = abi.decode(
route.nextHops[0],
(FraxswapRoute)
);
require(nextRoute.steps.length == 1, "FSR: DFSteps"); // directFunding
FraxswapStepData memory nextStep = abi.decode(
nextRoute.steps[0],
(FraxswapStepData)
);
return nextStep.pool; // pool to send funds to
}
/// @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
/// @return amountOut constant product curve expected output amount
function getAmountOut(
uint amountIn,
uint reserveIn,
uint reserveOut
) internal pure returns (uint amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint amountInWithFee = amountIn * 997;
uint numerator = amountInWithFee * reserveOut;
uint denominator = reserveIn * 1000 + amountInWithFee;
amountOut = numerator / denominator;
}
/// ---------------------------
/// --------- Structs ---------
/// ---------------------------
/// @notice Input to the swap function
/// @dev contains the top level info for the swap
/// @param tokenIn input token address
/// @param amountIn input token amount
/// @param tokenOut output token address
/// @param amountOutMinimum output token minimum amount (reverts if lower)
/// @param recipient recipient of the output token
/// @param deadline deadline for this swap transaction (reverts if exceeded)
/// @param v v value for permit signature if supported
/// @param r r value for permit signature if supported
/// @param s s value for permit signature if supported
/// @param route byte encoded
struct FraxswapParams {
address tokenIn;
uint256 amountIn;
address tokenOut;
uint256 amountOutMinimum;
address recipient;
uint256 deadline;
bool approveMax;
uint8 v;
bytes32 r;
bytes32 s;
bytes route;
}
/// @notice A hop along the swap route
/// @dev a series of swaps (steps) containing the same input token and output token
/// @param tokenOut output token address
/// @param amountOut output token amount
/// @param percentOfHop amount of output tokens from the previous hop going into this hop
/// @param steps list of swaps from the same input token to the same output token
/// @param nextHops next hops from this one, the next hops' input token is the tokenOut
struct FraxswapRoute {
address tokenOut;
uint256 amountOut;
uint256 percentOfHop;
bytes[] steps;
bytes[] nextHops;
}
/// @notice A swap step in a specific route. routes can have multiple swap steps
/// @dev a single swap to a token from the token of the previous hop in the route
/// @param swapType type of the swap performed (Uniswap V2, Fraxswap,Curve, etc)
/// @param directFundNextPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param directFundThisPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param tokenOut the target token of the step. output token address
/// @param pool address of the pool to use in the step
/// @param extraParam1 extra data used in the step
/// @param extraParam2 extra data used in the step
/// @param percentOfHop percentage of all of the steps in this route (hop)
struct FraxswapStepData {
uint8 swapType;
uint8 directFundNextPool;
uint8 directFundThisPool;
address tokenOut;
address pool;
uint256 extraParam1;
uint256 extraParam2;
uint256 percentOfHop;
}
/// @notice struct for Uniswap V3 callback
/// @param tokenIn address of input token
/// @param directFundThisPool this pool already been funded
struct SwapCallbackData {
address tokenIn;
bool directFundThisPool;
}
/// ---------------------------
/// --------- Events ----------
/// ---------------------------
/// @notice Swap event emitted every swap
/// @param pool address of the pool to used in the step
/// @param tokenIn token address of the input token
/// @param tokenOut token address of the output token
/// @param amountIn amount of input token
/// @param amountOut amount of output token
event Swapped(
address pool,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut
);
/// @notice Routing event emitted every swap
/// @param tokenIn address of the original input token
/// @param tokenOut address of the final output token
/// @param amountIn input amount for original input token
/// @param amountOut output amount for the final output token
event Routed(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut
);
}
|
contract FraxswapRouterMultihop is ReentrancyGuard, Ownable {
using SafeCast for uint256;
using SafeCast for int256;
IWETH WETH9;
address FRAX;
constructor(IWETH _WETH9, address _FRAX) {
WETH9 = _WETH9;
FRAX = _FRAX;
}
/// @notice modifier for checking deadline
modifier checkDeadline(uint256 deadline) {
require(block.timestamp <= deadline, "Transaction too old");
_;
}
/// @notice only accept ETH via fallback from the WETH contract
receive() external payable {
assert(msg.sender == address(WETH9));
}
/// ---------------------------
/// --------- Public ----------
/// ---------------------------
/// @notice Main external swap function
/// @param params all parameters for this swap
/// @return amountOut output amount from this swap
function swap(FraxswapParams memory params)
external
payable
nonReentrant
checkDeadline(params.deadline)
returns (uint256 amountOut)
{
if (params.tokenIn == address(0)) {
// ETH sent in via msg.value
require(msg.value == params.amountIn, "FSR:II"); // Insufficient input ETH
} else {
if (params.v != 0) {
// use permit instead of approval
uint256 amount = params.approveMax
? type(uint256).max
: params.amountIn;
IERC20Permit(params.tokenIn).permit(
msg.sender,
address(this),
amount,
params.deadline,
params.v,
params.r,
params.s
);
}
// Pull tokens into the Router Contract
TransferHelper.safeTransferFrom(
params.tokenIn,
msg.sender,
address(this),
params.amountIn
);
}
FraxswapRoute memory route = abi.decode(params.route, (FraxswapRoute));
route.tokenOut = params.tokenIn;
route.amountOut = params.amountIn;
for (uint256 i; i < route.nextHops.length; ++i) {
FraxswapRoute memory nextRoute = abi.decode(
route.nextHops[i],
(FraxswapRoute)
);
executeAllHops(route, nextRoute);
}
bool outputETH = params.tokenOut == address(0); // save gas
amountOut = outputETH
? address(this).balance
: IERC20(params.tokenOut).balanceOf(address(this));
// Check output amounts and send to recipient (IMPORTANT CHECK)
require(amountOut >= params.amountOutMinimum, "FSR:IO"); // Insufficient output
if (outputETH) {
// sending ETH
(bool success, ) = payable(params.recipient).call{value: amountOut}(
""
);
require(success, "FSR:Invalid transfer");
} else {
TransferHelper.safeTransfer(
params.tokenOut,
params.recipient,
amountOut
);
}
emit Routed(
params.tokenIn,
params.tokenOut,
params.amountIn,
amountOut
);
}
/// @notice Uniswap V3 callback function
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external {
require(amount0Delta > 0 || amount1Delta > 0);
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
if (!data.directFundThisPool) {
// it isn't directly funded we pay from the router address
TransferHelper.safeTransfer(
data.tokenIn,
msg.sender,
uint256(amount0Delta > 0 ? amount0Delta : amount1Delta)
);
}
}
/// ---------------------------
/// --------- Internal --------
/// ---------------------------
/// @notice Function that will execute a particular swap step
/// @param prevRoute previous hop of the route
/// @param route current hop of the route
/// @param step swap to execute
/// @return amountOut actual output from this swap step
function executeSwap(
FraxswapRoute memory prevRoute,
FraxswapRoute memory route,
FraxswapStepData memory step
) internal returns (uint256 amountOut) {
uint256 amountIn = getAmountForPct(
step.percentOfHop,
route.percentOfHop,
prevRoute.amountOut
);
if (step.swapType < 2) {
// Fraxswap/Uni v2
bool zeroForOne = prevRoute.tokenOut < step.tokenOut;
if (step.swapType == 0) {
// Execute virtual orders for Fraxswap
PoolInterface(step.pool).executeVirtualOrders(block.timestamp);
}
if (step.extraParam1 == 1) {
// Fraxswap V2 has getAmountOut in the pair (different fees)
amountOut = PoolInterface(step.pool).getAmountOut(
amountIn,
prevRoute.tokenOut
);
} else {
// use the reserves and helper function for Uniswap V2 and Fraxswap V1
(uint112 reserve0, uint112 reserve1, ) = IUniswapV2Pair(
step.pool
).getReserves();
amountOut = getAmountOut(
amountIn,
zeroForOne ? reserve0 : reserve1,
zeroForOne ? reserve1 : reserve0
);
}
if (step.directFundThisPool == 0) {
// this pool is funded by router
TransferHelper.safeTransfer(
prevRoute.tokenOut,
step.pool,
amountIn
);
}
IUniswapV2Pair(step.pool).swap(
zeroForOne ? 0 : amountOut,
zeroForOne ? amountOut : 0,
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this),
new bytes(0)
);
} else if (step.swapType == 2) {
// Uni v3
bool zeroForOne = prevRoute.tokenOut < step.tokenOut;
(int256 amount0, int256 amount1) = IUniswapV3Pool(step.pool).swap(
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this),
zeroForOne,
amountIn.toInt256(),
zeroForOne
? 4295128740
: 1461446703485210103287273052203988822378723970341, // Do not fail because of price
abi.encode(
SwapCallbackData({
tokenIn: prevRoute.tokenOut,
directFundThisPool: step.directFundThisPool == 1
})
)
);
amountOut = uint256(zeroForOne ? -amount1 : -amount0);
} else if (step.swapType == 3) {
// Curve exchange V2
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
PoolInterface(step.pool).exchange(
step.extraParam1,
step.extraParam2,
amountIn,
0
);
amountOut = IERC20(step.tokenOut).balanceOf(address(this));
} else if (step.swapType == 4) {
// Curve exchange, with returns
uint256 value = 0;
if (prevRoute.tokenOut == address(WETH9)) {
// WETH send as ETH
WETH9.withdraw(amountIn);
value = amountIn;
} else {
TransferHelper.safeApprove(
prevRoute.tokenOut,
step.pool,
amountIn
);
}
amountOut = PoolInterface(step.pool).exchange{value: value}(
int128(int256(step.extraParam1)),
int128(int256(step.extraParam2)),
amountIn,
0
);
if (route.tokenOut == address(WETH9)) {
// Wrap the received ETH as WETH
WETH9.deposit{value: amountOut}();
}
} else if (step.swapType == 5) {
// Curve exchange_underlying
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
amountOut = PoolInterface(step.pool).exchange_underlying(
int128(int256(step.extraParam1)),
int128(int256(step.extraParam2)),
amountIn,
0
);
} else if (step.swapType == 6) {
// Saddle
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
amountOut = PoolInterface(step.pool).swap(
uint8(step.extraParam1),
uint8(step.extraParam2),
amountIn,
0,
block.timestamp
);
} else if (step.swapType == 7) {
// FPIController
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
if (prevRoute.tokenOut == FRAX) {
amountOut = PoolInterface(step.pool).mintFPI(amountIn, 0);
} else {
amountOut = PoolInterface(step.pool).redeemFPI(amountIn, 0);
}
} else if (step.swapType == 8) {
// Fraxlend
TransferHelper.safeApprove(prevRoute.tokenOut, step.pool, amountIn);
amountOut = PoolInterface(step.pool).deposit(
amountIn,
address(this)
);
} else if (step.swapType == 9) {
// FrxETHMinter
if (step.extraParam1 == 0 && prevRoute.tokenOut == address(WETH9)) {
// Unwrap WETH
WETH9.withdraw(amountIn);
}
PoolInterface(step.pool).submitAndGive{value: amountIn}(
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this)
);
amountOut = amountIn; // exchange 1 for 1
} else if (step.swapType == 10) {
// WETH
if (prevRoute.tokenOut == address(WETH9)) {
// Unwrap WETH
WETH9.withdraw(amountIn);
} else {
// Wrap the ETH
WETH9.deposit{value: amountIn}();
}
amountOut = amountIn; // exchange 1 for 1
} else if (step.swapType == 999) {
// Generic Pool
if (step.directFundThisPool == 0) {
// this pool is funded by router
TransferHelper.safeTransfer(
prevRoute.tokenOut,
step.pool,
amountIn
);
}
amountOut = PoolInterface(step.pool).swap(
prevRoute.tokenOut,
route.tokenOut,
amountIn,
step.directFundNextPool == 1
? getNextDirectFundingPool(route)
: address(this)
);
}
emit Swapped(
step.pool,
prevRoute.tokenOut,
step.tokenOut,
amountIn,
amountOut
);
}
/// @notice Function that will loop through and execute swap steps
/// @param prevRoute previous hop of the route
/// @param route current hop of the route
function executeAllStepsForRoute(
FraxswapRoute memory prevRoute,
FraxswapRoute memory route
) internal {
for (uint256 j; j < route.steps.length; ++j) {
FraxswapStepData memory step = abi.decode(
route.steps[j],
(FraxswapStepData)
);
route.amountOut += executeSwap(prevRoute, route, step);
}
}
/// @notice Function that will loop through and execute route hops and execute all steps for each hop
/// @param prevRoute previous hop of the route
/// @param route current hop of the route
function executeAllHops(
FraxswapRoute memory prevRoute,
FraxswapRoute memory route
) internal {
executeAllStepsForRoute(prevRoute, route);
for (uint256 i; i < route.nextHops.length; ++i) {
FraxswapRoute memory nextRoute = abi.decode(
route.nextHops[i],
(FraxswapRoute)
);
executeAllHops(route, nextRoute);
}
}
/// ---------------------------
/// ------ Views / Pure -------
/// ---------------------------
/// @notice Utility function to build an encoded hop of route
/// @param tokenOut output token address
/// @param percentOfHop amount of output tokens from the previous hop going into this hop
/// @param steps list of swaps from the same input token to the same output token
/// @param nextHops next hops from this one, the next hops' input token is the tokenOut
/// @return out encoded FraxswapRoute
function encodeRoute(
address tokenOut,
uint256 percentOfHop,
bytes[] memory steps,
bytes[] memory nextHops
) external pure returns (bytes memory out) {
FraxswapRoute memory route;
route.tokenOut = tokenOut;
route.amountOut = 0;
route.percentOfHop = percentOfHop;
route.steps = steps;
route.nextHops = nextHops;
out = abi.encode(route);
}
/// @notice Utility function to build an encoded step
/// @param swapType type of the swap performed (Uniswap V2, Fraxswap,Curve, etc)
/// @param directFundNextPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param directFundThisPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param tokenOut the target token of the step. output token address
/// @param pool address of the pool to use in the step
/// @param extraParam1 extra data used in the step
/// @param extraParam2 extra data used in the step
/// @param percentOfHop percentage of all of the steps in this route (hop)
/// @return out encoded FraxswapStepData
function encodeStep(
uint8 swapType,
uint8 directFundNextPool,
uint8 directFundThisPool,
address tokenOut,
address pool,
uint256 extraParam1,
uint256 extraParam2,
uint256 percentOfHop
) external pure returns (bytes memory out) {
FraxswapStepData memory step;
step.swapType = swapType;
step.directFundNextPool = directFundNextPool;
step.directFundThisPool = directFundThisPool;
step.tokenOut = tokenOut;
step.pool = pool;
step.extraParam1 = extraParam1;
step.extraParam2 = extraParam2;
step.percentOfHop = percentOfHop;
out = abi.encode(step);
}
/// @notice Utility function to calculate the amount given the percentage of hop and route 10000 = 100%
/// @return amountOut amount of input token
function getAmountForPct(
uint256 pctOfHop1,
uint256 pctOfHop2,
uint256 amountIn
) internal pure returns (uint256 amountOut) {
return (pctOfHop1 * pctOfHop2 * amountIn) / 100_000_000;
}
/// @notice Utility function to get the next pool to directly fund
/// @return nextPoolAddress address of the next pool
function getNextDirectFundingPool(FraxswapRoute memory route)
internal
pure
returns (address nextPoolAddress)
{
require(
route.steps.length == 1 && route.nextHops.length == 1,
"FSR: DFRoutes"
); // directFunding
FraxswapRoute memory nextRoute = abi.decode(
route.nextHops[0],
(FraxswapRoute)
);
require(nextRoute.steps.length == 1, "FSR: DFSteps"); // directFunding
FraxswapStepData memory nextStep = abi.decode(
nextRoute.steps[0],
(FraxswapStepData)
);
return nextStep.pool; // pool to send funds to
}
/// @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
/// @return amountOut constant product curve expected output amount
function getAmountOut(
uint amountIn,
uint reserveIn,
uint reserveOut
) internal pure returns (uint amountOut) {
require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"UniswapV2Library: INSUFFICIENT_LIQUIDITY"
);
uint amountInWithFee = amountIn * 997;
uint numerator = amountInWithFee * reserveOut;
uint denominator = reserveIn * 1000 + amountInWithFee;
amountOut = numerator / denominator;
}
/// ---------------------------
/// --------- Structs ---------
/// ---------------------------
/// @notice Input to the swap function
/// @dev contains the top level info for the swap
/// @param tokenIn input token address
/// @param amountIn input token amount
/// @param tokenOut output token address
/// @param amountOutMinimum output token minimum amount (reverts if lower)
/// @param recipient recipient of the output token
/// @param deadline deadline for this swap transaction (reverts if exceeded)
/// @param v v value for permit signature if supported
/// @param r r value for permit signature if supported
/// @param s s value for permit signature if supported
/// @param route byte encoded
struct FraxswapParams {
address tokenIn;
uint256 amountIn;
address tokenOut;
uint256 amountOutMinimum;
address recipient;
uint256 deadline;
bool approveMax;
uint8 v;
bytes32 r;
bytes32 s;
bytes route;
}
/// @notice A hop along the swap route
/// @dev a series of swaps (steps) containing the same input token and output token
/// @param tokenOut output token address
/// @param amountOut output token amount
/// @param percentOfHop amount of output tokens from the previous hop going into this hop
/// @param steps list of swaps from the same input token to the same output token
/// @param nextHops next hops from this one, the next hops' input token is the tokenOut
struct FraxswapRoute {
address tokenOut;
uint256 amountOut;
uint256 percentOfHop;
bytes[] steps;
bytes[] nextHops;
}
/// @notice A swap step in a specific route. routes can have multiple swap steps
/// @dev a single swap to a token from the token of the previous hop in the route
/// @param swapType type of the swap performed (Uniswap V2, Fraxswap,Curve, etc)
/// @param directFundNextPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param directFundThisPool 0 = funds go via router, 1 = fund are sent directly to pool
/// @param tokenOut the target token of the step. output token address
/// @param pool address of the pool to use in the step
/// @param extraParam1 extra data used in the step
/// @param extraParam2 extra data used in the step
/// @param percentOfHop percentage of all of the steps in this route (hop)
struct FraxswapStepData {
uint8 swapType;
uint8 directFundNextPool;
uint8 directFundThisPool;
address tokenOut;
address pool;
uint256 extraParam1;
uint256 extraParam2;
uint256 percentOfHop;
}
/// @notice struct for Uniswap V3 callback
/// @param tokenIn address of input token
/// @param directFundThisPool this pool already been funded
struct SwapCallbackData {
address tokenIn;
bool directFundThisPool;
}
/// ---------------------------
/// --------- Events ----------
/// ---------------------------
/// @notice Swap event emitted every swap
/// @param pool address of the pool to used in the step
/// @param tokenIn token address of the input token
/// @param tokenOut token address of the output token
/// @param amountIn amount of input token
/// @param amountOut amount of output token
event Swapped(
address pool,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut
);
/// @notice Routing event emitted every swap
/// @param tokenIn address of the original input token
/// @param tokenOut address of the final output token
/// @param amountIn input amount for original input token
/// @param amountOut output amount for the final output token
event Routed(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut
);
}
| 39,953
|
134
|
// Sign out contract//_contract contract&39;s address
|
function signOut(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
delete authorized[_contract];
return OK;
}
|
function signOut(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
delete authorized[_contract];
return OK;
}
| 50,302
|
6
|
// owner set fallback function mode new fallback function mode. true - bet, false - add funds to contract /
|
function ownerSetMod(bool newMod) public
onlyOwner
|
function ownerSetMod(bool newMod) public
onlyOwner
| 49,607
|
99
|
// Transfer tokens into the swap
|
for (i = 0; i < _amounts.length; i++) {
if (_amounts[i] == 0) continue;
|
for (i = 0; i < _amounts.length; i++) {
if (_amounts[i] == 0) continue;
| 65,518
|
88
|
// Withdraw all claimable funds via LoanFDT.
|
uint256 beforeBal = liquidityAsset.balanceOf(address(this)); // Current balance of DebtLocker (accounts for direct inflows).
loan.withdrawFunds(); // Transfer funds from Loan to DebtLocker.
uint256 claimBal = liquidityAsset.balanceOf(address(this)).sub(beforeBal); // Amount claimed from Loan using LoanFDT.
|
uint256 beforeBal = liquidityAsset.balanceOf(address(this)); // Current balance of DebtLocker (accounts for direct inflows).
loan.withdrawFunds(); // Transfer funds from Loan to DebtLocker.
uint256 claimBal = liquidityAsset.balanceOf(address(this)).sub(beforeBal); // Amount claimed from Loan using LoanFDT.
| 6,630
|
24
|
// A master staking contact Will be deployed once as master contact /
|
contract Staking is IStaking, AccessControl, ReentrancyGuard {
using SafeERC20 for ERC20;
ITokenaFactory public immutable factory;
// Whether it is initialized and
bool private _isInitialized;
uint8 public bonusMultiplier;
// Accrued token per share
uint256[] public accTokenPerShare;
uint256 public stakers;
uint256 public startBlock;
uint256 public endBlock;
uint256 public bonusStartBlock;
uint256 public bonusEndBlock;
uint256[] public rewardPerBlock;
uint256[] public rewardTokenAmounts;
uint256 public stakedTokenSupply;
// The precision factor
// The reward token
ERC20[] public rewardToken;
// The staked token
ERC20 public stakedToken;
ProjectInfo public info;
uint128[] private _PRECISION_FACTOR;
uint256 private _numOfRewardTokens;
uint256 private _lastRewardBlock;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256[] rewardDebt; // Reward debt
}
constructor(address adr) {
factory = ITokenaFactory(adr);
}
/**
* @notice initialize stake/LM for user
* @param _stakedToken: address of staked token
* @param _rewardToken: address of reward token
* @param _rewardTokenAmounts: amount of tokens for reward
* @param _startBlock: start time in blocks
* @param _endBlock: estimate time of life for pool in blocks
* @param admin: address of user owner
*/
function initialize(
address _stakedToken,
address[] calldata _rewardToken,
uint256[] calldata _rewardTokenAmounts,
uint256 _startBlock,
uint256 _endBlock,
ProjectInfo calldata _info,
address admin
) external override {
require(!_isInitialized, "Already initialized");
require(msg.sender == address(factory), "Initialize not from factory");
_isInitialized = true;
_setupRole(DEFAULT_ADMIN_ROLE, admin);
// Make this contract initialized
stakedToken = ERC20(_stakedToken);
uint256 i;
for (i; i < _rewardToken.length; i++) {
rewardToken.push(ERC20(_rewardToken[i]));
accTokenPerShare.push(0);
rewardPerBlock.push(_rewardTokenAmounts[i] / (_endBlock - _startBlock));
uint8 decimalsRewardToken = (ERC20(_rewardToken[i]).decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
_PRECISION_FACTOR.push(uint128(10**(30 - (decimalsRewardToken))));
}
info = _info;
startBlock = _startBlock;
_lastRewardBlock = _startBlock;
bonusMultiplier = 1;
endBlock = _endBlock;
rewardTokenAmounts = _rewardTokenAmounts;
_numOfRewardTokens = _rewardToken.length;
}
/**
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param amount: amount to deposit (in stakedToken)
*/
function deposit(uint256 amount) external nonReentrant {
require(amount != 0, "Must deposit not 0");
require(block.number < endBlock, "Pool already end");
UserInfo storage user = userInfo[msg.sender];
uint256 pending;
uint256 i;
if (user.rewardDebt.length == 0) {
user.rewardDebt = new uint256[](_numOfRewardTokens);
stakers++;
}
_updatePool();
uint256 curAmount = user.amount;
uint256 balanceBefore = stakedToken.balanceOf(address(this));
stakedToken.safeTransferFrom(address(msg.sender), address(this), amount);
uint256 balanceAfter = stakedToken.balanceOf(address(this));
user.amount = user.amount + (balanceAfter - balanceBefore);
stakedTokenSupply += (balanceAfter - balanceBefore);
for (i = 0; i < _numOfRewardTokens; i++) {
if (curAmount > 0) {
pending = (curAmount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]);
if (pending > 0) {
rewardToken[i].safeTransfer(address(msg.sender), pending);
}
}
user.rewardDebt[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]);
}
}
/**
* @notice Withdraw staked tokens and collect reward tokens
* @param amount: amount to withdraw (in stakedToken)
*/
function withdraw(uint256 amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= amount, "Amount to withdraw too high");
bool flag;
_updatePool();
uint256 pending;
uint256 i;
uint256 curAmount = user.amount;
if (amount > 0) {
user.amount = user.amount - (amount);
stakedToken.safeTransfer(address(msg.sender), amount);
if (user.amount == 0) {
flag = true;
}
}
stakedTokenSupply -= amount;
for (i = 0; i < _numOfRewardTokens; i++) {
pending = ((curAmount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]));
if (pending > 0) {
rewardToken[i].safeTransfer(address(msg.sender), pending);
}
user.rewardDebt[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]);
}
if (flag) {
delete (userInfo[msg.sender]);
stakers--;
}
}
/**
* @notice Collect reward tokens of a certain index
* @param index: index of the reward token
*/
function withdrawOnlyIndexWithoutUnstake(uint256 index) external nonReentrant {
require(index < _numOfRewardTokens, "Wrong index");
UserInfo storage user = userInfo[msg.sender];
_updatePool();
uint256 newRewardDebt = ((user.amount * (accTokenPerShare[index])) / (_PRECISION_FACTOR[index]));
uint256 pending = (newRewardDebt - (user.rewardDebt[index]));
if (pending > 0) {
rewardToken[index].safeTransfer(address(msg.sender), pending);
}
user.rewardDebt[index] = newRewardDebt;
}
/**
* @notice Withdraw staked tokens without caring about rewards rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
stakedTokenSupply -= amountToTransfer;
delete (userInfo[msg.sender]);
stakers--;
if (amountToTransfer > 0) {
stakedToken.safeTransfer(address(msg.sender), amountToTransfer);
}
}
/**
* @notice Update project info
* @param _info Struct of name, link, themeId
*/
function updateProjectInfo(ProjectInfo calldata _info) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bytes(info.name).length != 0, "Must set name");
require(info.themeId > 0 && info.themeId < 10, "Wrong theme id");
info = _info;
}
/**
* @notice Collect all reward tokens left in pool after certain time has passed
* @param toTransfer: address to transfer leftover tokens to
*/
function getLeftovers(address toTransfer) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
require((endBlock + factory.getDelta()) >= block.number, "Too early");
for (uint256 i; i < _numOfRewardTokens; i++) {
ERC20 token = rewardToken[i];
token.safeTransfer(toTransfer, token.balanceOf(address(this)));
}
}
/**
* @notice Start bonus time
* @param _bonusMultiplier multiplier reward
* @param _bonusStartBlock block from which bonus starts
* @param _bonusEndBlock block in which user want stop bonus period
*/
function startBonusTime(
uint8 _bonusMultiplier,
uint256 _bonusStartBlock,
uint256 _bonusEndBlock
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_bonusMultiplier > 1, "Multiplier must be > 1");
require(_bonusStartBlock >= startBlock && _bonusStartBlock < endBlock, "Non valid start time");
require(_bonusEndBlock > startBlock && _bonusEndBlock > _bonusStartBlock, "Non valid end time");
_updatePool();
require(bonusEndBlock == 0, "Can't start another Bonus Time");
uint256 _endBlock = endBlock - ((_bonusEndBlock - _bonusStartBlock) * (_bonusMultiplier - 1));
require(_endBlock > block.number && _endBlock > startBlock, "Not enough rewards for Bonus");
if (_endBlock < _bonusEndBlock) {
bonusEndBlock = _endBlock;
} else {
bonusEndBlock = _bonusEndBlock;
}
bonusMultiplier = _bonusMultiplier;
bonusStartBlock = _bonusStartBlock;
endBlock = _endBlock;
}
/**
* @notice Change time of end pool
* @param _endBlock endBlock
*/
function updateEndBlock(uint256 _endBlock) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {
require(endBlock > block.number, "Pool already finished");
require(_endBlock > endBlock, "Cannot shorten");
uint256 blocksAdded = _endBlock - endBlock;
for (uint256 i; i < _numOfRewardTokens; i++) {
uint256 toTransfer = blocksAdded * rewardPerBlock[i];
require(toTransfer > 100, "Too short for increase");
address taker = factory.getFeeTaker();
uint256 percent = factory.getFeePercentage();
uint256 balanceBefore = rewardToken[i].balanceOf(address(this));
rewardToken[i].safeTransferFrom(msg.sender, address(this), toTransfer);
uint256 balanceAfter = rewardToken[i].balanceOf(address(this));
rewardTokenAmounts[i] += balanceAfter - balanceBefore;
if (!factory.whitelistAddress(address(rewardToken[i]))) {
rewardToken[i].safeTransferFrom(msg.sender, taker, (toTransfer * percent) / 100);
}
}
endBlock = _endBlock;
}
function getRewardTokens() external view returns (ERC20[] memory) {
return rewardToken;
}
/**
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256[] memory) {
require(block.number > startBlock, "Pool is not started yet");
UserInfo memory user = userInfo[_user];
uint256[] memory toReturn = new uint256[](_numOfRewardTokens);
for (uint256 i; i < _numOfRewardTokens; i++) {
if (block.number > _lastRewardBlock && stakedTokenSupply != 0) {
uint256 multiplier = _getMultiplier(_lastRewardBlock, block.number);
uint256 reward = multiplier * (rewardPerBlock[i]);
uint256 adjustedTokenPerShare = accTokenPerShare[i] + ((reward * (_PRECISION_FACTOR[i])) / (stakedTokenSupply));
toReturn[i] = (user.amount * (adjustedTokenPerShare)) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]);
} else {
toReturn[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]);
}
}
return toReturn;
}
/**
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
if (block.number <= _lastRewardBlock) {
return;
}
if (stakedTokenSupply == 0) {
_lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(_lastRewardBlock, block.number);
for (uint256 i; i < _numOfRewardTokens; i++) {
uint256 reward = multiplier * (rewardPerBlock[i]);
accTokenPerShare[i] = accTokenPerShare[i] + ((reward * (_PRECISION_FACTOR[i])) / (stakedTokenSupply));
}
if (endBlock > block.number) {
_lastRewardBlock = block.number;
} else {
_lastRewardBlock = endBlock;
}
if (bonusEndBlock != 0 && block.number > bonusEndBlock) {
bonusStartBlock = 0;
bonusEndBlock = 0;
bonusMultiplier = 1;
}
}
/**
* @notice Return reward multiplier over the given from to to block.
* @param from: block to start
* @param to: block to finish
* @return The weighted multiplier for the given period
*/
function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) {
from = from >= startBlock ? from : startBlock;
to = endBlock > to ? to : endBlock;
if (from < bonusStartBlock && to > bonusEndBlock) {
return bonusStartBlock - from + to - bonusEndBlock + (bonusEndBlock - bonusStartBlock) * bonusMultiplier;
} else if (from < bonusStartBlock && to > bonusStartBlock) {
return bonusStartBlock - from + (to - bonusStartBlock) * bonusMultiplier;
} else if (from < bonusEndBlock && to > bonusEndBlock) {
return to - bonusEndBlock + (bonusEndBlock - from) * bonusMultiplier;
} else if (from >= bonusStartBlock && to <= bonusEndBlock) {
return (to - from) * bonusMultiplier;
} else {
return to - from;
}
}
}
|
contract Staking is IStaking, AccessControl, ReentrancyGuard {
using SafeERC20 for ERC20;
ITokenaFactory public immutable factory;
// Whether it is initialized and
bool private _isInitialized;
uint8 public bonusMultiplier;
// Accrued token per share
uint256[] public accTokenPerShare;
uint256 public stakers;
uint256 public startBlock;
uint256 public endBlock;
uint256 public bonusStartBlock;
uint256 public bonusEndBlock;
uint256[] public rewardPerBlock;
uint256[] public rewardTokenAmounts;
uint256 public stakedTokenSupply;
// The precision factor
// The reward token
ERC20[] public rewardToken;
// The staked token
ERC20 public stakedToken;
ProjectInfo public info;
uint128[] private _PRECISION_FACTOR;
uint256 private _numOfRewardTokens;
uint256 private _lastRewardBlock;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256[] rewardDebt; // Reward debt
}
constructor(address adr) {
factory = ITokenaFactory(adr);
}
/**
* @notice initialize stake/LM for user
* @param _stakedToken: address of staked token
* @param _rewardToken: address of reward token
* @param _rewardTokenAmounts: amount of tokens for reward
* @param _startBlock: start time in blocks
* @param _endBlock: estimate time of life for pool in blocks
* @param admin: address of user owner
*/
function initialize(
address _stakedToken,
address[] calldata _rewardToken,
uint256[] calldata _rewardTokenAmounts,
uint256 _startBlock,
uint256 _endBlock,
ProjectInfo calldata _info,
address admin
) external override {
require(!_isInitialized, "Already initialized");
require(msg.sender == address(factory), "Initialize not from factory");
_isInitialized = true;
_setupRole(DEFAULT_ADMIN_ROLE, admin);
// Make this contract initialized
stakedToken = ERC20(_stakedToken);
uint256 i;
for (i; i < _rewardToken.length; i++) {
rewardToken.push(ERC20(_rewardToken[i]));
accTokenPerShare.push(0);
rewardPerBlock.push(_rewardTokenAmounts[i] / (_endBlock - _startBlock));
uint8 decimalsRewardToken = (ERC20(_rewardToken[i]).decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
_PRECISION_FACTOR.push(uint128(10**(30 - (decimalsRewardToken))));
}
info = _info;
startBlock = _startBlock;
_lastRewardBlock = _startBlock;
bonusMultiplier = 1;
endBlock = _endBlock;
rewardTokenAmounts = _rewardTokenAmounts;
_numOfRewardTokens = _rewardToken.length;
}
/**
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param amount: amount to deposit (in stakedToken)
*/
function deposit(uint256 amount) external nonReentrant {
require(amount != 0, "Must deposit not 0");
require(block.number < endBlock, "Pool already end");
UserInfo storage user = userInfo[msg.sender];
uint256 pending;
uint256 i;
if (user.rewardDebt.length == 0) {
user.rewardDebt = new uint256[](_numOfRewardTokens);
stakers++;
}
_updatePool();
uint256 curAmount = user.amount;
uint256 balanceBefore = stakedToken.balanceOf(address(this));
stakedToken.safeTransferFrom(address(msg.sender), address(this), amount);
uint256 balanceAfter = stakedToken.balanceOf(address(this));
user.amount = user.amount + (balanceAfter - balanceBefore);
stakedTokenSupply += (balanceAfter - balanceBefore);
for (i = 0; i < _numOfRewardTokens; i++) {
if (curAmount > 0) {
pending = (curAmount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]);
if (pending > 0) {
rewardToken[i].safeTransfer(address(msg.sender), pending);
}
}
user.rewardDebt[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]);
}
}
/**
* @notice Withdraw staked tokens and collect reward tokens
* @param amount: amount to withdraw (in stakedToken)
*/
function withdraw(uint256 amount) external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= amount, "Amount to withdraw too high");
bool flag;
_updatePool();
uint256 pending;
uint256 i;
uint256 curAmount = user.amount;
if (amount > 0) {
user.amount = user.amount - (amount);
stakedToken.safeTransfer(address(msg.sender), amount);
if (user.amount == 0) {
flag = true;
}
}
stakedTokenSupply -= amount;
for (i = 0; i < _numOfRewardTokens; i++) {
pending = ((curAmount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]));
if (pending > 0) {
rewardToken[i].safeTransfer(address(msg.sender), pending);
}
user.rewardDebt[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]);
}
if (flag) {
delete (userInfo[msg.sender]);
stakers--;
}
}
/**
* @notice Collect reward tokens of a certain index
* @param index: index of the reward token
*/
function withdrawOnlyIndexWithoutUnstake(uint256 index) external nonReentrant {
require(index < _numOfRewardTokens, "Wrong index");
UserInfo storage user = userInfo[msg.sender];
_updatePool();
uint256 newRewardDebt = ((user.amount * (accTokenPerShare[index])) / (_PRECISION_FACTOR[index]));
uint256 pending = (newRewardDebt - (user.rewardDebt[index]));
if (pending > 0) {
rewardToken[index].safeTransfer(address(msg.sender), pending);
}
user.rewardDebt[index] = newRewardDebt;
}
/**
* @notice Withdraw staked tokens without caring about rewards rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
stakedTokenSupply -= amountToTransfer;
delete (userInfo[msg.sender]);
stakers--;
if (amountToTransfer > 0) {
stakedToken.safeTransfer(address(msg.sender), amountToTransfer);
}
}
/**
* @notice Update project info
* @param _info Struct of name, link, themeId
*/
function updateProjectInfo(ProjectInfo calldata _info) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(bytes(info.name).length != 0, "Must set name");
require(info.themeId > 0 && info.themeId < 10, "Wrong theme id");
info = _info;
}
/**
* @notice Collect all reward tokens left in pool after certain time has passed
* @param toTransfer: address to transfer leftover tokens to
*/
function getLeftovers(address toTransfer) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
require((endBlock + factory.getDelta()) >= block.number, "Too early");
for (uint256 i; i < _numOfRewardTokens; i++) {
ERC20 token = rewardToken[i];
token.safeTransfer(toTransfer, token.balanceOf(address(this)));
}
}
/**
* @notice Start bonus time
* @param _bonusMultiplier multiplier reward
* @param _bonusStartBlock block from which bonus starts
* @param _bonusEndBlock block in which user want stop bonus period
*/
function startBonusTime(
uint8 _bonusMultiplier,
uint256 _bonusStartBlock,
uint256 _bonusEndBlock
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_bonusMultiplier > 1, "Multiplier must be > 1");
require(_bonusStartBlock >= startBlock && _bonusStartBlock < endBlock, "Non valid start time");
require(_bonusEndBlock > startBlock && _bonusEndBlock > _bonusStartBlock, "Non valid end time");
_updatePool();
require(bonusEndBlock == 0, "Can't start another Bonus Time");
uint256 _endBlock = endBlock - ((_bonusEndBlock - _bonusStartBlock) * (_bonusMultiplier - 1));
require(_endBlock > block.number && _endBlock > startBlock, "Not enough rewards for Bonus");
if (_endBlock < _bonusEndBlock) {
bonusEndBlock = _endBlock;
} else {
bonusEndBlock = _bonusEndBlock;
}
bonusMultiplier = _bonusMultiplier;
bonusStartBlock = _bonusStartBlock;
endBlock = _endBlock;
}
/**
* @notice Change time of end pool
* @param _endBlock endBlock
*/
function updateEndBlock(uint256 _endBlock) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {
require(endBlock > block.number, "Pool already finished");
require(_endBlock > endBlock, "Cannot shorten");
uint256 blocksAdded = _endBlock - endBlock;
for (uint256 i; i < _numOfRewardTokens; i++) {
uint256 toTransfer = blocksAdded * rewardPerBlock[i];
require(toTransfer > 100, "Too short for increase");
address taker = factory.getFeeTaker();
uint256 percent = factory.getFeePercentage();
uint256 balanceBefore = rewardToken[i].balanceOf(address(this));
rewardToken[i].safeTransferFrom(msg.sender, address(this), toTransfer);
uint256 balanceAfter = rewardToken[i].balanceOf(address(this));
rewardTokenAmounts[i] += balanceAfter - balanceBefore;
if (!factory.whitelistAddress(address(rewardToken[i]))) {
rewardToken[i].safeTransferFrom(msg.sender, taker, (toTransfer * percent) / 100);
}
}
endBlock = _endBlock;
}
function getRewardTokens() external view returns (ERC20[] memory) {
return rewardToken;
}
/**
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256[] memory) {
require(block.number > startBlock, "Pool is not started yet");
UserInfo memory user = userInfo[_user];
uint256[] memory toReturn = new uint256[](_numOfRewardTokens);
for (uint256 i; i < _numOfRewardTokens; i++) {
if (block.number > _lastRewardBlock && stakedTokenSupply != 0) {
uint256 multiplier = _getMultiplier(_lastRewardBlock, block.number);
uint256 reward = multiplier * (rewardPerBlock[i]);
uint256 adjustedTokenPerShare = accTokenPerShare[i] + ((reward * (_PRECISION_FACTOR[i])) / (stakedTokenSupply));
toReturn[i] = (user.amount * (adjustedTokenPerShare)) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]);
} else {
toReturn[i] = (user.amount * (accTokenPerShare[i])) / (_PRECISION_FACTOR[i]) - (user.rewardDebt[i]);
}
}
return toReturn;
}
/**
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
if (block.number <= _lastRewardBlock) {
return;
}
if (stakedTokenSupply == 0) {
_lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(_lastRewardBlock, block.number);
for (uint256 i; i < _numOfRewardTokens; i++) {
uint256 reward = multiplier * (rewardPerBlock[i]);
accTokenPerShare[i] = accTokenPerShare[i] + ((reward * (_PRECISION_FACTOR[i])) / (stakedTokenSupply));
}
if (endBlock > block.number) {
_lastRewardBlock = block.number;
} else {
_lastRewardBlock = endBlock;
}
if (bonusEndBlock != 0 && block.number > bonusEndBlock) {
bonusStartBlock = 0;
bonusEndBlock = 0;
bonusMultiplier = 1;
}
}
/**
* @notice Return reward multiplier over the given from to to block.
* @param from: block to start
* @param to: block to finish
* @return The weighted multiplier for the given period
*/
function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) {
from = from >= startBlock ? from : startBlock;
to = endBlock > to ? to : endBlock;
if (from < bonusStartBlock && to > bonusEndBlock) {
return bonusStartBlock - from + to - bonusEndBlock + (bonusEndBlock - bonusStartBlock) * bonusMultiplier;
} else if (from < bonusStartBlock && to > bonusStartBlock) {
return bonusStartBlock - from + (to - bonusStartBlock) * bonusMultiplier;
} else if (from < bonusEndBlock && to > bonusEndBlock) {
return to - bonusEndBlock + (bonusEndBlock - from) * bonusMultiplier;
} else if (from >= bonusStartBlock && to <= bonusEndBlock) {
return (to - from) * bonusMultiplier;
} else {
return to - from;
}
}
}
| 12,275
|
24
|
// All functions must succeed or everything should be rolled back.
|
function buy(address owner, bytes32 id, uint64 qty) public payable {
// Check that seller owns the asset and it exists
Item storage asset = holdings[owner][id];
require(asset.id != 0, "Asset does not exist.");
// Check that asset is for sale
uint64 price = forsale[owner][id];
require(price != 0, "Asset is not for sale.");
// Check that seller has required quantity
require(asset.qty >= qty, "Required qty does not exist.");
// Check that buyer has sent enough value
require(msg.value >= price * qty, "Not enough value.");
// Subtract the quantity of assets in account
asset.qty -= qty;
// If asset is used then reduce old owners helper array
if (asset.qty == 0){
pop(owner, asset);
}
// Check if the beneficiary already has some of the asset.
Item storage existing = holdings[msg.sender][id];
if (existing.qty > 0) {
existing.qty += qty;
} else {
uint256 len = indexes[msg.sender].length;
Item memory newAsset = Item(id, asset.issuer, asset.name, asset.value, asset.unit, qty, asset.validity, asset.resale, len);
holdings[msg.sender][id] = newAsset;
indexes[msg.sender].push(id);
}
// Pay the seller
require(owner.send(msg.value));
}
|
function buy(address owner, bytes32 id, uint64 qty) public payable {
// Check that seller owns the asset and it exists
Item storage asset = holdings[owner][id];
require(asset.id != 0, "Asset does not exist.");
// Check that asset is for sale
uint64 price = forsale[owner][id];
require(price != 0, "Asset is not for sale.");
// Check that seller has required quantity
require(asset.qty >= qty, "Required qty does not exist.");
// Check that buyer has sent enough value
require(msg.value >= price * qty, "Not enough value.");
// Subtract the quantity of assets in account
asset.qty -= qty;
// If asset is used then reduce old owners helper array
if (asset.qty == 0){
pop(owner, asset);
}
// Check if the beneficiary already has some of the asset.
Item storage existing = holdings[msg.sender][id];
if (existing.qty > 0) {
existing.qty += qty;
} else {
uint256 len = indexes[msg.sender].length;
Item memory newAsset = Item(id, asset.issuer, asset.name, asset.value, asset.unit, qty, asset.validity, asset.resale, len);
holdings[msg.sender][id] = newAsset;
indexes[msg.sender].push(id);
}
// Pay the seller
require(owner.send(msg.value));
}
| 34,774
|
368
|
// Concatenates two strings `s1` and `s2`, for example, if `s1` == `foo` and `s2` == `bar`, the result `s` == `foobar` s1 first string s2 second stringreturn s concatenation result s1 + s2 /
|
function concat(string memory s1, string memory s2) internal pure returns (string memory s) {
|
function concat(string memory s1, string memory s2) internal pure returns (string memory s) {
| 50,557
|
142
|
// defines if funds have been already released or not
|
bool private _released = false;
constructor (
IERC20 token,
address beneficiary,
address recovery,
uint256 releaseTime,
uint256 releasePercent
|
bool private _released = false;
constructor (
IERC20 token,
address beneficiary,
address recovery,
uint256 releaseTime,
uint256 releasePercent
| 24,813
|
61
|
// validate inputs
|
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q);
|
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q);
| 29,019
|
2
|
// Emitted when multiple `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. /
|
event TraitTransfer(
|
event TraitTransfer(
| 41,159
|
243
|
// Returns name of the NFT at index. /
|
function tokenNameByIndex(uint256 index) public view returns (string memory) {
return _tokenName[index];
}
|
function tokenNameByIndex(uint256 index) public view returns (string memory) {
return _tokenName[index];
}
| 30,290
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.