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
|
|---|---|---|---|---|
124
|
// Convert from seconds to ledger timer ticks
|
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
|
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
| 27,950
|
30
|
// Sets data for an address/caller THROWS when the account doesn't existaddr The addressindex The index of the datacustomData The data store set /
|
function setAccountData(address addr, uint8 index, bytes32 customData)
isUnlocked
isAllowed(get(addr).kind)
|
function setAccountData(address addr, uint8 index, bytes32 customData)
isUnlocked
isAllowed(get(addr).kind)
| 30,863
|
21
|
// recordDealRefundReason creates an event of not paid deal that was cancelled _orderId Identifier of deal's order_clientAddress Address of client's account_clientReputation Updated reputation of the client_merchantReputation Updated reputation of the merchant_dealHash Hashcode of the deal, describing the order (used for deal verification)_refundReason deal refund reason (text) /
|
function recordDealRefundReason(
uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _refundReason)
external onlyMonetha
|
function recordDealRefundReason(
uint _orderId,
address _clientAddress,
uint32 _clientReputation,
uint32 _merchantReputation,
uint _dealHash,
string _refundReason)
external onlyMonetha
| 25,706
|
0
|
// Computes the result of a swap within ticks/Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
|
interface ISwapMath {
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
/// @param sqrtRatioCurrentX96 The current sqrt price of the pool
/// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
/// @param liquidity The usable liquidity
/// @param amountRemaining How much input or output amount is remaining to be swapped in/out
/// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
/// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
/// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
/// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
/// @return feeAmount The amount of input that will be taken as a fee
function computeSwapStep(
uint160 sqrtRatioCurrentX96,
uint160 sqrtRatioTargetX96,
uint128 liquidity,
int256 amountRemaining,
uint24 feePips
)
external
pure
returns (
uint160 sqrtRatioNextX96,
uint256 amountIn,
uint256 amountOut,
uint256 feeAmount
);
}
|
interface ISwapMath {
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
/// @param sqrtRatioCurrentX96 The current sqrt price of the pool
/// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
/// @param liquidity The usable liquidity
/// @param amountRemaining How much input or output amount is remaining to be swapped in/out
/// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
/// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
/// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
/// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
/// @return feeAmount The amount of input that will be taken as a fee
function computeSwapStep(
uint160 sqrtRatioCurrentX96,
uint160 sqrtRatioTargetX96,
uint128 liquidity,
int256 amountRemaining,
uint24 feePips
)
external
pure
returns (
uint160 sqrtRatioNextX96,
uint256 amountIn,
uint256 amountOut,
uint256 feeAmount
);
}
| 3,939
|
1
|
// releaseTime = now + 3 minutes;
|
allocate();
|
allocate();
| 20,348
|
191
|
// Whether boosting is currently frozen.
|
bool public frozen;
|
bool public frozen;
| 19,137
|
4
|
// These functions call with hidden parameters
|
function callFuncNoParams() external {
doCall(abi.encodeWithSelector(dest.funcNoParams.selector));
}
|
function callFuncNoParams() external {
doCall(abi.encodeWithSelector(dest.funcNoParams.selector));
}
| 38,449
|
92
|
// Burn mineCoin to account when account redeem collateral to collateral pool, only manager contract can modify database. account user's account amount the mine shared amount /
|
function burnMinerCoin(address /*account*/,uint256 /*amount*/) public {
delegateAndReturn();
}
|
function burnMinerCoin(address /*account*/,uint256 /*amount*/) public {
delegateAndReturn();
}
| 34,232
|
36
|
// Distribution contract /
|
contract Distribution is Ownable {
using SafeMath for uint256;
uint16 public stages;
uint256 public stageDuration;
uint256 public startTime;
uint256 public soldTokens;
uint256 public bonusClaimedTokens;
uint256 public raisedETH;
uint256 public raisedUSD;
uint256 public weiUsdRate;
BurnableToken public token;
bool public isActive;
uint256 public cap;
uint256 public stageCap;
mapping (address => mapping (uint16 => uint256)) public contributions;
mapping (uint16 => uint256) public sold;
mapping (uint16 => bool) public burned;
mapping (address => mapping (uint16 => bool)) public claimed;
event NewPurchase(
address indexed purchaser,
uint256 sdtAmount,
uint256 usdAmount,
uint256 ethAmount
);
event NewBonusClaim(
address indexed purchaser,
uint256 sdtAmount
);
function Distribution(
uint16 _stages,
uint256 _stageDuration,
address _token
) public {
stages = _stages;
stageDuration = _stageDuration;
isActive = false;
token = BurnableToken(_token);
}
/**
* @dev contribution function
*/
function () external payable {
require(isActive);
require(weiUsdRate > 0);
require(getStage() < stages);
uint256 usd = msg.value / weiUsdRate;
uint256 tokens = computeTokens(usd);
uint16 stage = getStage();
sold[stage] = sold[stage].add(tokens);
require(sold[stage] < stageCap);
contributions[msg.sender][stage] = contributions[msg.sender][stage].add(tokens);
soldTokens = soldTokens.add(tokens);
raisedETH = raisedETH.add(msg.value);
raisedUSD = raisedUSD.add(usd);
NewPurchase(msg.sender, tokens, usd, msg.value);
token.transfer(msg.sender, tokens);
}
/**
* @dev Initialize distribution
* @param _cap uint256 The amount of tokens for distribution
*/
function init(uint256 _cap, uint256 _startTime) public onlyOwner {
require(!isActive);
require(token.balanceOf(this) == _cap);
require(_startTime > block.timestamp);
startTime = _startTime;
cap = _cap;
stageCap = cap / stages;
isActive = true;
}
/**
* @dev retrieve bonus from specified stage
* @param _stage uint16 The stage
*/
function claimBonus(uint16 _stage) public {
require(!claimed[msg.sender][_stage]);
require(getStage() > _stage);
if (!burned[_stage]) {
token.burn(stageCap.sub(sold[_stage]).sub(sold[_stage].mul(computeBonus(_stage)).div(1 ether)));
burned[_stage] = true;
}
uint256 tokens = computeAddressBonus(_stage);
token.transfer(msg.sender, tokens);
bonusClaimedTokens = bonusClaimedTokens.add(tokens);
claimed[msg.sender][_stage] = true;
NewBonusClaim(msg.sender, tokens);
}
/**
* @dev set an exchange rate in wei
* @param _rate uint256 The new exchange rate
*/
function setWeiUsdRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
weiUsdRate = _rate;
}
/**
* @dev retrieve ETH
* @param _amount uint256 The new exchange rate
* @param _address address The address to receive ETH
*/
function forwardFunds(uint256 _amount, address _address) public onlyOwner {
_address.transfer(_amount);
}
/**
* @dev compute tokens given a USD value
* @param _usd uint256 Value in USD
*/
function computeTokens(uint256 _usd) public view returns(uint256) {
return _usd.mul(1000000000000000000 ether).div(
soldTokens.mul(19800000000000000000).div(cap).add(200000000000000000)
);
}
/**
* @dev current stage
*/
function getStage() public view returns(uint16) {
require(block.timestamp >= startTime);
return uint16(uint256(block.timestamp).sub(startTime).div(stageDuration));
}
/**
* @dev compute bonus (%) for a specified stage
* @param _stage uint16 The stage
*/
function computeBonus(uint16 _stage) public view returns(uint256) {
return uint256(100000000000000000).sub(sold[_stage].mul(100000).div(441095890411));
}
/**
* @dev compute for a specified stage
* @param _stage uint16 The stage
*/
function computeAddressBonus(uint16 _stage) public view returns(uint256) {
return contributions[msg.sender][_stage].mul(computeBonus(_stage)).div(1 ether);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyOwner {
// owner can claim any token but SDT
require(_token != address(token));
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Basic erc20token = ERC20Basic(_token);
uint256 balance = erc20token.balanceOf(this);
erc20token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(
address indexed _token,
address indexed _controller,
uint256 _amount
);
}
|
contract Distribution is Ownable {
using SafeMath for uint256;
uint16 public stages;
uint256 public stageDuration;
uint256 public startTime;
uint256 public soldTokens;
uint256 public bonusClaimedTokens;
uint256 public raisedETH;
uint256 public raisedUSD;
uint256 public weiUsdRate;
BurnableToken public token;
bool public isActive;
uint256 public cap;
uint256 public stageCap;
mapping (address => mapping (uint16 => uint256)) public contributions;
mapping (uint16 => uint256) public sold;
mapping (uint16 => bool) public burned;
mapping (address => mapping (uint16 => bool)) public claimed;
event NewPurchase(
address indexed purchaser,
uint256 sdtAmount,
uint256 usdAmount,
uint256 ethAmount
);
event NewBonusClaim(
address indexed purchaser,
uint256 sdtAmount
);
function Distribution(
uint16 _stages,
uint256 _stageDuration,
address _token
) public {
stages = _stages;
stageDuration = _stageDuration;
isActive = false;
token = BurnableToken(_token);
}
/**
* @dev contribution function
*/
function () external payable {
require(isActive);
require(weiUsdRate > 0);
require(getStage() < stages);
uint256 usd = msg.value / weiUsdRate;
uint256 tokens = computeTokens(usd);
uint16 stage = getStage();
sold[stage] = sold[stage].add(tokens);
require(sold[stage] < stageCap);
contributions[msg.sender][stage] = contributions[msg.sender][stage].add(tokens);
soldTokens = soldTokens.add(tokens);
raisedETH = raisedETH.add(msg.value);
raisedUSD = raisedUSD.add(usd);
NewPurchase(msg.sender, tokens, usd, msg.value);
token.transfer(msg.sender, tokens);
}
/**
* @dev Initialize distribution
* @param _cap uint256 The amount of tokens for distribution
*/
function init(uint256 _cap, uint256 _startTime) public onlyOwner {
require(!isActive);
require(token.balanceOf(this) == _cap);
require(_startTime > block.timestamp);
startTime = _startTime;
cap = _cap;
stageCap = cap / stages;
isActive = true;
}
/**
* @dev retrieve bonus from specified stage
* @param _stage uint16 The stage
*/
function claimBonus(uint16 _stage) public {
require(!claimed[msg.sender][_stage]);
require(getStage() > _stage);
if (!burned[_stage]) {
token.burn(stageCap.sub(sold[_stage]).sub(sold[_stage].mul(computeBonus(_stage)).div(1 ether)));
burned[_stage] = true;
}
uint256 tokens = computeAddressBonus(_stage);
token.transfer(msg.sender, tokens);
bonusClaimedTokens = bonusClaimedTokens.add(tokens);
claimed[msg.sender][_stage] = true;
NewBonusClaim(msg.sender, tokens);
}
/**
* @dev set an exchange rate in wei
* @param _rate uint256 The new exchange rate
*/
function setWeiUsdRate(uint256 _rate) public onlyOwner {
require(_rate > 0);
weiUsdRate = _rate;
}
/**
* @dev retrieve ETH
* @param _amount uint256 The new exchange rate
* @param _address address The address to receive ETH
*/
function forwardFunds(uint256 _amount, address _address) public onlyOwner {
_address.transfer(_amount);
}
/**
* @dev compute tokens given a USD value
* @param _usd uint256 Value in USD
*/
function computeTokens(uint256 _usd) public view returns(uint256) {
return _usd.mul(1000000000000000000 ether).div(
soldTokens.mul(19800000000000000000).div(cap).add(200000000000000000)
);
}
/**
* @dev current stage
*/
function getStage() public view returns(uint16) {
require(block.timestamp >= startTime);
return uint16(uint256(block.timestamp).sub(startTime).div(stageDuration));
}
/**
* @dev compute bonus (%) for a specified stage
* @param _stage uint16 The stage
*/
function computeBonus(uint16 _stage) public view returns(uint256) {
return uint256(100000000000000000).sub(sold[_stage].mul(100000).div(441095890411));
}
/**
* @dev compute for a specified stage
* @param _stage uint16 The stage
*/
function computeAddressBonus(uint16 _stage) public view returns(uint256) {
return contributions[msg.sender][_stage].mul(computeBonus(_stage)).div(1 ether);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyOwner {
// owner can claim any token but SDT
require(_token != address(token));
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Basic erc20token = ERC20Basic(_token);
uint256 balance = erc20token.balanceOf(this);
erc20token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(
address indexed _token,
address indexed _controller,
uint256 _amount
);
}
| 33,496
|
740
|
// amount to return for the bucket
|
uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
availableForBucket[bucket].add(getBucketOwedAmount(bucket))
);
|
uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
availableForBucket[bucket].add(getBucketOwedAmount(bucket))
);
| 39,142
|
16
|
// Fixed point arithmetic library/Taken from https:github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol
|
library FixedMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivDown(x, y, baseUnit); // Equivalent to (x * y) / baseUnit rounded down.
}
function fmul(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function fmulUp(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivUp(x, y, baseUnit); // Equivalent to (x * y) / baseUnit rounded up.
}
function fmulUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivDown(x, baseUnit, y); // Equivalent to (x * baseUnit) / y rounded down.
}
function fdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function fdivUp(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivUp(x, baseUnit, y); // Equivalent to (x * baseUnit) / y rounded up.
}
function fdivUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// We allow z - 1 to underflow if z is 0, because we multiply the
// end result by 0 if z is zero, ensuring we return 0 if z is zero.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
}
|
library FixedMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant RAY = 1e27;
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivDown(x, y, baseUnit); // Equivalent to (x * y) / baseUnit rounded down.
}
function fmul(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function fmulUp(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivUp(x, y, baseUnit); // Equivalent to (x * y) / baseUnit rounded up.
}
function fmulUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivDown(x, baseUnit, y); // Equivalent to (x * baseUnit) / y rounded down.
}
function fdiv(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function fdivUp(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256) {
return mulDivUp(x, baseUnit, y); // Equivalent to (x * baseUnit) / y rounded up.
}
function fdivUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// We allow z - 1 to underflow if z is 0, because we multiply the
// end result by 0 if z is zero, ensuring we return 0 if z is zero.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
}
| 11,199
|
14
|
// Event emitted when external ERC20s are awarded to a winner
|
event AwardedExternalERC20(
address indexed winner,
address indexed token,
uint256 amount
);
|
event AwardedExternalERC20(
address indexed winner,
address indexed token,
uint256 amount
);
| 16,339
|
543
|
// Fees in fee period [0] are not yet available for withdrawal
|
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute);
totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed);
}
|
for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) {
totalFees = totalFees.add(_recentFeePeriodsStorage(i).feesToDistribute);
totalFees = totalFees.sub(_recentFeePeriodsStorage(i).feesClaimed);
}
| 48,795
|
20
|
// funding round status of the FrAactionHub
|
FundingStatus public fundingStatus;
|
FundingStatus public fundingStatus;
| 9,504
|
85
|
// Swap the bnb for tokens
|
pancakeswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
|
pancakeswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
| 21,980
|
104
|
// To see if the minimum goal of tokens of the ICO has been reached / return bool True if the tokens raised are bigger than the goal or false otherwise
|
function goalReached() public view returns(bool) {
return tokensRaised >= minimumGoal;
}
|
function goalReached() public view returns(bool) {
return tokensRaised >= minimumGoal;
}
| 42,601
|
2
|
// accept beneficiary role over timelocked TRIBE
|
function acceptBeneficiary() public override {
_setBeneficiary(msg.sender);
}
|
function acceptBeneficiary() public override {
_setBeneficiary(msg.sender);
}
| 52,424
|
158
|
// Withdraw all from Gauge
|
(, uint256 gaugePTokens, uint256 totalPTokens) = _getTotalPTokens();
ICurveGauge(crvGaugeAddress).withdraw(gaugePTokens);
uint256[3] memory minWithdrawAmounts = [
uint256(0),
uint256(0),
uint256(0)
];
|
(, uint256 gaugePTokens, uint256 totalPTokens) = _getTotalPTokens();
ICurveGauge(crvGaugeAddress).withdraw(gaugePTokens);
uint256[3] memory minWithdrawAmounts = [
uint256(0),
uint256(0),
uint256(0)
];
| 43,337
|
55
|
// Log ETH contributed and tokens generated
|
TokensBought(contributor, msg.value, tokens);
|
TokensBought(contributor, msg.value, tokens);
| 5,544
|
3
|
// ALPHA price
|
uint256 public ALPHA_PRICE = 1000000;
uint256 public ALPHA_PRICE_WAVG = 1000000;
|
uint256 public ALPHA_PRICE = 1000000;
uint256 public ALPHA_PRICE_WAVG = 1000000;
| 31,023
|
259
|
// Returns whether `tokenId` exists.
|
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
|
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
| 3,111
|
59
|
// Token decimals
|
uint public constant DECIMALS = 18;
|
uint public constant DECIMALS = 18;
| 46,448
|
174
|
// pay outstanding interest to lender
|
_PAYINTEREST683(
loanLocal.lender,
loanParamsLocal.loanToken
);
LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id];
LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken];
_SETTLEFEEREWARDFORINTERESTEXPENSE273(
loanInterestLocal,
|
_PAYINTEREST683(
loanLocal.lender,
loanParamsLocal.loanToken
);
LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id];
LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken];
_SETTLEFEEREWARDFORINTERESTEXPENSE273(
loanInterestLocal,
| 43,509
|
14
|
// this eth is now is the contract's possession floatETH += value;
|
floatETH = ExternalSafeMath.add(floatETH, value);
emit Purchase(msg.sender, amount);
return true;
|
floatETH = ExternalSafeMath.add(floatETH, value);
emit Purchase(msg.sender, amount);
return true;
| 5,005
|
13
|
// calculate the next installment date
|
uint256 duration = repaidInstallments.add(1);
duration = duration > params.duration ? params.duration : duration;
_nextInstallment.timestamp = DateTime.addMonths(issuedAt, duration);
_nextInstallment.principal = _nextInstallment.total.sub(
_nextInstallment.interest
);
return _nextInstallment;
|
uint256 duration = repaidInstallments.add(1);
duration = duration > params.duration ? params.duration : duration;
_nextInstallment.timestamp = DateTime.addMonths(issuedAt, duration);
_nextInstallment.principal = _nextInstallment.total.sub(
_nextInstallment.interest
);
return _nextInstallment;
| 6,628
|
16
|
// EnsSubdomainFactoryAllows to create and configure a subdomain for Ethereum ENS in one call. After deploying this contract, change the owner of the top level domain you want to use to this deployed contract address./
|
contract EnsSubdomainFactory is Ownable {
EnsRegistry public registry = EnsRegistry(0x314159265dD8dbb310642f98f50C066173C1259b);
EnsResolver public resolver = EnsResolver(0x5FfC014343cd971B7eb70732021E26C35B744cc4);
event SubdomainCreated(bytes32 indexed subdomain, address indexed owner);
constructor() public {
owner = msg.sender;
}
/**
* @dev The owner can take away the ownership of any top level domain owned by this contract.
*/
function setDomainOwner(bytes32 _node, address _owner) onlyOwner public {
registry.setOwner(_node, _owner);
}
/**
* @dev Allows to create a subdomain, set its resolver and set its target address
* @param _node - namehash of parent domain name e.g. namehash("startonchain.eth")
* @param _subnode - namehash of sub with parent domain name e.g. namehash("radek.startonchain.eth")
* @param _label - hash of subdomain name only e.g. "radek"
* @param _owner - address that will become owner of this new subdomain
* @param _target - address that this new domain will resolve to
*/
function newSubdomain(bytes32 _node, bytes32 _subnode, bytes32 _label, address _owner, address _target) public {
//create new subdomain, temporarily this smartcontract is the owner
registry.setSubnodeOwner(_node, _label, address(this));
//set public resolver for this domain
registry.setResolver(_subnode, resolver);
//set the destination address
resolver.setAddr(_subnode, _target);
//change the ownership back to requested owner
registry.setOwner(_subnode, _owner);
emit SubdomainCreated(_label, _owner);
}
}
|
contract EnsSubdomainFactory is Ownable {
EnsRegistry public registry = EnsRegistry(0x314159265dD8dbb310642f98f50C066173C1259b);
EnsResolver public resolver = EnsResolver(0x5FfC014343cd971B7eb70732021E26C35B744cc4);
event SubdomainCreated(bytes32 indexed subdomain, address indexed owner);
constructor() public {
owner = msg.sender;
}
/**
* @dev The owner can take away the ownership of any top level domain owned by this contract.
*/
function setDomainOwner(bytes32 _node, address _owner) onlyOwner public {
registry.setOwner(_node, _owner);
}
/**
* @dev Allows to create a subdomain, set its resolver and set its target address
* @param _node - namehash of parent domain name e.g. namehash("startonchain.eth")
* @param _subnode - namehash of sub with parent domain name e.g. namehash("radek.startonchain.eth")
* @param _label - hash of subdomain name only e.g. "radek"
* @param _owner - address that will become owner of this new subdomain
* @param _target - address that this new domain will resolve to
*/
function newSubdomain(bytes32 _node, bytes32 _subnode, bytes32 _label, address _owner, address _target) public {
//create new subdomain, temporarily this smartcontract is the owner
registry.setSubnodeOwner(_node, _label, address(this));
//set public resolver for this domain
registry.setResolver(_subnode, resolver);
//set the destination address
resolver.setAddr(_subnode, _target);
//change the ownership back to requested owner
registry.setOwner(_subnode, _owner);
emit SubdomainCreated(_label, _owner);
}
}
| 37,468
|
7
|
// single asset deposit
|
function singleAssetDeposit(address _token, uint256 _tokenAmount) external payable{
require(tokenData.length>0, "Funds can not be deposited before the owner initializes the pool");
Coin _coin = Coin(payable(_token));
uint256 _issuedValue;
//calc new pool value and added user value
uint8 tokenIndex = getTokenIndex(_token); //get index of target token
uint256 weight = uint256(tokenData[tokenIndex]>>160); //get weight of token and convert to decimal
uint256 balance = _coin.balanceOf(address(this));
uint256 balanceGain = badd(bdiv(_tokenAmount,balance),BONE);
uint256 multiplier = bsub(fractPow(balanceGain, weight), BONE);
_issuedValue = bmul(poolValue, multiplier);
bool transferSuccess = _coin.transferFrom(msg.sender, payable(this), _tokenAmount);
require(transferSuccess ==true, "Transfer failed");
poolValue += uint120(_issuedValue);
userValue[msg.sender] += _issuedValue;
}
|
function singleAssetDeposit(address _token, uint256 _tokenAmount) external payable{
require(tokenData.length>0, "Funds can not be deposited before the owner initializes the pool");
Coin _coin = Coin(payable(_token));
uint256 _issuedValue;
//calc new pool value and added user value
uint8 tokenIndex = getTokenIndex(_token); //get index of target token
uint256 weight = uint256(tokenData[tokenIndex]>>160); //get weight of token and convert to decimal
uint256 balance = _coin.balanceOf(address(this));
uint256 balanceGain = badd(bdiv(_tokenAmount,balance),BONE);
uint256 multiplier = bsub(fractPow(balanceGain, weight), BONE);
_issuedValue = bmul(poolValue, multiplier);
bool transferSuccess = _coin.transferFrom(msg.sender, payable(this), _tokenAmount);
require(transferSuccess ==true, "Transfer failed");
poolValue += uint120(_issuedValue);
userValue[msg.sender] += _issuedValue;
}
| 26,813
|
2
|
// Sets the per-item price.
|
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
|
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
| 9,024
|
2
|
// Set oracle address locally Since we use sendChainlinkRequestTo instead of sendChainlinkRequest we set this locally _oracleThis is the address of the oracle registered with chainlink /
|
function setOracle(address _oracle) external onlyOwner {
require(_oracle != address(0)); //Check that it is not the zeroth address
oracle = _oracle;
}
|
function setOracle(address _oracle) external onlyOwner {
require(_oracle != address(0)); //Check that it is not the zeroth address
oracle = _oracle;
}
| 20,568
|
21
|
// calculate dividend holders' shares
|
uint256 dividendPerRecipient = getDividendPayout(
currentPrice,
stock.dividendAmount,
sharesForStock.length - 1
);
|
uint256 dividendPerRecipient = getDividendPayout(
currentPrice,
stock.dividendAmount,
sharesForStock.length - 1
);
| 21,590
|
53
|
// Sets `adminRole` as ``role``'s admin role. Emits a {RoleAdminChanged} event. /
|
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
|
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
| 16,522
|
211
|
// Set contract state. contractState_ The new state of the contract. /
|
function setContractState(uint256 contractState_) external onlyOwner {
require(contractState_ < 2, "Invalid State!");
if (contractState_ == 0) {
contractState = ContractState.OFF;
}
else {
contractState = ContractState.ON;
}
}
|
function setContractState(uint256 contractState_) external onlyOwner {
require(contractState_ < 2, "Invalid State!");
if (contractState_ == 0) {
contractState = ContractState.OFF;
}
else {
contractState = ContractState.ON;
}
}
| 31,940
|
37
|
// |/ Get the number of prints minted for the corresponding seed seed The seed/original NFT token id /
|
function seedToPrintsSupply(uint256 seed)
public
view
returns (uint256)
|
function seedToPrintsSupply(uint256 seed)
public
view
returns (uint256)
| 7,946
|
261
|
// Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
|
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
|
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
| 37,754
|
130
|
// Initializes the ownership slot minted at `index` for efficiency purposes. /
|
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
|
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
| 32,838
|
79
|
// Returns the number of values in the set. O(1). /
|
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
|
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
| 32,319
|
10
|
// Emit an event notifying about the update.
|
emit ProtocolFeeChanged(
address(uint160(oldProtocolFee >> 96)),
_newProtocolFeeRecipient,
uint256(uint96(oldProtocolFee)),
_newProtocolFeePercent
);
|
emit ProtocolFeeChanged(
address(uint160(oldProtocolFee >> 96)),
_newProtocolFeeRecipient,
uint256(uint96(oldProtocolFee)),
_newProtocolFeePercent
);
| 21,082
|
23
|
// require(prizeIds.length <= _prizeID, "DP1"); uint256 rewardAmt; for (uint256 i = 0; i < prizeIds.length; i++) {string memory prizeId = prizeIds[i]; rewardAmt += prizes[prizeId].rewardAmount; delete prizes[prizeId]; _prizeID--; } prizeVault.transfer(address(registrationVault), rewardAmt);emit PrizesDeleted(prizeIds,rewardAmt);
| 3,435
|
||
43
|
// BaseCDPManager all common logic should be moved here in future /
|
abstract contract BaseCDPManager is ReentrancyGuard {
import "../helpers/ReentrancyGuard.sol";
import '../helpers/TransferHelper.sol';
import "../helpers/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
using SafeMath for uint;
IVault public immutable vault;
IVaultManagerParameters public immutable vaultManagerParameters;
IOracleRegistry public immutable oracleRegistry;
ICDPRegistry public immutable cdpRegistry;
IVaultManagerBorrowFeeParameters public immutable vaultManagerBorrowFeeParameters;
IERC20 public immutable usdp;
uint public constant Q112 = 2 ** 112;
uint public constant DENOMINATOR_1E5 = 1e5;
/**
* @dev Trigger when joins are happened
**/
event Join(address indexed asset, address indexed owner, uint main, uint usdp);
/**
* @dev Trigger when exits are happened
**/
event Exit(address indexed asset, address indexed owner, uint main, uint usdp);
/**
* @dev Trigger when liquidations are initiated
**/
event LiquidationTriggered(address indexed asset, address indexed owner);
modifier checkpoint(address asset, address owner) {
_;
cdpRegistry.checkpoint(asset, owner);
}
/**
* @param _vaultManagerParameters The address of the contract with Vault manager parameters
* @param _oracleRegistry The address of the oracle registry
* @param _cdpRegistry The address of the CDP registry
* @param _vaultManagerBorrowFeeParameters The address of the vault manager borrow fee parameters
**/
constructor(address _vaultManagerParameters, address _oracleRegistry, address _cdpRegistry, address _vaultManagerBorrowFeeParameters) {
require(
_vaultManagerParameters != address(0) &&
_oracleRegistry != address(0) &&
_cdpRegistry != address(0) &&
_vaultManagerBorrowFeeParameters != address(0),
"Unit Protocol: INVALID_ARGS"
);
vaultManagerParameters = IVaultManagerParameters(_vaultManagerParameters);
IVault vaultLocal = IVault(IVaultParameters(IVaultManagerParameters(_vaultManagerParameters).vaultParameters()).vault());
vault = vaultLocal;
oracleRegistry = IOracleRegistry(_oracleRegistry);
cdpRegistry = ICDPRegistry(_cdpRegistry);
vaultManagerBorrowFeeParameters = IVaultManagerBorrowFeeParameters(_vaultManagerBorrowFeeParameters);
usdp = IERC20(vaultLocal.usdp());
}
/**
* @notice Charge borrow fee if needed
*/
function _chargeBorrowFee(address asset, address user, uint usdpAmount) internal {
uint borrowFee = vaultManagerBorrowFeeParameters.calcBorrowFeeAmount(asset, usdpAmount);
if (borrowFee == 0) { // very small amount case
return;
}
// to fail with concrete reason, not with TRANSFER_FROM_FAILED from safeTransferFrom
require(usdp.allowance(user, address(this)) >= borrowFee, "Unit Protocol: BORROW_FEE_NOT_APPROVED");
TransferHelper.safeTransferFrom(
address(usdp),
user,
vaultManagerBorrowFeeParameters.feeReceiver(),
borrowFee
);
}
// decreases debt
function _repay(address asset, address owner, uint usdpAmount) internal {
uint fee = vault.calculateFee(asset, owner, usdpAmount);
vault.chargeFee(vault.usdp(), owner, fee);
// burn USDP from the owner's balance
uint debtAfter = vault.repay(asset, owner, usdpAmount);
if (debtAfter == 0) {
// clear unused storage
vault.destroy(asset, owner);
}
}
/**
* @dev Calculates liquidation price
* @param asset The address of the collateral
* @param owner The owner of the position
* @return Q112-encoded liquidation price
**/
function liquidationPrice_q112(
address asset,
address owner
) external view returns (uint) {
uint debt = vault.getTotalDebt(asset, owner);
if (debt == 0) return uint(-1);
uint collateralLiqPrice = debt.mul(100).mul(Q112).div(vaultManagerParameters.liquidationRatio(asset));
require(IToken(asset).decimals() <= 18, "Unit Protocol: NOT_SUPPORTED_DECIMALS");
return collateralLiqPrice / vault.collaterals(asset, owner) / 10 ** (18 - IToken(asset).decimals());
}
function _calcPrincipal(address asset, address owner, uint repayment) internal view returns (uint) {
uint fee = vault.stabilityFee(asset, owner) * (block.timestamp - vault.lastUpdate(asset, owner)) / 365 days;
return repayment * DENOMINATOR_1E5 / (DENOMINATOR_1E5 + fee);
}
/**
* @dev Determines whether a position is liquidatable
* @param asset The address of the collateral
* @param owner The owner of the position
* @param usdValue_q112 Q112-encoded USD value of the collateral
* @return boolean value, whether a position is liquidatable
**/
function _isLiquidatablePosition(
address asset,
address owner,
uint usdValue_q112
) internal view returns (bool) {
uint debt = vault.getTotalDebt(asset, owner);
// position is collateralized if there is no debt
if (debt == 0) return false;
return debt.mul(100).mul(Q112).div(usdValue_q112) >= vaultManagerParameters.liquidationRatio(asset);
}
}
|
abstract contract BaseCDPManager is ReentrancyGuard {
import "../helpers/ReentrancyGuard.sol";
import '../helpers/TransferHelper.sol';
import "../helpers/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
using SafeMath for uint;
IVault public immutable vault;
IVaultManagerParameters public immutable vaultManagerParameters;
IOracleRegistry public immutable oracleRegistry;
ICDPRegistry public immutable cdpRegistry;
IVaultManagerBorrowFeeParameters public immutable vaultManagerBorrowFeeParameters;
IERC20 public immutable usdp;
uint public constant Q112 = 2 ** 112;
uint public constant DENOMINATOR_1E5 = 1e5;
/**
* @dev Trigger when joins are happened
**/
event Join(address indexed asset, address indexed owner, uint main, uint usdp);
/**
* @dev Trigger when exits are happened
**/
event Exit(address indexed asset, address indexed owner, uint main, uint usdp);
/**
* @dev Trigger when liquidations are initiated
**/
event LiquidationTriggered(address indexed asset, address indexed owner);
modifier checkpoint(address asset, address owner) {
_;
cdpRegistry.checkpoint(asset, owner);
}
/**
* @param _vaultManagerParameters The address of the contract with Vault manager parameters
* @param _oracleRegistry The address of the oracle registry
* @param _cdpRegistry The address of the CDP registry
* @param _vaultManagerBorrowFeeParameters The address of the vault manager borrow fee parameters
**/
constructor(address _vaultManagerParameters, address _oracleRegistry, address _cdpRegistry, address _vaultManagerBorrowFeeParameters) {
require(
_vaultManagerParameters != address(0) &&
_oracleRegistry != address(0) &&
_cdpRegistry != address(0) &&
_vaultManagerBorrowFeeParameters != address(0),
"Unit Protocol: INVALID_ARGS"
);
vaultManagerParameters = IVaultManagerParameters(_vaultManagerParameters);
IVault vaultLocal = IVault(IVaultParameters(IVaultManagerParameters(_vaultManagerParameters).vaultParameters()).vault());
vault = vaultLocal;
oracleRegistry = IOracleRegistry(_oracleRegistry);
cdpRegistry = ICDPRegistry(_cdpRegistry);
vaultManagerBorrowFeeParameters = IVaultManagerBorrowFeeParameters(_vaultManagerBorrowFeeParameters);
usdp = IERC20(vaultLocal.usdp());
}
/**
* @notice Charge borrow fee if needed
*/
function _chargeBorrowFee(address asset, address user, uint usdpAmount) internal {
uint borrowFee = vaultManagerBorrowFeeParameters.calcBorrowFeeAmount(asset, usdpAmount);
if (borrowFee == 0) { // very small amount case
return;
}
// to fail with concrete reason, not with TRANSFER_FROM_FAILED from safeTransferFrom
require(usdp.allowance(user, address(this)) >= borrowFee, "Unit Protocol: BORROW_FEE_NOT_APPROVED");
TransferHelper.safeTransferFrom(
address(usdp),
user,
vaultManagerBorrowFeeParameters.feeReceiver(),
borrowFee
);
}
// decreases debt
function _repay(address asset, address owner, uint usdpAmount) internal {
uint fee = vault.calculateFee(asset, owner, usdpAmount);
vault.chargeFee(vault.usdp(), owner, fee);
// burn USDP from the owner's balance
uint debtAfter = vault.repay(asset, owner, usdpAmount);
if (debtAfter == 0) {
// clear unused storage
vault.destroy(asset, owner);
}
}
/**
* @dev Calculates liquidation price
* @param asset The address of the collateral
* @param owner The owner of the position
* @return Q112-encoded liquidation price
**/
function liquidationPrice_q112(
address asset,
address owner
) external view returns (uint) {
uint debt = vault.getTotalDebt(asset, owner);
if (debt == 0) return uint(-1);
uint collateralLiqPrice = debt.mul(100).mul(Q112).div(vaultManagerParameters.liquidationRatio(asset));
require(IToken(asset).decimals() <= 18, "Unit Protocol: NOT_SUPPORTED_DECIMALS");
return collateralLiqPrice / vault.collaterals(asset, owner) / 10 ** (18 - IToken(asset).decimals());
}
function _calcPrincipal(address asset, address owner, uint repayment) internal view returns (uint) {
uint fee = vault.stabilityFee(asset, owner) * (block.timestamp - vault.lastUpdate(asset, owner)) / 365 days;
return repayment * DENOMINATOR_1E5 / (DENOMINATOR_1E5 + fee);
}
/**
* @dev Determines whether a position is liquidatable
* @param asset The address of the collateral
* @param owner The owner of the position
* @param usdValue_q112 Q112-encoded USD value of the collateral
* @return boolean value, whether a position is liquidatable
**/
function _isLiquidatablePosition(
address asset,
address owner,
uint usdValue_q112
) internal view returns (bool) {
uint debt = vault.getTotalDebt(asset, owner);
// position is collateralized if there is no debt
if (debt == 0) return false;
return debt.mul(100).mul(Q112).div(usdValue_q112) >= vaultManagerParameters.liquidationRatio(asset);
}
}
| 19,079
|
61
|
// Transfer back un-sold tokens
|
if(amountRemaining > 0) {
require(
Token(tokens.tokenAddresses[tokenIndex]).transfer(msg.sender, amountRemaining),
"TotlePrimary - failed to transfer remaining tokens to msg.sender after sell"
);
}
|
if(amountRemaining > 0) {
require(
Token(tokens.tokenAddresses[tokenIndex]).transfer(msg.sender, amountRemaining),
"TotlePrimary - failed to transfer remaining tokens to msg.sender after sell"
);
}
| 20,493
|
56
|
// Exit the function once typehash has been located.
|
leave
|
leave
| 37,194
|
13
|
// Some old tokens are implemented without a retrun parameter (this was prior to the ERC20 standart change)
|
function transfer(address to, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
|
function transfer(address to, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
| 37,879
|
116
|
// Constructor/_exchange Address of the IExchangeCore exchange
|
constructor(
address _exchange,
address _weth
)
public
|
constructor(
address _exchange,
address _weth
)
public
| 16,072
|
538
|
// Get total delegation from a given address _delegator - delegator address /
|
function getTotalDelegatorStake(address _delegator)
external view returns (uint256)
|
function getTotalDelegatorStake(address _delegator)
external view returns (uint256)
| 45,427
|
25
|
// 残高の参照/_owner 保有者のアドレス/ return 残高数量
|
function balanceOf(address _owner)
public
view
override
returns (uint256)
|
function balanceOf(address _owner)
public
view
override
returns (uint256)
| 48,853
|
67
|
// This is an alternative to {approve} that can be used as a mitigation forproblems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. /
|
function increaseApproval(
address spender,
uint256 addedValue
)
public
virtual
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
|
function increaseApproval(
address spender,
uint256 addedValue
)
public
virtual
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
| 26,958
|
24
|
// Updates the logic contract for the SuperTokenFactory/This function updates the logic contract for the SuperTokenFactory/newAddress the new address of the SuperTokenFactory logic contract
|
function updateCode(address newAddress) external override {
if (msg.sender != address(_host)) {
revert SUPER_TOKEN_FACTORY_ONLY_HOST();
}
_updateCodeAddress(newAddress);
// Upgrade the Flow NFT logic contracts on the canonical proxies
// We only do this if the new logic contracts passed in updating the SuperTokenFactory
// are different from the current logic contracts
SuperTokenFactory newFactory = SuperTokenFactory(newAddress);
address newConstantOutflowLogic = address(newFactory.CONSTANT_OUTFLOW_NFT_LOGIC());
address newConstantInflowLogic = address(newFactory.CONSTANT_INFLOW_NFT_LOGIC());
if (address(CONSTANT_OUTFLOW_NFT_LOGIC) != newConstantOutflowLogic) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.CONSTANT_OUTFLOW_NFT())).updateCode(newConstantOutflowLogic);
}
if (address(CONSTANT_INFLOW_NFT_LOGIC) != newConstantInflowLogic) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.CONSTANT_INFLOW_NFT())).updateCode(newConstantInflowLogic);
}
if (address(POOL_ADMIN_NFT_LOGIC) != address(newFactory.POOL_ADMIN_NFT_LOGIC())) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.POOL_ADMIN_NFT())).updateCode(
address(newFactory.POOL_ADMIN_NFT_LOGIC())
);
}
if (address(POOL_MEMBER_NFT_LOGIC) != address(newFactory.POOL_MEMBER_NFT_LOGIC())) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.POOL_MEMBER_NFT())).updateCode(
address(newFactory.POOL_MEMBER_NFT_LOGIC())
);
}
}
|
function updateCode(address newAddress) external override {
if (msg.sender != address(_host)) {
revert SUPER_TOKEN_FACTORY_ONLY_HOST();
}
_updateCodeAddress(newAddress);
// Upgrade the Flow NFT logic contracts on the canonical proxies
// We only do this if the new logic contracts passed in updating the SuperTokenFactory
// are different from the current logic contracts
SuperTokenFactory newFactory = SuperTokenFactory(newAddress);
address newConstantOutflowLogic = address(newFactory.CONSTANT_OUTFLOW_NFT_LOGIC());
address newConstantInflowLogic = address(newFactory.CONSTANT_INFLOW_NFT_LOGIC());
if (address(CONSTANT_OUTFLOW_NFT_LOGIC) != newConstantOutflowLogic) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.CONSTANT_OUTFLOW_NFT())).updateCode(newConstantOutflowLogic);
}
if (address(CONSTANT_INFLOW_NFT_LOGIC) != newConstantInflowLogic) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.CONSTANT_INFLOW_NFT())).updateCode(newConstantInflowLogic);
}
if (address(POOL_ADMIN_NFT_LOGIC) != address(newFactory.POOL_ADMIN_NFT_LOGIC())) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.POOL_ADMIN_NFT())).updateCode(
address(newFactory.POOL_ADMIN_NFT_LOGIC())
);
}
if (address(POOL_MEMBER_NFT_LOGIC) != address(newFactory.POOL_MEMBER_NFT_LOGIC())) {
UUPSProxiable(address(_SUPER_TOKEN_LOGIC.POOL_MEMBER_NFT())).updateCode(
address(newFactory.POOL_MEMBER_NFT_LOGIC())
);
}
}
| 35,215
|
48
|
// The account is only partially vaporizable using excess funds
|
else {
state.setParFromDeltaWei(
args.vaporAccount,
args.owedMarket,
excessWei
);
return (false, excessWei);
}
|
else {
state.setParFromDeltaWei(
args.vaporAccount,
args.owedMarket,
excessWei
);
return (false, excessWei);
}
| 24,273
|
4
|
// etherbots
|
(bool found, uint index) = getEtherbotsIndex(proto);
if (found) {
return uint16(380 + index);
}
|
(bool found, uint index) = getEtherbotsIndex(proto);
if (found) {
return uint16(380 + index);
}
| 38,459
|
222
|
// mint unsold to mintAmount
|
if (uniVars.mintToReserves > 0) {
yuan.mint(reservesContracts[0], uniVars.mintToReserves);
}
|
if (uniVars.mintToReserves > 0) {
yuan.mint(reservesContracts[0], uniVars.mintToReserves);
}
| 14,320
|
89
|
// Gets the token holder at the specified index. /
|
function tokenHolder(uint256 _index) accountReaderOnly constant returns (address) {
return allTokenHolders[_index];
}
|
function tokenHolder(uint256 _index) accountReaderOnly constant returns (address) {
return allTokenHolders[_index];
}
| 38,945
|
0
|
// https:docs.synthetix.io/contracts/source/interfaces/ifeepool
|
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
|
interface IFeePool {
// Views
// solhint-disable-next-line func-name-mixedcase
function FEE_ADDRESS() external view returns (address);
function feesAvailable(address account) external view returns (uint, uint);
function feePeriodDuration() external view returns (uint);
function isFeesClaimable(address account) external view returns (bool);
function targetThreshold() external view returns (uint);
function totalFeesAvailable() external view returns (uint);
function totalRewardsAvailable() external view returns (uint);
// Mutative Functions
function claimFees() external returns (bool);
function claimOnBehalf(address claimingForAddress) external returns (bool);
function closeCurrentFeePeriod() external;
// Restricted: used internally to Synthetix
function appendAccountIssuanceRecord(
address account,
uint lockedAmount,
uint debtEntryIndex
) external;
function recordFeePaid(uint sUSDAmount) external;
function setRewardsToDistribute(uint amount) external;
}
| 19,792
|
217
|
// settle vested BZRX only if needed
|
IVestingToken(vBZRX).claim();
|
IVestingToken(vBZRX).claim();
| 40,214
|
96
|
// Tracking mint status
|
bool private _paused = true;
|
bool private _paused = true;
| 76,690
|
68
|
// Events
|
event Embark(address indexed sender, uint index, uint amount, uint amountAfterFee, uint timestamp);
event Disembark(uint start, uint end, bytes32 hash);
event Depart(uint batchNo,uint start,uint end,bytes32 hash);
event RemoveBatch(uint batchNo);
event DisputeBatch(uint batchNo, bytes32 hash);
event Cancelled(uint index, bool cancel);
event Pause(bool paused);
event OwnerNominated(address indexed newOwner);
event OwnerChanged(address indexed previousOwner,address indexed newOwner);
|
event Embark(address indexed sender, uint index, uint amount, uint amountAfterFee, uint timestamp);
event Disembark(uint start, uint end, bytes32 hash);
event Depart(uint batchNo,uint start,uint end,bytes32 hash);
event RemoveBatch(uint batchNo);
event DisputeBatch(uint batchNo, bytes32 hash);
event Cancelled(uint index, bool cancel);
event Pause(bool paused);
event OwnerNominated(address indexed newOwner);
event OwnerChanged(address indexed previousOwner,address indexed newOwner);
| 50,871
|
568
|
// Expecting 60 bytes _extraData for stake delegation.
|
require(_extraData.length == 60, "Stake delegation data must be provided.");
address operator = _extraData.toAddress(20);
|
require(_extraData.length == 60, "Stake delegation data must be provided.");
address operator = _extraData.toAddress(20);
| 7,069
|
7
|
// OpenSea's Proxy Registry
|
IProxyRegistry public immutable proxyRegistry;
|
IProxyRegistry public immutable proxyRegistry;
| 10,854
|
6
|
// Adicionando um NFT aleatoriamente para uma carteira
|
buyers[msg.sender].push(random());
|
buyers[msg.sender].push(random());
| 20,542
|
52
|
// return leaf
|
function getLeaf() external view onlyOwner returns (LeafToken) {
return leaf;
}
|
function getLeaf() external view onlyOwner returns (LeafToken) {
return leaf;
}
| 14,902
|
139
|
// See {ERC20-_beforeTokenTransfer}. Requirements: - minted tokens must not cause the total supply to go over the cap. /
|
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
|
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
| 16,228
|
35
|
// calculate the pending token rewards, use actual user stake rewards will be denoted in token decimals, not 1e18
|
uint256 userTokenPending = userInfo[_pid][_user].staked.mul(poolInfo[_pid].accTokenPerShare).div(1e12).sub(userInfo[_pid][_user].tokenRewardDebt);
if (userTokenPending > 0) {
userInfo[_pid][_user].tokenClaimed = userInfo[_pid][_user].tokenClaimed.add(userTokenPending);
userInfo[_pid][_user].tokenRewardDebt = userInfo[_pid][_user].staked.mul(poolInfo[_pid].accTokenPerShare).div(1e12);
if (poolInfo[_pid].lpStaked) {
_safeTokenTransfer(
poolInfo[_pid].lpToken,
_user,
userTokenPending
|
uint256 userTokenPending = userInfo[_pid][_user].staked.mul(poolInfo[_pid].accTokenPerShare).div(1e12).sub(userInfo[_pid][_user].tokenRewardDebt);
if (userTokenPending > 0) {
userInfo[_pid][_user].tokenClaimed = userInfo[_pid][_user].tokenClaimed.add(userTokenPending);
userInfo[_pid][_user].tokenRewardDebt = userInfo[_pid][_user].staked.mul(poolInfo[_pid].accTokenPerShare).div(1e12);
if (poolInfo[_pid].lpStaked) {
_safeTokenTransfer(
poolInfo[_pid].lpToken,
_user,
userTokenPending
| 30,200
|
359
|
// Update liquidities
|
_updateLiqAmts(staker_address, liquidity, false);
emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address);
|
_updateLiqAmts(staker_address, liquidity, false);
emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address);
| 17,918
|
298
|
// Controller errors
|
string public constant LIST_SIZES_NOT_EQUAL = '36';
string public constant POOL_LIST_ALREADY_SET = '37';
string public constant POOL_ALREADY_LISTED = '38';
string public constant POOL_NOT_LISTED = '39';
string public constant CALLER_NOT_POOL = '40';
string public constant REWARDS_CASH_TOO_LOW = '41';
string public constant FAIL_BECOME_IMPLEMENTATION = '42';
string public constant INSUFFICIENT_DEPOSITED = '43';
string public constant NOT_CLAIMABLE = '44';
string public constant LOCKED = '45';
|
string public constant LIST_SIZES_NOT_EQUAL = '36';
string public constant POOL_LIST_ALREADY_SET = '37';
string public constant POOL_ALREADY_LISTED = '38';
string public constant POOL_NOT_LISTED = '39';
string public constant CALLER_NOT_POOL = '40';
string public constant REWARDS_CASH_TOO_LOW = '41';
string public constant FAIL_BECOME_IMPLEMENTATION = '42';
string public constant INSUFFICIENT_DEPOSITED = '43';
string public constant NOT_CLAIMABLE = '44';
string public constant LOCKED = '45';
| 75,073
|
234
|
// New position has been created./position The address of the user opening new position./collateralToken The token used as collateral for the created position.
|
event PositionCreated(address indexed position, IERC20 indexed collateralToken);
|
event PositionCreated(address indexed position, IERC20 indexed collateralToken);
| 21,833
|
250
|
// unsold tokens allocation oraclize gas limit
|
uint256 public unsoldAllocationOraclizeGasLimit = 2500000;
|
uint256 public unsoldAllocationOraclizeGasLimit = 2500000;
| 24,242
|
89
|
// assmble order parameters into Order struct./ return A list of orders.
|
function assembleOrders(
RingParams params,
TokenTransferDelegate delegate,
address[4][] addressList,
uint[6][] uintArgsList,
uint8[1][] uint8ArgsList,
bool[] buyNoMoreThanAmountBList
)
private
view
|
function assembleOrders(
RingParams params,
TokenTransferDelegate delegate,
address[4][] addressList,
uint[6][] uintArgsList,
uint8[1][] uint8ArgsList,
bool[] buyNoMoreThanAmountBList
)
private
view
| 21,583
|
40
|
// Enjin Team timelock
|
modifier safeTimelock() {
require(now >= endTime + 6 * 4 weeks);
_;
}
|
modifier safeTimelock() {
require(now >= endTime + 6 * 4 weeks);
_;
}
| 41,455
|
42
|
// user receives the amount + the srcReward
|
amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
_safeTransfer(token, _to, amountLD);
emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
|
amountLD = amountSDtoLD(_s.amount.add(_s.eqReward));
_safeTransfer(token, _to, amountLD);
emit SwapRemote(_to, _s.amount.add(_s.eqReward), _s.protocolFee, _s.eqFee);
| 33,750
|
20
|
// Receives native currency, wraps it into WETH-like token and sends cross-chain
|
function sendNativeDeposit(
bytes32 salt,
address refundAddress,
string calldata destinationChain,
string calldata destinationAddress
|
function sendNativeDeposit(
bytes32 salt,
address refundAddress,
string calldata destinationChain,
string calldata destinationAddress
| 9,963
|
14
|
// toggle token invisibility
|
function toggleInvisible(uint256 tokenId) external {
require(ownerOf(tokenId) == _msgSender(), "Token owner only");
_invisibilities[tokenId] = !_invisibilities[tokenId];
}
|
function toggleInvisible(uint256 tokenId) external {
require(ownerOf(tokenId) == _msgSender(), "Token owner only");
_invisibilities[tokenId] = !_invisibilities[tokenId];
}
| 28,142
|
4
|
// approve the router to spend
|
inputToken.safeIncreaseAllowance(address(uniswapRouter), amount);
uint[] memory amounts = uniswapRouter.swapExactTokensForTokens(
amount,
minOutput,
path,
to,
deadline
);
|
inputToken.safeIncreaseAllowance(address(uniswapRouter), amount);
uint[] memory amounts = uniswapRouter.swapExactTokensForTokens(
amount,
minOutput,
path,
to,
deadline
);
| 23,502
|
116
|
// Creates `amount` tokens of token type `id`, and assigns them to `to`.
|
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
|
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
| 2,012
|
284
|
// check the period has rolled over first
|
rolloverFee(sender, lastTransferTimestamp[sender], state.balanceOf(sender));
|
rolloverFee(sender, lastTransferTimestamp[sender], state.balanceOf(sender));
| 35,873
|
20
|
// getABPrice This function wll call internal function _getABPrice that will calculate thecalculate the ABPrice based on current market conditions. It calculates only the unit price AB, not taking inconsideration the slippage. return ABPrice ABPrice is the unit price AB. Meaning how many units of B, buys 1 unit of A /
|
function getABPrice() external override view returns (uint256 ABPrice) {
return _getABPrice();
}
|
function getABPrice() external override view returns (uint256 ABPrice) {
return _getABPrice();
}
| 56,874
|
30
|
// Calculates sqrt(a), following the selected rounding direction. /
|
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
uint256 result = sqrt(a);
if (rounding == Rounding.Up && result * result < a) {
result += 1;
}
return result;
}
|
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
uint256 result = sqrt(a);
if (rounding == Rounding.Up && result * result < a) {
result += 1;
}
return result;
}
| 18,593
|
154
|
// want = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)
|
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public cdp_manager = address(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public vat = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
address public mcd_join_eth_a = address(0x2F0b23f53734252Bda2277357e97e1517d6B042A);
address public mcd_join_dai = address(0x9759A6Ac90977b93B58547b4A71c78317f391A28);
address public mcd_spot = address(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
address public jug = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1);
address public auto_line = address(0xC7Bdd1F2B16447dcf3dE045C4a039A60EC2f0ba3);
|
address constant public weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public dai = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public cdp_manager = address(0x5ef30b9986345249bc32d8928B7ee64DE9435E39);
address public vat = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
address public mcd_join_eth_a = address(0x2F0b23f53734252Bda2277357e97e1517d6B042A);
address public mcd_join_dai = address(0x9759A6Ac90977b93B58547b4A71c78317f391A28);
address public mcd_spot = address(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3);
address public jug = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1);
address public auto_line = address(0xC7Bdd1F2B16447dcf3dE045C4a039A60EC2f0ba3);
| 43,989
|
12
|
// ERC721 events/transfer event/from address transfer from/to address transfer to/tokenId NFT token ID to transfer
|
event Transfer(address from, address to, uint256 tokenId);
|
event Transfer(address from, address to, uint256 tokenId);
| 50,910
|
62
|
// returns the number of contributors in the list of contributors/ return count of contributors/As the `collectAll` function is called the contributor array is cleaned up/ consequently this method only returns the remaining contributor count.
|
function contributorCount() public view returns (uint) {
return contributors.length;
}
|
function contributorCount() public view returns (uint) {
return contributors.length;
}
| 26,760
|
32
|
// modifier for some action only admin or owner can do /
|
modifier onlyAdmins() {
require(msg.sender == owner || admins[msg.sender]);
_;
}
|
modifier onlyAdmins() {
require(msg.sender == owner || admins[msg.sender]);
_;
}
| 62,264
|
15
|
// Adds a country to countryList if the country is not in this list
|
if (campaignsByCountry[country].length == 0){
bytes2 countryCode;
assembly {
countryCode := mload(add(country, 32))
}
|
if (campaignsByCountry[country].length == 0){
bytes2 countryCode;
assembly {
countryCode := mload(add(country, 32))
}
| 70,147
|
113
|
// Emits a {BeneficiaryChanged} event. /
|
function setBeneficiary(address _beneficiary) public {
require(msg.sender == beneficiary, "TokenVestingWallet: only beneficiary");
require(_beneficiary != address(0), "TokenVestingWallet: beneficiary is zero address");
emit BeneficiaryChanged(beneficiary, _beneficiary);
beneficiary = _beneficiary;
}
|
function setBeneficiary(address _beneficiary) public {
require(msg.sender == beneficiary, "TokenVestingWallet: only beneficiary");
require(_beneficiary != address(0), "TokenVestingWallet: beneficiary is zero address");
emit BeneficiaryChanged(beneficiary, _beneficiary);
beneficiary = _beneficiary;
}
| 30,857
|
487
|
// ABI encode calldata for `fillOrder`
|
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchange(address(0)).fillOrder.selector,
order,
takerAssetFillAmount,
signature
);
address exchange = address(EXCHANGE);
(bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata);
if (didSucceed) {
|
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchange(address(0)).fillOrder.selector,
order,
takerAssetFillAmount,
signature
);
address exchange = address(EXCHANGE);
(bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata);
if (didSucceed) {
| 37,168
|
32
|
// in this case, the market is skewed long so its free to short.
|
if (longSupply > shortSupply) {
return (0, rateIsInvalid);
}
|
if (longSupply > shortSupply) {
return (0, rateIsInvalid);
}
| 21,502
|
36
|
// Set the arbitration price. Only callable by the owner._arbitrationPrice Amount to be paid for arbitration. /
|
function setArbitrationPrice(uint _arbitrationPrice) external onlyOwner {
arbitrationPrice = _arbitrationPrice;
}
|
function setArbitrationPrice(uint _arbitrationPrice) external onlyOwner {
arbitrationPrice = _arbitrationPrice;
}
| 51,886
|
4
|
// Basic. Deposit & Withdraw ERC721 from DSA. /
|
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {DSMath} from "../../common/math.sol";
import {Basic} from "../../common/basic.sol";
import {Events} from "./events.sol";
abstract contract BasicResolver is Events, DSMath, Basic {
/**
* @dev Deposit Assets To Smart Account.
* @notice Deposit a ERC721 token to DSA
* @param token Address of token.
* @param tokenId ID of token.
* @param getId ID to retrieve tokenId.
* @param setId ID stores the tokenId.
*/
function depositERC721(
address token,
uint256 tokenId,
uint256 getId,
uint256 setId
)
public
payable
returns (string memory _eventName, bytes memory _eventParam)
{
uint256 _tokenId = getUint(getId, tokenId);
IERC721 tokenContract = IERC721(token);
tokenContract.safeTransferFrom(msg.sender, address(this), _tokenId);
setUint(setId, _tokenId);
_eventName = "LogDepositERC721(address,address,uint256,uint256,uint256)";
_eventParam = abi.encode(token, msg.sender, _tokenId, getId, setId);
}
/**
* @dev Withdraw Assets To Smart Account.
* @notice Withdraw a ERC721 token from DSA
* @param token Address of the token.
* @param tokenId ID of token.
* @param to The address to receive the token upon withdrawal
* @param getId ID to retrieve tokenId.
* @param setId ID stores the tokenId.
*/
function withdrawERC721(
address token,
uint256 tokenId,
address payable to,
uint256 getId,
uint256 setId
)
public
payable
returns (string memory _eventName, bytes memory _eventParam)
{
uint256 _tokenId = getUint(getId, tokenId);
IERC721 tokenContract = IERC721(token);
tokenContract.safeTransferFrom(address(this), to, _tokenId);
setUint(setId, _tokenId);
_eventName = "LogWithdrawERC721(address,uint256,address,uint256,uint256)";
_eventParam = abi.encode(token, _tokenId, to, getId, setId);
}
}
|
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {DSMath} from "../../common/math.sol";
import {Basic} from "../../common/basic.sol";
import {Events} from "./events.sol";
abstract contract BasicResolver is Events, DSMath, Basic {
/**
* @dev Deposit Assets To Smart Account.
* @notice Deposit a ERC721 token to DSA
* @param token Address of token.
* @param tokenId ID of token.
* @param getId ID to retrieve tokenId.
* @param setId ID stores the tokenId.
*/
function depositERC721(
address token,
uint256 tokenId,
uint256 getId,
uint256 setId
)
public
payable
returns (string memory _eventName, bytes memory _eventParam)
{
uint256 _tokenId = getUint(getId, tokenId);
IERC721 tokenContract = IERC721(token);
tokenContract.safeTransferFrom(msg.sender, address(this), _tokenId);
setUint(setId, _tokenId);
_eventName = "LogDepositERC721(address,address,uint256,uint256,uint256)";
_eventParam = abi.encode(token, msg.sender, _tokenId, getId, setId);
}
/**
* @dev Withdraw Assets To Smart Account.
* @notice Withdraw a ERC721 token from DSA
* @param token Address of the token.
* @param tokenId ID of token.
* @param to The address to receive the token upon withdrawal
* @param getId ID to retrieve tokenId.
* @param setId ID stores the tokenId.
*/
function withdrawERC721(
address token,
uint256 tokenId,
address payable to,
uint256 getId,
uint256 setId
)
public
payable
returns (string memory _eventName, bytes memory _eventParam)
{
uint256 _tokenId = getUint(getId, tokenId);
IERC721 tokenContract = IERC721(token);
tokenContract.safeTransferFrom(address(this), to, _tokenId);
setUint(setId, _tokenId);
_eventName = "LogWithdrawERC721(address,uint256,address,uint256,uint256)";
_eventParam = abi.encode(token, _tokenId, to, getId, setId);
}
}
| 25,955
|
147
|
// jsons/toddlerpillars.json
|
string constant _name = "Toddlerpillars";
string constant _symbol = "TDPL";
|
string constant _name = "Toddlerpillars";
string constant _symbol = "TDPL";
| 63,588
|
4
|
// proposers
|
mapping(bytes32 => bool) internal addedProposal;
VotingStatus internal currentStatus;
|
mapping(bytes32 => bool) internal addedProposal;
VotingStatus internal currentStatus;
| 48,299
|
0
|
// All assets are stored with 4 decimal shift unless specified
|
uint128 public constant MO_DECIMALS = 10**4;
uint256 public constant RWA_DECIMALS = 10**12;
event RWAUnitCreated(uint256 indexed rWAUnitId);
event RWAUnitAddedUnitsForTokenId(
uint256 indexed rWAUnitId,
uint16 indexed tokenId,
uint64 units
);
event RWAUnitRedeemedUnitsForTokenId(
|
uint128 public constant MO_DECIMALS = 10**4;
uint256 public constant RWA_DECIMALS = 10**12;
event RWAUnitCreated(uint256 indexed rWAUnitId);
event RWAUnitAddedUnitsForTokenId(
uint256 indexed rWAUnitId,
uint16 indexed tokenId,
uint64 units
);
event RWAUnitRedeemedUnitsForTokenId(
| 33,829
|
678
|
// Calculate the max amount of fyTokens that can be bought from the pool without making the interest rate negative.See section 6.3 of the YieldSpace White paper baseReserves Base reserves amount fyTokenReserves fyToken reserves amount timeTillMaturity time till maturity in seconds ts time till maturity coefficient, multiplied by 2^64 g fee coefficient, multiplied by 2^64return max amount of fyTokens that can be bought from the pool /
|
function maxFYTokenOut(
uint128 baseReserves, uint128 fyTokenReserves,
uint128 timeTillMaturity, int128 ts, int128 g)
|
function maxFYTokenOut(
uint128 baseReserves, uint128 fyTokenReserves,
uint128 timeTillMaturity, int128 ts, int128 g)
| 20,184
|
43
|
// 读取个人信息
|
function getUserById(uint256 _userId) view returns(string _name,uint256 _regTime,uint8 _identity,bool _enable, uint256[] _itemIds){
User memory user = indexToUser[_userId];
_name = user.name;
_regTime=user.regTime;
_identity=user.identity;
_enable=user.enable;
_itemIds=userIndexToJoinItems[_userId];
}
|
function getUserById(uint256 _userId) view returns(string _name,uint256 _regTime,uint8 _identity,bool _enable, uint256[] _itemIds){
User memory user = indexToUser[_userId];
_name = user.name;
_regTime=user.regTime;
_identity=user.identity;
_enable=user.enable;
_itemIds=userIndexToJoinItems[_userId];
}
| 45,283
|
8
|
// VERC MetaProxy construction via calldata.
|
function createProxy (
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _totalSupply,
bytes32 _domainSeparator
|
function createProxy (
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _totalSupply,
bytes32 _domainSeparator
| 12,826
|
61
|
// Internal function to withdraw funds from RariFund to `msg.sender` in exchange for REPT burned from `from`.Please note that you must approve RariFundManager to burn of the necessary amount of REPT. from The address from which REPT will be burned. amount The amount of tokens to be withdrawn.return Boolean indicating success. /
|
function _withdrawFrom(address from, uint256 amount) internal fundEnabled cachePoolBalance returns (bool) {
// Input validation
require(amount > 0, "Withdrawal amount must be greater than 0.");
// Check contract balance of ETH and withdraw from pools if necessary
uint256 contractBalance = _rariFundControllerContract.balance;
if (contractBalance > 0) rariFundController.withdrawToManager(contractBalance);
for (uint256 i = 0; i < _supportedPools.length; i++) {
if (contractBalance >= amount) break;
uint8 pool = _supportedPools[i];
uint256 poolBalance = getPoolBalance(pool);
if (poolBalance <= 0) continue;
uint256 amountLeft = amount.sub(contractBalance);
uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance;
require(rariFundController.withdrawFromPoolKnowingBalanceToManager(pool, poolAmount, poolBalance), "Pool withdrawal failed.");
_poolBalanceCache[pool] = poolBalance.sub(poolAmount);
contractBalance = contractBalance.add(poolAmount);
}
require(amount <= contractBalance, "Available balance not enough to cover amount even after withdrawing from pools.");
// Calculate REPT to burn
uint256 reptAmount = getREPTBurnAmount(from, amount);
_netDeposits = _netDeposits.sub(int256(amount));
rariFundToken.fundManagerBurnFrom(from, reptAmount); // The user must approve the burning of tokens beforehand
(bool senderSuccess, ) = msg.sender.call.value(amount)(""); // Transfer 'amount' in ETH to the sender
require(senderSuccess, "Failed to transfer ETH to sender.");
uint256 balance = address(this).balance;
if (balance > 0) {
(bool controllerSuccess, ) = _rariFundControllerContract.call.value(balance)(""); // Transfer any leftover eth back to fund controller
require(controllerSuccess, "Failed to transfer remaining ETH to RariFundController.");
}
emit Withdrawal(from, msg.sender, amount, reptAmount);
// Update RGT distribution speeds
IRariGovernanceTokenDistributor rariGovernanceTokenDistributor = rariFundToken.rariGovernanceTokenDistributor();
if (address(rariGovernanceTokenDistributor) != address(0) && block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Ethereum, getFundBalance());
return true;
}
|
function _withdrawFrom(address from, uint256 amount) internal fundEnabled cachePoolBalance returns (bool) {
// Input validation
require(amount > 0, "Withdrawal amount must be greater than 0.");
// Check contract balance of ETH and withdraw from pools if necessary
uint256 contractBalance = _rariFundControllerContract.balance;
if (contractBalance > 0) rariFundController.withdrawToManager(contractBalance);
for (uint256 i = 0; i < _supportedPools.length; i++) {
if (contractBalance >= amount) break;
uint8 pool = _supportedPools[i];
uint256 poolBalance = getPoolBalance(pool);
if (poolBalance <= 0) continue;
uint256 amountLeft = amount.sub(contractBalance);
uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance;
require(rariFundController.withdrawFromPoolKnowingBalanceToManager(pool, poolAmount, poolBalance), "Pool withdrawal failed.");
_poolBalanceCache[pool] = poolBalance.sub(poolAmount);
contractBalance = contractBalance.add(poolAmount);
}
require(amount <= contractBalance, "Available balance not enough to cover amount even after withdrawing from pools.");
// Calculate REPT to burn
uint256 reptAmount = getREPTBurnAmount(from, amount);
_netDeposits = _netDeposits.sub(int256(amount));
rariFundToken.fundManagerBurnFrom(from, reptAmount); // The user must approve the burning of tokens beforehand
(bool senderSuccess, ) = msg.sender.call.value(amount)(""); // Transfer 'amount' in ETH to the sender
require(senderSuccess, "Failed to transfer ETH to sender.");
uint256 balance = address(this).balance;
if (balance > 0) {
(bool controllerSuccess, ) = _rariFundControllerContract.call.value(balance)(""); // Transfer any leftover eth back to fund controller
require(controllerSuccess, "Failed to transfer remaining ETH to RariFundController.");
}
emit Withdrawal(from, msg.sender, amount, reptAmount);
// Update RGT distribution speeds
IRariGovernanceTokenDistributor rariGovernanceTokenDistributor = rariFundToken.rariGovernanceTokenDistributor();
if (address(rariGovernanceTokenDistributor) != address(0) && block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Ethereum, getFundBalance());
return true;
}
| 34,352
|
59
|
// Returns how much a user could earn plus the giving block number.
|
function takeWithBlock() external override view returns (uint, uint) {
if(mintCumulation >= maxMintCumulation)
return (0, block.number);
(, , , uint amount) = _computeUserProduct();
return (amount, block.number);
}
|
function takeWithBlock() external override view returns (uint, uint) {
if(mintCumulation >= maxMintCumulation)
return (0, block.number);
(, , , uint amount) = _computeUserProduct();
return (amount, block.number);
}
| 33,435
|
5
|
// NFTs that have been withdrawn to the root chain
|
mapping (uint256 => bool) public withdrawnTokens;
|
mapping (uint256 => bool) public withdrawnTokens;
| 29,442
|
4
|
// The address in which the funds reserved for futuredevelopments are sent.They correspond to the % of the supply specified in the whitepaper. /
|
TokenVault immutable public RESERVED_FUNDS_VAULT;
|
TokenVault immutable public RESERVED_FUNDS_VAULT;
| 14,381
|
14
|
// Token Functions /
|
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
|
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
| 69,846
|
42
|
// Address of OneSplitAudit
|
address public immutable OneSplitAudit;
|
address public immutable OneSplitAudit;
| 37,087
|
99
|
// token The address of the token that will be removed from farming. /
|
function removeAllowableToken(address token) external;
|
function removeAllowableToken(address token) external;
| 46,611
|
14
|
// put in WAVAX, take out sAVAX
|
uint256 inAmount = ((wAvaxResTarget * (10_000 - windowPer10k)) /
1000 -
wAvaxRes);
uint256 outAmount = getAmountOut(inAmount, wAvaxRes, sAvaxRes);
if (
wAvaxBalance >= inAmount &&
sAvax.getPooledAvaxByShares(outAmount) >= inAmount &&
(AuxLPT(msAvax).totalSupply() * maxOverExtensionPer10k) /
10_000 >=
|
uint256 inAmount = ((wAvaxResTarget * (10_000 - windowPer10k)) /
1000 -
wAvaxRes);
uint256 outAmount = getAmountOut(inAmount, wAvaxRes, sAvaxRes);
if (
wAvaxBalance >= inAmount &&
sAvax.getPooledAvaxByShares(outAmount) >= inAmount &&
(AuxLPT(msAvax).totalSupply() * maxOverExtensionPer10k) /
10_000 >=
| 2,837
|
3
|
// Fees paid to the contract that have not yet been withdrawn
|
uint public contractFeesAccrued;
|
uint public contractFeesAccrued;
| 30,949
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.