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 |
|---|---|---|---|---|
144 | // Minter Minting Contract seeding Theras for the purpose of developing Disruptive technology and uniting multi-patent technologies for genesis like creations. | contract TheraTech is TheraFounding {
uint256 internal constant RATE = 39060000000000000;
constructor(address payable Wallet, address payable Token) public Crowdsale(RATE, Wallet, TheraSeeding(Token)) {
}
}
| contract TheraTech is TheraFounding {
uint256 internal constant RATE = 39060000000000000;
constructor(address payable Wallet, address payable Token) public Crowdsale(RATE, Wallet, TheraSeeding(Token)) {
}
}
| 12,458 |
36 | // external/Used to mint IdleTokens, given an underlying amount (eg. DAI).This method triggers a rebalance of the pools if neededNOTE: User should 'approve' _amount of tokens before calling mintIdleTokenNOTE 2: this method can be paused_amount : amount of underlying token to be lended _clientProtocolAmounts : client side calculated amounts to put on each lending protocolreturn mintedTokens : amount of IdleTokens minted / | function mintIdleToken(uint256 _amount, uint256[] memory _clientProtocolAmounts)
public nonReentrant whenNotPaused whenITokenPriceHasNotDecreased
| function mintIdleToken(uint256 _amount, uint256[] memory _clientProtocolAmounts)
public nonReentrant whenNotPaused whenITokenPriceHasNotDecreased
| 36,829 |
16 | // SMART CONTRACT FUNCTIONS / /Add an airline to the registration queue/ | function registerAirline(address newAirline) external
requireIsOperational
requireRegisteredAirline
| function registerAirline(address newAirline) external
requireIsOperational
requireRegisteredAirline
| 43,193 |
279 | // 3. Set back scaled time e.g. stake 10 for 100 seconds, withdraw 5.secondsHeld = (100 - 0)(10 - 0.625) = 937.5 | uint256 secondsHeld = (block.timestamp - oldBalance.weightedTimestamp) *
(totalRaw - (_rawAmount / 8));
| uint256 secondsHeld = (block.timestamp - oldBalance.weightedTimestamp) *
(totalRaw - (_rawAmount / 8));
| 87,867 |
69 | // Update the user's stored veFXS multipliers | _vefxsMultiplierStored[account] = new_vefxs_multiplier;
| _vefxsMultiplierStored[account] = new_vefxs_multiplier;
| 3,706 |
13 | // Events Log | event LogStartPreSaleRound();
event LogPausePreSaleRound();
event LogFinishPreSaleRound(
address AppicsFund,
address EcosystemFund,
address SteemitFund,
address BountyFund
);
event LogStartRoundA();
event LogPauseRoundA();
| event LogStartPreSaleRound();
event LogPausePreSaleRound();
event LogFinishPreSaleRound(
address AppicsFund,
address EcosystemFund,
address SteemitFund,
address BountyFund
);
event LogStartRoundA();
event LogPauseRoundA();
| 13,247 |
44 | // Get Functions / | function isBuyer(uint256 purchase_id) public view returns (bool) {
return (msg.sender == purchases[purchase_id].purchaser);
}
| function isBuyer(uint256 purchase_id) public view returns (bool) {
return (msg.sender == purchases[purchase_id].purchaser);
}
| 15,741 |
8 | // @custom:security-contact wx@weareday.one | contract LuckyChonks is ERC721, ERC721Enumerable, Pausable, AccessControl, ERC721Burnable {
using Counters for Counters.Counter;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
Counters.Counter private _tokenIdCounter;
constructor() ERC721("LuckyChonks", "LUCKY") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function _baseURI() internal pure override returns (string memory) {
return "https://luckychonks.com/meta-testnet/";
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
function safeMint(address to) public onlyRole(MINTER_ROLE) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| contract LuckyChonks is ERC721, ERC721Enumerable, Pausable, AccessControl, ERC721Burnable {
using Counters for Counters.Counter;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
Counters.Counter private _tokenIdCounter;
constructor() ERC721("LuckyChonks", "LUCKY") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
}
function _baseURI() internal pure override returns (string memory) {
return "https://luckychonks.com/meta-testnet/";
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
function safeMint(address to) public onlyRole(MINTER_ROLE) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| 21,470 |
6 | // Admin function to update the Term Finance treasury wallet address/treasuryWalletnew treasury address | function updateTreasuryAddress(address treasuryWallet) external;
| function updateTreasuryAddress(address treasuryWallet) external;
| 35,497 |
11 | // Checks a BLS proof of possession. sender The address signed by the BLS key to generate the proof of possession. blsKey The BLS public key that the validator is using for consensus, should pass proofof possession. 48 bytes. blsPop The BLS public key proof-of-possession, which consists of a signature on theaccount address. 96 bytes.return True upon success. / | function checkProofOfPossession(
address sender,
bytes memory blsKey,
bytes memory blsPop
| function checkProofOfPossession(
address sender,
bytes memory blsKey,
bytes memory blsPop
| 23,050 |
4 | // --- Single ETH listing --- |
function acceptETHListing(
IRarible.Order calldata orderLeft,
bytes calldata signatureLeft,
IRarible.Order calldata orderRight,
bytes calldata signatureRight,
ETHListingParams calldata params,
Fee[] calldata fees
)
external
|
function acceptETHListing(
IRarible.Order calldata orderLeft,
bytes calldata signatureLeft,
IRarible.Order calldata orderRight,
bytes calldata signatureRight,
ETHListingParams calldata params,
Fee[] calldata fees
)
external
| 4,443 |
142 | // return the crowdsale opening time. / | function openingTime() public view returns (uint256) {
return _openingTime;
}
| function openingTime() public view returns (uint256) {
return _openingTime;
}
| 8,141 |
13 | // Bid on the auction with the value sent/ together with this transaction./ The value will only be refunded if the/ auction is not won. | function bid() public payable {
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
// Revert the call if the bidding
// period is over.
require(now <= (auctionStart + biddingTime));
// If the bid is not higher, send the
// money back.
require(msg.value > highestBid);
if (highestBidder != address(0x0)) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it can be prevented by the caller by e.g.
// raising the call stack to 1023. It is always safer
// to let the recipients withdraw their money themselves.
pendingReturns[highestBidder] += highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
emit HighestBidIncreased(msg.sender, msg.value);
}
| function bid() public payable {
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
// Revert the call if the bidding
// period is over.
require(now <= (auctionStart + biddingTime));
// If the bid is not higher, send the
// money back.
require(msg.value > highestBid);
if (highestBidder != address(0x0)) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it can be prevented by the caller by e.g.
// raising the call stack to 1023. It is always safer
// to let the recipients withdraw their money themselves.
pendingReturns[highestBidder] += highestBid;
}
highestBidder = msg.sender;
highestBid = msg.value;
emit HighestBidIncreased(msg.sender, msg.value);
}
| 44,084 |
21 | // transfer remainings to token owner | tokenOwner.transfer(_remainings);
| tokenOwner.transfer(_remainings);
| 16,684 |
283 | // Return the information about past downtime/ | function getPastDowntime(address _staker, uint256 _index)
| function getPastDowntime(address _staker, uint256 _index)
| 50,112 |
379 | // calculate the annualized volatility for given set of parameters base The base token of the pair underlying The underlying token of the pair spot64x64 64x64 fixed point representation of spot price strike64x64 64x64 fixed point representation of strike price timeToMaturity64x64 64x64 fixed point representation of time to maturity (denominated in years)return 64x64 fixed point representation of annualized implied volatility, where 1 is defined as 100% / | function getAnnualizedVolatility64x64(
| function getAnnualizedVolatility64x64(
| 79,991 |
178 | // OK, this defines the emission rate of the token, it'll start at 0.7 FXT/Block, and then be divided by 2 each year (15,770,000 blocks).approximately 10M tokens will be minted the 1st year, 5M the next year, then 2.5M, etc.. Effectively capping the FXT supply at 20M. Initial emission rate: 0.65 FXT per block. | uint256 public constant INITIAL_EMISSION_RATE = 650 finney;
| uint256 public constant INITIAL_EMISSION_RATE = 650 finney;
| 15,391 |
103 | // Given a pool, it returns the number of seconds ago of the oldest stored observation/pool Address of Uniswap V3 pool that we want to observe/ return The number of seconds ago of the oldest observation stored for the pool | function getOldestObservationSecondsAgo(address pool) internal view returns (uint32) {
(, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 0, 'NI');
(uint32 observationTimestamp, , , bool initialized) =
IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);
// The next index might not be initialized if the cardinality is in the process of increasing
// In this case the oldest observation is always in index 0
if (!initialized) {
(observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
}
return uint32(block.timestamp) - observationTimestamp;
}
| function getOldestObservationSecondsAgo(address pool) internal view returns (uint32) {
(, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 0, 'NI');
(uint32 observationTimestamp, , , bool initialized) =
IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);
// The next index might not be initialized if the cardinality is in the process of increasing
// In this case the oldest observation is always in index 0
if (!initialized) {
(observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
}
return uint32(block.timestamp) - observationTimestamp;
}
| 37,766 |
19 | // In case it needs to proxy later in the future | function approve(ERC20Interface erc20, address spender, uint tokens) public returns (bool success) {
require(owner == msg.sender);
require(erc20.approve(spender, tokens));
return true;
}
| function approve(ERC20Interface erc20, address spender, uint tokens) public returns (bool success) {
require(owner == msg.sender);
require(erc20.approve(spender, tokens));
return true;
}
| 41,421 |
32 | // increment the egg counter. | eggs++;
| eggs++;
| 23,704 |
148 | // Invoke Cook Finance A collection of common utility functions for interacting with the CKToken's invoke function / | library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the CKToken to set approvals of the ERC20 token to a spender.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the CKToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ICKToken _ckToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_ckToken.invoke(_token, 0, callData);
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_ckToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
* The new CKToken balance must equal the existing balance less the quantity transferred
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the CKToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_ckToken));
Invoke.invokeTransfer(_ckToken, _token, _to, _quantity);
// Get new balance of transferred token for CKToken
uint256 newBalance = IERC20(_token).balanceOf(address(_ckToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the CKToken to unwrap the passed quantity of WETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_ckToken.invoke(_weth, 0, callData);
}
/**
* Instructs the CKToken to wrap the passed quantity of ETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_ckToken.invoke(_weth, _quantity, callData);
}
}
| library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the CKToken to set approvals of the ERC20 token to a spender.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the CKToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ICKToken _ckToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_ckToken.invoke(_token, 0, callData);
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_ckToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the CKToken to transfer the ERC20 token to a recipient.
* The new CKToken balance must equal the existing balance less the quantity transferred
*
* @param _ckToken CKToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ICKToken _ckToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the CKToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_ckToken));
Invoke.invokeTransfer(_ckToken, _token, _to, _quantity);
// Get new balance of transferred token for CKToken
uint256 newBalance = IERC20(_token).balanceOf(address(_ckToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the CKToken to unwrap the passed quantity of WETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_ckToken.invoke(_weth, 0, callData);
}
/**
* Instructs the CKToken to wrap the passed quantity of ETH
*
* @param _ckToken CKToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_ckToken.invoke(_weth, _quantity, callData);
}
}
| 18,122 |
192 | // Check that token is for sale. | require(sp.amount > 0, "buy::Tokens priced at 0 are not for sale.");
| require(sp.amount > 0, "buy::Tokens priced at 0 are not for sale.");
| 21,496 |
66 | // Set max transaction | function setMaxTxAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
| function setMaxTxAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
| 15,107 |
0 | // Interface of the ERC20 standard as defined in the EIP. / | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 4,727 |
334 | // < 10^30 | returns (uint amountAfterFee)
| returns (uint amountAfterFee)
| 55,269 |
37 | // Pass all relevant position paramaters to be processed w/ Settler Library. Evaluates and returns winner address. | winnerAddress = Settler.settlement_evaluation(encodedForSettler);
| winnerAddress = Settler.settlement_evaluation(encodedForSettler);
| 34,850 |
38 | // We now verify the legitimacy of the transaction (it must be signed by the sender, and not be replayed), and that the recpient will accept to be charged by it. | uint256 preconditionCheck;
(preconditionCheck, recipientContext) = canRelay(msg.sender, from, recipient, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, signature, approvalData);
if (preconditionCheck != uint256(PreconditionCheck.OK)) {
emit CanRelayFailed(msg.sender, from, recipient, functionSelector, preconditionCheck);
return;
}
| uint256 preconditionCheck;
(preconditionCheck, recipientContext) = canRelay(msg.sender, from, recipient, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, signature, approvalData);
if (preconditionCheck != uint256(PreconditionCheck.OK)) {
emit CanRelayFailed(msg.sender, from, recipient, functionSelector, preconditionCheck);
return;
}
| 39,665 |
48 | // Collects and distributes the primary sale value of tokens being claimed. | function collectPrice(MintRequest calldata _req) internal {
if (_req.price == 0) {
return;
}
uint256 totalPrice = _req.price;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
if (_req.currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == totalPrice, "must send total price.");
} else {
require(msg.value == 0, "msg value not zero");
}
address saleRecipient = _req.primarySaleRecipient == address(0)
? primarySaleRecipient
: _req.primarySaleRecipient;
CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), saleRecipient, totalPrice - platformFees);
}
| function collectPrice(MintRequest calldata _req) internal {
if (_req.price == 0) {
return;
}
uint256 totalPrice = _req.price;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
if (_req.currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == totalPrice, "must send total price.");
} else {
require(msg.value == 0, "msg value not zero");
}
address saleRecipient = _req.primarySaleRecipient == address(0)
? primarySaleRecipient
: _req.primarySaleRecipient;
CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_req.currency, _msgSender(), saleRecipient, totalPrice - platformFees);
}
| 14,838 |
63 | // Checks whether an incoming bid is the new current highest bid. | function isNewWinningBid(
uint256 _reserveAmount,
uint256 _currentWinningBidAmount,
uint256 _incomingBidAmount
| function isNewWinningBid(
uint256 _reserveAmount,
uint256 _currentWinningBidAmount,
uint256 _incomingBidAmount
| 23,118 |
102 | // sets swaps contract address. The contract on the addres should implement ISwapsImpl interface/newContract module address for the ISwapsImpl implementation | function setSwapsImplContract(address newContract) external;
| function setSwapsImplContract(address newContract) external;
| 43,010 |
281 | // Controls who (if anyone) can mint a Bit Monster.In web3, these are represented as 0 (NotAllowed), 1 (WhitelistOnly), and 2 (AllAllowed). / | enum MintingState {
NotAllowed,
WhitelistOnly,
AllAllowed
}
| enum MintingState {
NotAllowed,
WhitelistOnly,
AllAllowed
}
| 3,255 |
155 | // Update metadata like cap, time etc. from AssetToken./It is essential that this method is at least called before start and before end. | function updateFromAssetToken() public {
(uint256 _cap, /*goal*/, uint256 _startTime, uint256 _endTime) = IBasicAssetToken(crowdsaleData.token).getLimits();
setCap(_cap);
setCrowdsaleTime(_startTime, _endTime);
}
| function updateFromAssetToken() public {
(uint256 _cap, /*goal*/, uint256 _startTime, uint256 _endTime) = IBasicAssetToken(crowdsaleData.token).getLimits();
setCap(_cap);
setCrowdsaleTime(_startTime, _endTime);
}
| 53,988 |
11 | // 2.从 uniswap v3 中使用 aToken 兑换 busd Approve the router to spend | TransferHelper.safeApprove(ATOKEN, address(swapRouter), balanceOfAToken);
| TransferHelper.safeApprove(ATOKEN, address(swapRouter), balanceOfAToken);
| 9,730 |
36 | // Get hash of the transaction. | bytes32 confirmationHash = keccak256(
abi.encode(peggyId, WITHDRAW_METHOD_NAME, _id, _amount, _destination)
);
| bytes32 confirmationHash = keccak256(
abi.encode(peggyId, WITHDRAW_METHOD_NAME, _id, _amount, _destination)
);
| 33,198 |
37 | // ERC20 Contract and directions of flow between ethereum, token and User. | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private constant MAXCAP = 10000000 * (10 ** uint256(18));
function totalSupply() override public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) override public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) override public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) override public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) override public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) override public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
require(amount + totalSupply() <= MAXCAP, "Max Cap: request for minting more than possible value");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
| contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private constant MAXCAP = 10000000 * (10 ** uint256(18));
function totalSupply() override public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) override public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) override public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) override public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) override public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) override public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
require(amount + totalSupply() <= MAXCAP, "Max Cap: request for minting more than possible value");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
| 19,944 |
40 | // First gets the tokens from msg.sender to this contract (Pool Controller) | bool returnValue = BalancerIERC20(newToken.addr).transferFrom(
self.getController(),
address(self),
newToken.balance
);
require(returnValue, "ERR_ERC20_FALSE");
| bool returnValue = BalancerIERC20(newToken.addr).transferFrom(
self.getController(),
address(self),
newToken.balance
);
require(returnValue, "ERR_ERC20_FALSE");
| 3,816 |
126 | // the orderbooks. Gas is saved when using array to store them instead of mapping | uint[1<<22] private _sellOrders;
uint[1<<22] private _buyOrders;
uint32 private constant _MAX_ID = (1<<22)-1; // the maximum value of an order ID
| uint[1<<22] private _sellOrders;
uint[1<<22] private _buyOrders;
uint32 private constant _MAX_ID = (1<<22)-1; // the maximum value of an order ID
| 38,774 |
150 | // Burn the number of receipt tokens specified | _receiptToken.burn(senderAddr, receiptTokenAmount);
| _receiptToken.burn(senderAddr, receiptTokenAmount);
| 43,927 |
184 | // _user: The address of the user return address[]: The addresses of any markets the user has deployed through this factory./ | function getDeployedMarkets(
address _user
)
public
view
returns(address[] memory)
| function getDeployedMarkets(
address _user
)
public
view
returns(address[] memory)
| 4,608 |
44 | // ==========Queries========== // Returns a boolean stating whether `implementationID` is locked. / | function isImplementationLocked(bytes32 implementationID) external override view returns (bool) {
// Read the implementation holder address from storage.
address implementationHolder = _implementationHolders[implementationID];
// Verify that the implementation exists.
require(implementationHolder != address(0), "ERR_IMPLEMENTATION_ID");
return _lockedImplementations[implementationHolder];
}
| function isImplementationLocked(bytes32 implementationID) external override view returns (bool) {
// Read the implementation holder address from storage.
address implementationHolder = _implementationHolders[implementationID];
// Verify that the implementation exists.
require(implementationHolder != address(0), "ERR_IMPLEMENTATION_ID");
return _lockedImplementations[implementationHolder];
}
| 43,587 |
7 | // Emitted when extension is updated; emitted for each function of the extension. | event ExtensionUpdated(
address indexed oldExtensionAddress,
address indexed newExtensionAddress,
bytes4 indexed functionSelector,
string functionSignature
);
| event ExtensionUpdated(
address indexed oldExtensionAddress,
address indexed newExtensionAddress,
bytes4 indexed functionSelector,
string functionSignature
);
| 5,032 |
10 | // GetAddressCurrentBalance | function GetBalance(address strAddress) external view returns(uint)
| function GetBalance(address strAddress) external view returns(uint)
| 46,850 |
1 | // constant | uint256 public constant VERSION = 10204;
uint16 public constant BASE = 10000; // base for royalty
uint8 public immutable MAX_MINT_TIER_1 = 3;
uint8 public immutable MAX_MINT_TIER_2 = 1;
uint8 public immutable MAX_MINT_PUBLIC = 10;
| uint256 public constant VERSION = 10204;
uint16 public constant BASE = 10000; // base for royalty
uint8 public immutable MAX_MINT_TIER_1 = 3;
uint8 public immutable MAX_MINT_TIER_2 = 1;
uint8 public immutable MAX_MINT_PUBLIC = 10;
| 36,636 |
141 | // The staked token. | IERC20 public immutable stakedToken;
| IERC20 public immutable stakedToken;
| 53,842 |
26 | // Updates a deal by merchant _dealIndex deal index _newRewardRatePpm new reward rate ppm, 100% == 1000000 / | function updateDeal(uint _dealIndex, uint _newRewardRatePpm) public;
| function updateDeal(uint _dealIndex, uint _newRewardRatePpm) public;
| 47,678 |
54 | // CG: Scale the DAI cents amount of the open bid to the smallest DAI unit needed to interact with the DAI ERC20 contract. | uint256 refundTotal = SafeMathTyped.mul256(SafeMathTyped.mul256(bid.pricePerToken, bid.amountOfTokens), bidAssetScaling);
| uint256 refundTotal = SafeMathTyped.mul256(SafeMathTyped.mul256(bid.pricePerToken, bid.amountOfTokens), bidAssetScaling);
| 54,730 |
202 | // Safe erc20 transfer function, just in case if rounding error causes pool to not have enough ERC20s. | function safeERC20Transfer(address _to, uint256 _amount) internal {
uint256 erc20Bal = erc20.balanceOf(address(this));
if (_amount > erc20Bal) {
erc20.transfer(_to, erc20Bal);
} else {
erc20.transfer(_to, _amount);
}
}
| function safeERC20Transfer(address _to, uint256 _amount) internal {
uint256 erc20Bal = erc20.balanceOf(address(this));
if (_amount > erc20Bal) {
erc20.transfer(_to, erc20Bal);
} else {
erc20.transfer(_to, _amount);
}
}
| 30,707 |
37 | // constructor, sets initial rate to 1000 TAN per 1 Ether | function TangentStake(address tokenAddress) public {
tokenContract = Tangent(tokenAddress);
multiplier = 1000;
divisor = 1;
acm = 10**18;
netStakes = 0;
}
| function TangentStake(address tokenAddress) public {
tokenContract = Tangent(tokenAddress);
multiplier = 1000;
divisor = 1;
acm = 10**18;
netStakes = 0;
}
| 1,893 |
19 | // Admin function to set the royalty information receiver The receiver of royalty payments amount The royalty percentage with two decimals (10,000 = 100%) / | function setRoyaltyInfo(address receiver, uint256 amount) external onlyOwnerOrAdmin {
_setRoyaltyInfo(receiver, amount);
}
| function setRoyaltyInfo(address receiver, uint256 amount) external onlyOwnerOrAdmin {
_setRoyaltyInfo(receiver, amount);
}
| 26,495 |
167 | // stores the total amount of the burned governance tokens | uint256 private _totalBurnedAmount;
| uint256 private _totalBurnedAmount;
| 46,327 |
5 | // PUBLIC CALLABLE BY ANYONE/Add funds to the wallet associated with an address + usernameCreate a wallet if none exists. / | function deposit(bytes32 walletID) public payable {
wallets[walletID].balance += msg.value;
emit Deposit(walletID, msg.sender, msg.value);
}
| function deposit(bytes32 walletID) public payable {
wallets[walletID].balance += msg.value;
emit Deposit(walletID, msg.sender, msg.value);
}
| 20,876 |
6 | // Returns the variable rate slope below optimal usage ratio It's the variable rate when usage ratio > 0 and <= OPTIMAL_USAGE_RATIOreturn The variable rate slope, expressed in ray / | function getVariableRateSlope1() external view returns (uint256);
| function getVariableRateSlope1() external view returns (uint256);
| 6,079 |
4 | // repairing a multiple flagships _flagshipIds - ids of the flagships / | function repairFlagships(uint256[] calldata _flagshipIds) external nonReentrant {
for (uint256 i; i < _flagshipIds.length; i++) {
repairFlagship(_flagshipIds[i]);
}
}
| function repairFlagships(uint256[] calldata _flagshipIds) external nonReentrant {
for (uint256 i; i < _flagshipIds.length; i++) {
repairFlagship(_flagshipIds[i]);
}
}
| 22,491 |
10 | // Returns true if and only if the function is running in the constructor | function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
| function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
| 7,525 |
42 | // Check if public minting is live. / | function publicLive()
public view returns (bool)
| function publicLive()
public view returns (bool)
| 29,658 |
109 | // Converts the amount of home tokens into the equivalent amount of foreign tokens._value amount of home tokens. return equivalent amount of foreign tokens./ | function _unshiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, -decimalShift());
}
| function _unshiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, -decimalShift());
}
| 43,415 |
480 | // Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake andboosts their voting power. _amount Units of STAKED_TOKEN to stake _exitCooldown Bool signalling whether to take this opportunity to end any outstanding cooldown andreturn the user back to their full voting power / | function stake(uint256 _amount, bool _exitCooldown) external {
_transferAndStake(_amount, address(0), _exitCooldown);
}
| function stake(uint256 _amount, bool _exitCooldown) external {
_transferAndStake(_amount, address(0), _exitCooldown);
}
| 58,071 |
246 | // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful | mapping (address => mapping (uint256 => TokenVesting)) internal vestings;
mapping (address => uint256) public vestingsLengths;
| mapping (address => mapping (uint256 => TokenVesting)) internal vestings;
mapping (address => uint256) public vestingsLengths;
| 47,100 |
8 | // Don't like the logic here - ToDo Boolean checks (truth table) | if (now < pools[_id].StartTime) return PoolStatus.PreMade;
if (now < pools[_id].OpenForAll && pools[_id].Lefttokens > 0) {
| if (now < pools[_id].StartTime) return PoolStatus.PreMade;
if (now < pools[_id].OpenForAll && pools[_id].Lefttokens > 0) {
| 48,483 |
297 | // set a limit for power for a given alpha to prevent overflow | uint256 limitExponent = 172;//for alpha less or equal 2
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
| uint256 limitExponent = 172;//for alpha less or equal 2
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
| 30,256 |
119 | // Get the borrow limit of the handler (internal)handlerID The handler ID return The borrow limit/ | function _getTokenHandlerBorrowLimit(uint256 handlerID) internal view returns (uint256)
| function _getTokenHandlerBorrowLimit(uint256 handlerID) internal view returns (uint256)
| 36,562 |
15 | // Exposes that this contract thinks it is an AffiliateProgram / | function isAffiliateProgram() public pure returns (bool) {
return true;
}
| function isAffiliateProgram() public pure returns (bool) {
return true;
}
| 26,380 |
21 | // Constructor function Initializes contract with initial supply tokens to the creator of the contract / | constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
| constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
| 32,330 |
18 | // addAirdrop(0xf077eC872d3cA323Ae3aEf0F53Fbe36cdd8924A8,73.9826); | addAirdrop(0x89778fDB388A0CC83b19B51F0b50E78100540B43,500);
addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,50);
addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,40);
addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,50);
| addAirdrop(0x89778fDB388A0CC83b19B51F0b50E78100540B43,500);
addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,50);
addAirdrop(0xBFd271EcC7a54f0950f7021E3A0A81a39bF7434a,40);
addAirdrop(0x5C8403A2617aca5C86946E32E14148776E37f72A,50);
| 38,765 |
8 | // Atomically increases the `borrowAllowance` granted to `receiver` andexecutable by `operator` by the caller. Based on OZ {ERC20-increaseAllowance}for `debtAsset`.operator address who can execute the use of the allowance receiver address who can spend the allowance byAmount to increase borrow allowanceRequirements:- Must emit a {BorrowApproval} event indicating the updated borrow allowance.- Must check `operator` and `receiver` are not zero address. / | function increaseBorrowAllowance(
| function increaseBorrowAllowance(
| 14,259 |
260 | // mapping from tokenId to a struct containing the token's traits | mapping(uint256 => SheepWolf) private tokenTraits;
| mapping(uint256 => SheepWolf) private tokenTraits;
| 32,221 |
10 | // load destination chain id length | chainIdLength := byte(25, blob)
| chainIdLength := byte(25, blob)
| 24,132 |
22 | // Getter for auth token address of a token _tokenId the token idreturn the address of the auth token / | function getAuthTokenAddress(uint256 _tokenId) public view returns (address) {
require(_exists(_tokenId), "ERR_TOKEN_ID");
return authToken[_tokenId];
}
| function getAuthTokenAddress(uint256 _tokenId) public view returns (address) {
require(_exists(_tokenId), "ERR_TOKEN_ID");
return authToken[_tokenId];
}
| 44,045 |
2 | // Info of each rewards pool./tokenPerBlock Reward tokens per block number./lpSupply Total staked amount./accRewardsPerShare Total rewards accumulated per staked token./lastRewardBlock Last time rewards were updated for the pool./endOfEpochBlock End of epoc block number for compute and to avoid deposits. | struct PoolInfo {
uint256 tokenPerBlock;
uint256 lpSupply;
uint128 accRewardsPerShare;
uint64 lastRewardBlock;
uint endOfEpochBlock;
}
| struct PoolInfo {
uint256 tokenPerBlock;
uint256 lpSupply;
uint128 accRewardsPerShare;
uint64 lastRewardBlock;
uint endOfEpochBlock;
}
| 77,585 |
21 | // Counter underflow is impossible as _burnCounter cannot be incremented more than _currentIndex times | unchecked {
return _currentIndex - _burnCounter;
}
| unchecked {
return _currentIndex - _burnCounter;
}
| 37,233 |
114 | // Calculate share based on share price and given amount. / | function _calculateShares(uint256 amount) internal returns (uint256) {
| function _calculateShares(uint256 amount) internal returns (uint256) {
| 24,000 |
25 | // Set inviting registration only | nostarted = true;
| nostarted = true;
| 32,068 |
9 | // Creates a new token type and assigns _initialSupply to an address _maxSupply max supply allowed _initialSupply Optional amount to supply the first owner _id attemptId _data Optional data to pass if receiver is contractreturn The newly created token ID / | function create(
address _creator,
uint256 _maxSupply,
uint256 _initialSupply,
uint256 _id,
uint64 _x,
uint64 _y,
bytes calldata _data
| function create(
address _creator,
uint256 _maxSupply,
uint256 _initialSupply,
uint256 _id,
uint64 _x,
uint64 _y,
bytes calldata _data
| 37,522 |
366 | // Setup token mint | _tokenMintAddress = tokenMintAddress;
_tokenMintContract = TokenMint(tokenMintAddress);
| _tokenMintAddress = tokenMintAddress;
_tokenMintContract = TokenMint(tokenMintAddress);
| 36,055 |
3 | // (userAddress=>messengerAddress[]) to register the messengers of an owner | mapping(address => uint256[]) public ownerMessengers;
| mapping(address => uint256[]) public ownerMessengers;
| 69,384 |
238 | // Unlock back the amount of tokens that were bridged to the other network but failed._token address that bridged token contract._recipient address that will receive the tokens._value amount of tokens to be received./ | function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal {
_setMediatorBalance(_token, mediatorBalance(_token).sub(_value));
LegacyERC20(_token).transfer(_recipient, _value);
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer)
* @param _token address of the token contract.
* @param _receiver the address that will receive the tokens on the other network.
*/
function fixMediatorBalance(address _token, address _receiver) public onlyIfUpgradeabilityOwner {
require(isTokenRegistered(_token));
uint256 balance = ERC677(_token).balanceOf(address(this));
uint256 expectedBalance = mediatorBalance(_token);
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx(_token);
require(available > 0);
if (diff > available) {
diff = available;
}
| function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal {
_setMediatorBalance(_token, mediatorBalance(_token).sub(_value));
LegacyERC20(_token).transfer(_recipient, _value);
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer)
* @param _token address of the token contract.
* @param _receiver the address that will receive the tokens on the other network.
*/
function fixMediatorBalance(address _token, address _receiver) public onlyIfUpgradeabilityOwner {
require(isTokenRegistered(_token));
uint256 balance = ERC677(_token).balanceOf(address(this));
uint256 expectedBalance = mediatorBalance(_token);
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx(_token);
require(available > 0);
if (diff > available) {
diff = available;
}
| 49,255 |
2 | // The address of supplying token (e.g. DAI, USDT) | address public supplyToken;
| address public supplyToken;
| 13,755 |
6 | // proxy owner if used through proxy, address(0) otherwise | require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
| require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
| 16,700 |
0 | // Extension of {ERC1618} that adds a set of accounts with the{TrusteeRole}, which have permission to mint (create) new tokens as/ See {ERC1618-_mint}. Requirements:- the caller must have the {TrusteeRole}.account address to have their tokens minted amount number of tokens to be mintedreturn true if the tokens were successfully minted / | function mint(address account, uint256 amount)
public
onlyTrustee
returns (bool)
{
_mint(account, amount);
return true;
}
| function mint(address account, uint256 amount)
public
onlyTrustee
returns (bool)
{
_mint(account, amount);
return true;
}
| 48,461 |
127 | // Called after validating a `onApprovalReceived`. Override this method tomake your stuffs within your contract. sender The address which called `approveAndCall` function amount The amount of tokens to be spent data Additional data with no specified format / | function _approvalReceived(
address sender,
uint256 amount,
bytes memory data
| function _approvalReceived(
address sender,
uint256 amount,
bytes memory data
| 81,426 |
18 | // Locks maximum supply forever | function lockMaxSupply() external onlyRolesOrOwner(ADMIN_ROLE) {
_maxSupplyLocked = true;
}
| function lockMaxSupply() external onlyRolesOrOwner(ADMIN_ROLE) {
_maxSupplyLocked = true;
}
| 4,980 |
43 | // gets total registred airlines/ |
function getNumberOfRegistredAirlines()
view
external
returns(uint256)
|
function getNumberOfRegistredAirlines()
view
external
returns(uint256)
| 18,745 |
7 | // Check registry code length to facilitate testing in environments without a deployed registry. | if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {
revert OperatorNotAllowed(operator);
}
| if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {
revert OperatorNotAllowed(operator);
}
| 1,931 |
39 | // Cancels a swap. _swapId The Id of the swap. / | function cancelSwap(uint256 _swapId) public whenNotPaused nonReentrant {
require(msg.sender == _swaps[_swapId].initiator);
require(_swaps[_swapId].status);
_swaps[_swapId].status = false;
ERC721(_swaps[_swapId].initiatorNFTAddress).safeTransferFrom(
address(this),
_swaps[_swapId].initiator,
_swaps[_swapId].initiatorNftId
);
emit SwapCancelled(_swapId);
}
| function cancelSwap(uint256 _swapId) public whenNotPaused nonReentrant {
require(msg.sender == _swaps[_swapId].initiator);
require(_swaps[_swapId].status);
_swaps[_swapId].status = false;
ERC721(_swaps[_swapId].initiatorNFTAddress).safeTransferFrom(
address(this),
_swaps[_swapId].initiator,
_swaps[_swapId].initiatorNftId
);
emit SwapCancelled(_swapId);
}
| 28,145 |
34 | // add payout | realisedTokens[sender] = realisedTokens[sender].add(pendingz);
| realisedTokens[sender] = realisedTokens[sender].add(pendingz);
| 6,763 |
46 | // whether to apply hard cap check logic via getMaximumFunds() method | function hasHardCap() internal constant returns (bool) {
return getMaximumFunds() != 0;
}
| function hasHardCap() internal constant returns (bool) {
return getMaximumFunds() != 0;
}
| 42,873 |
36 | // function _transferTokensOnClaim( address _to, uint256 _tokenId, uint256 _quantityBeingClaimed | // ) internal virtual {
// _mint(_to, _tokenId, _quantityBeingClaimed, "");
// }
| // ) internal virtual {
// _mint(_to, _tokenId, _quantityBeingClaimed, "");
// }
| 7,202 |
69 | // Storing stake details | stakingDetails[msg.sender].stakeId.push(
stakingDetails[msg.sender].stakeId.length
);
stakingDetails[msg.sender].isActive.push(true);
stakingDetails[msg.sender].user = msg.sender;
stakingDetails[msg.sender].referrer.push(referrerAddress);
stakingDetails[msg.sender].tokenAddress.push(tokenAddress);
stakingDetails[msg.sender].stakeOption.push(stakeOption);
stakingDetails[msg.sender].startTime.push(block.timestamp);
| stakingDetails[msg.sender].stakeId.push(
stakingDetails[msg.sender].stakeId.length
);
stakingDetails[msg.sender].isActive.push(true);
stakingDetails[msg.sender].user = msg.sender;
stakingDetails[msg.sender].referrer.push(referrerAddress);
stakingDetails[msg.sender].tokenAddress.push(tokenAddress);
stakingDetails[msg.sender].stakeOption.push(stakeOption);
stakingDetails[msg.sender].startTime.push(block.timestamp);
| 32,669 |
323 | // https:docs.synthetix.io/contracts/source/contracts/exchangerwithfeereclamationalternatives | contract ExchangerWithFeeRecAlternatives is MinimalProxyFactory, Exchanger {
bytes32 public constant CONTRACT_NAME = "ExchangerWithFeeRecAlternatives";
using SafeMath for uint;
struct ExchangeVolumeAtPeriod {
uint64 time;
uint192 volume;
}
ExchangeVolumeAtPeriod public lastAtomicVolume;
constructor(address _owner, address _resolver) public MinimalProxyFactory() Exchanger(_owner, _resolver) {}
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_VIRTUALSYNTH_MASTERCOPY = "VirtualSynthMastercopy";
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = Exchanger.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](1);
newAddresses[0] = CONTRACT_VIRTUALSYNTH_MASTERCOPY;
addresses = combineArrays(existingAddresses, newAddresses);
}
/* ========== VIEWS ========== */
function atomicMaxVolumePerBlock() external view returns (uint) {
return getAtomicMaxVolumePerBlock();
}
function feeRateForAtomicExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate)
{
exchangeFeeRate = _feeRateForAtomicExchange(sourceCurrencyKey, destinationCurrencyKey);
}
function getAmountsForAtomicExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
)
{
(amountReceived, fee, exchangeFeeRate, , , ) = _getAmountsForAtomicExchangeMinusFees(
sourceAmount,
sourceCurrencyKey,
destinationCurrencyKey
);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function exchangeAtomically(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external onlySynthetixorSynth returns (uint amountReceived) {
uint fee;
(amountReceived, fee) = _exchangeAtomically(
from,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress
);
_processTradingRewards(fee, destinationAddress);
if (trackingCode != bytes32(0)) {
_emitTrackingEvent(trackingCode, destinationCurrencyKey, amountReceived, fee);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _virtualSynthMastercopy() internal view returns (address) {
return requireAndGetAddress(CONTRACT_VIRTUALSYNTH_MASTERCOPY);
}
function _createVirtualSynth(
IERC20 synth,
address recipient,
uint amount,
bytes32 currencyKey
) internal returns (IVirtualSynth) {
// prevent inverse synths from being allowed due to purgeability
require(currencyKey[0] != 0x69, "Cannot virtualize this synth");
IVirtualSynthInternal vSynth =
IVirtualSynthInternal(_cloneAsMinimalProxy(_virtualSynthMastercopy(), "Could not create new vSynth"));
vSynth.initialize(synth, resolver, recipient, amount, currencyKey);
emit VirtualSynthCreated(address(synth), recipient, address(vSynth), currencyKey, amount);
return IVirtualSynth(address(vSynth));
}
function _exchangeAtomically(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress
) internal returns (uint amountReceived, uint fee) {
_ensureCanExchange(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
// One of src/dest synth must be sUSD (checked below for gas optimization reasons)
require(
!exchangeRates().synthTooVolatileForAtomicExchange(
sourceCurrencyKey == sUSD ? destinationCurrencyKey : sourceCurrencyKey
),
"Src/dest synth too volatile"
);
uint sourceAmountAfterSettlement = _settleAndCalcSourceAmountRemaining(sourceAmount, from, sourceCurrencyKey);
// If, after settlement the user has no balance left (highly unlikely), then return to prevent
// emitting events of 0 and don't revert so as to ensure the settlement queue is emptied
if (sourceAmountAfterSettlement == 0) {
return (0, 0);
}
uint exchangeFeeRate;
uint systemConvertedAmount;
uint systemSourceRate;
uint systemDestinationRate;
// Note: also ensures the given synths are allowed to be atomically exchanged
(
amountReceived, // output amount with fee taken out (denominated in dest currency)
fee, // fee amount (denominated in dest currency)
exchangeFeeRate, // applied fee rate
systemConvertedAmount, // current system value without fees (denominated in dest currency)
systemSourceRate, // current system rate for src currency
systemDestinationRate // current system rate for dest currency
) = _getAmountsForAtomicExchangeMinusFees(sourceAmountAfterSettlement, sourceCurrencyKey, destinationCurrencyKey);
// SIP-65: Decentralized Circuit Breaker (checking current system rates)
if (
_suspendIfRateInvalid(sourceCurrencyKey, systemSourceRate) ||
_suspendIfRateInvalid(destinationCurrencyKey, systemDestinationRate)
) {
return (0, 0);
}
// Sanity check atomic output's value against current system value (checking atomic rates)
require(
!_isDeviationAboveThreshold(systemConvertedAmount, amountReceived.add(fee)),
"Atomic rate deviates too much"
);
// Ensure src/dest synth is sUSD and determine sUSD value of exchange
uint sourceSusdValue;
if (sourceCurrencyKey == sUSD) {
// Use after-settled amount as this is amount converted (not sourceAmount)
sourceSusdValue = sourceAmountAfterSettlement;
} else if (destinationCurrencyKey == sUSD) {
// In this case the systemConvertedAmount would be the fee-free sUSD value of the source synth
sourceSusdValue = systemConvertedAmount;
} else {
revert("Src/dest synth must be sUSD");
}
// Check and update atomic volume limit
_checkAndUpdateAtomicVolume(sourceSusdValue);
// Note: We don't need to check their balance as the _convert() below will do a safe subtraction which requires
// the subtraction to not overflow, which would happen if their balance is not sufficient.
_convert(
sourceCurrencyKey,
from,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress,
false // no vsynths
);
// Remit the fee if required
if (fee > 0) {
// Normalize fee to sUSD
// Note: `fee` is being reused to avoid stack too deep errors.
fee = exchangeRates().effectiveValue(destinationCurrencyKey, fee, sUSD);
// Remit the fee in sUSDs
issuer().synths(sUSD).issue(feePool().FEE_ADDRESS(), fee);
// Tell the fee pool about this
feePool().recordFeePaid(fee);
}
// Note: As of this point, `fee` is denominated in sUSD.
// Note: this update of the debt snapshot will not be accurate because the atomic exchange
// was executed with a different rate than the system rate. To be perfect, issuance data,
// priced in system rates, should have been adjusted on the src and dest synth.
// The debt pool is expected to be deprecated soon, and so we don't bother with being
// perfect here. For now, an inaccuracy will slowly accrue over time with increasing atomic
// exchange volume.
_updateSNXIssuedDebtOnExchange(
[sourceCurrencyKey, destinationCurrencyKey],
[systemSourceRate, systemDestinationRate]
);
// Let the DApps know there was a Synth exchange
ISynthetixInternal(address(synthetix())).emitSynthExchange(
from,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress
);
// Emit separate event to track atomic exchanges
ISynthetixInternal(address(synthetix())).emitAtomicSynthExchange(
from,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress
);
// No need to persist any exchange information, as no settlement is required for atomic exchanges
}
function _checkAndUpdateAtomicVolume(uint sourceSusdValue) internal {
uint currentVolume =
uint(lastAtomicVolume.time) == block.timestamp
? uint(lastAtomicVolume.volume).add(sourceSusdValue)
: sourceSusdValue;
require(currentVolume <= getAtomicMaxVolumePerBlock(), "Surpassed volume limit");
lastAtomicVolume.time = uint64(block.timestamp);
lastAtomicVolume.volume = uint192(currentVolume); // Protected by volume limit check above
}
function _feeRateForAtomicExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
internal
view
returns (uint)
{
// Get the exchange fee rate as per destination currencyKey
uint baseRate = getAtomicExchangeFeeRate(destinationCurrencyKey);
if (baseRate == 0) {
// If no atomic rate was set, fallback to the regular exchange rate
baseRate = getExchangeFeeRate(destinationCurrencyKey);
}
return _calculateFeeRateFromExchangeSynths(baseRate, sourceCurrencyKey, destinationCurrencyKey);
}
function _getAmountsForAtomicExchangeMinusFees(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
internal
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate,
uint systemConvertedAmount,
uint systemSourceRate,
uint systemDestinationRate
)
{
uint destinationAmount;
(destinationAmount, systemConvertedAmount, systemSourceRate, systemDestinationRate) = exchangeRates()
.effectiveAtomicValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
exchangeFeeRate = _feeRateForAtomicExchange(sourceCurrencyKey, destinationCurrencyKey);
amountReceived = _deductFeesFromAmount(destinationAmount, exchangeFeeRate);
fee = destinationAmount.sub(amountReceived);
}
event VirtualSynthCreated(
address indexed synth,
address indexed recipient,
address vSynth,
bytes32 currencyKey,
uint amount
);
} | contract ExchangerWithFeeRecAlternatives is MinimalProxyFactory, Exchanger {
bytes32 public constant CONTRACT_NAME = "ExchangerWithFeeRecAlternatives";
using SafeMath for uint;
struct ExchangeVolumeAtPeriod {
uint64 time;
uint192 volume;
}
ExchangeVolumeAtPeriod public lastAtomicVolume;
constructor(address _owner, address _resolver) public MinimalProxyFactory() Exchanger(_owner, _resolver) {}
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_VIRTUALSYNTH_MASTERCOPY = "VirtualSynthMastercopy";
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = Exchanger.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](1);
newAddresses[0] = CONTRACT_VIRTUALSYNTH_MASTERCOPY;
addresses = combineArrays(existingAddresses, newAddresses);
}
/* ========== VIEWS ========== */
function atomicMaxVolumePerBlock() external view returns (uint) {
return getAtomicMaxVolumePerBlock();
}
function feeRateForAtomicExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint exchangeFeeRate)
{
exchangeFeeRate = _feeRateForAtomicExchange(sourceCurrencyKey, destinationCurrencyKey);
}
function getAmountsForAtomicExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
)
{
(amountReceived, fee, exchangeFeeRate, , , ) = _getAmountsForAtomicExchangeMinusFees(
sourceAmount,
sourceCurrencyKey,
destinationCurrencyKey
);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function exchangeAtomically(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external onlySynthetixorSynth returns (uint amountReceived) {
uint fee;
(amountReceived, fee) = _exchangeAtomically(
from,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress
);
_processTradingRewards(fee, destinationAddress);
if (trackingCode != bytes32(0)) {
_emitTrackingEvent(trackingCode, destinationCurrencyKey, amountReceived, fee);
}
}
/* ========== INTERNAL FUNCTIONS ========== */
function _virtualSynthMastercopy() internal view returns (address) {
return requireAndGetAddress(CONTRACT_VIRTUALSYNTH_MASTERCOPY);
}
function _createVirtualSynth(
IERC20 synth,
address recipient,
uint amount,
bytes32 currencyKey
) internal returns (IVirtualSynth) {
// prevent inverse synths from being allowed due to purgeability
require(currencyKey[0] != 0x69, "Cannot virtualize this synth");
IVirtualSynthInternal vSynth =
IVirtualSynthInternal(_cloneAsMinimalProxy(_virtualSynthMastercopy(), "Could not create new vSynth"));
vSynth.initialize(synth, resolver, recipient, amount, currencyKey);
emit VirtualSynthCreated(address(synth), recipient, address(vSynth), currencyKey, amount);
return IVirtualSynth(address(vSynth));
}
function _exchangeAtomically(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress
) internal returns (uint amountReceived, uint fee) {
_ensureCanExchange(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
// One of src/dest synth must be sUSD (checked below for gas optimization reasons)
require(
!exchangeRates().synthTooVolatileForAtomicExchange(
sourceCurrencyKey == sUSD ? destinationCurrencyKey : sourceCurrencyKey
),
"Src/dest synth too volatile"
);
uint sourceAmountAfterSettlement = _settleAndCalcSourceAmountRemaining(sourceAmount, from, sourceCurrencyKey);
// If, after settlement the user has no balance left (highly unlikely), then return to prevent
// emitting events of 0 and don't revert so as to ensure the settlement queue is emptied
if (sourceAmountAfterSettlement == 0) {
return (0, 0);
}
uint exchangeFeeRate;
uint systemConvertedAmount;
uint systemSourceRate;
uint systemDestinationRate;
// Note: also ensures the given synths are allowed to be atomically exchanged
(
amountReceived, // output amount with fee taken out (denominated in dest currency)
fee, // fee amount (denominated in dest currency)
exchangeFeeRate, // applied fee rate
systemConvertedAmount, // current system value without fees (denominated in dest currency)
systemSourceRate, // current system rate for src currency
systemDestinationRate // current system rate for dest currency
) = _getAmountsForAtomicExchangeMinusFees(sourceAmountAfterSettlement, sourceCurrencyKey, destinationCurrencyKey);
// SIP-65: Decentralized Circuit Breaker (checking current system rates)
if (
_suspendIfRateInvalid(sourceCurrencyKey, systemSourceRate) ||
_suspendIfRateInvalid(destinationCurrencyKey, systemDestinationRate)
) {
return (0, 0);
}
// Sanity check atomic output's value against current system value (checking atomic rates)
require(
!_isDeviationAboveThreshold(systemConvertedAmount, amountReceived.add(fee)),
"Atomic rate deviates too much"
);
// Ensure src/dest synth is sUSD and determine sUSD value of exchange
uint sourceSusdValue;
if (sourceCurrencyKey == sUSD) {
// Use after-settled amount as this is amount converted (not sourceAmount)
sourceSusdValue = sourceAmountAfterSettlement;
} else if (destinationCurrencyKey == sUSD) {
// In this case the systemConvertedAmount would be the fee-free sUSD value of the source synth
sourceSusdValue = systemConvertedAmount;
} else {
revert("Src/dest synth must be sUSD");
}
// Check and update atomic volume limit
_checkAndUpdateAtomicVolume(sourceSusdValue);
// Note: We don't need to check their balance as the _convert() below will do a safe subtraction which requires
// the subtraction to not overflow, which would happen if their balance is not sufficient.
_convert(
sourceCurrencyKey,
from,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress,
false // no vsynths
);
// Remit the fee if required
if (fee > 0) {
// Normalize fee to sUSD
// Note: `fee` is being reused to avoid stack too deep errors.
fee = exchangeRates().effectiveValue(destinationCurrencyKey, fee, sUSD);
// Remit the fee in sUSDs
issuer().synths(sUSD).issue(feePool().FEE_ADDRESS(), fee);
// Tell the fee pool about this
feePool().recordFeePaid(fee);
}
// Note: As of this point, `fee` is denominated in sUSD.
// Note: this update of the debt snapshot will not be accurate because the atomic exchange
// was executed with a different rate than the system rate. To be perfect, issuance data,
// priced in system rates, should have been adjusted on the src and dest synth.
// The debt pool is expected to be deprecated soon, and so we don't bother with being
// perfect here. For now, an inaccuracy will slowly accrue over time with increasing atomic
// exchange volume.
_updateSNXIssuedDebtOnExchange(
[sourceCurrencyKey, destinationCurrencyKey],
[systemSourceRate, systemDestinationRate]
);
// Let the DApps know there was a Synth exchange
ISynthetixInternal(address(synthetix())).emitSynthExchange(
from,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress
);
// Emit separate event to track atomic exchanges
ISynthetixInternal(address(synthetix())).emitAtomicSynthExchange(
from,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress
);
// No need to persist any exchange information, as no settlement is required for atomic exchanges
}
function _checkAndUpdateAtomicVolume(uint sourceSusdValue) internal {
uint currentVolume =
uint(lastAtomicVolume.time) == block.timestamp
? uint(lastAtomicVolume.volume).add(sourceSusdValue)
: sourceSusdValue;
require(currentVolume <= getAtomicMaxVolumePerBlock(), "Surpassed volume limit");
lastAtomicVolume.time = uint64(block.timestamp);
lastAtomicVolume.volume = uint192(currentVolume); // Protected by volume limit check above
}
function _feeRateForAtomicExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
internal
view
returns (uint)
{
// Get the exchange fee rate as per destination currencyKey
uint baseRate = getAtomicExchangeFeeRate(destinationCurrencyKey);
if (baseRate == 0) {
// If no atomic rate was set, fallback to the regular exchange rate
baseRate = getExchangeFeeRate(destinationCurrencyKey);
}
return _calculateFeeRateFromExchangeSynths(baseRate, sourceCurrencyKey, destinationCurrencyKey);
}
function _getAmountsForAtomicExchangeMinusFees(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
internal
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate,
uint systemConvertedAmount,
uint systemSourceRate,
uint systemDestinationRate
)
{
uint destinationAmount;
(destinationAmount, systemConvertedAmount, systemSourceRate, systemDestinationRate) = exchangeRates()
.effectiveAtomicValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
exchangeFeeRate = _feeRateForAtomicExchange(sourceCurrencyKey, destinationCurrencyKey);
amountReceived = _deductFeesFromAmount(destinationAmount, exchangeFeeRate);
fee = destinationAmount.sub(amountReceived);
}
event VirtualSynthCreated(
address indexed synth,
address indexed recipient,
address vSynth,
bytes32 currencyKey,
uint amount
);
} | 38,125 |
176 | // get ERC20 in core ERC20 | else{
uint256 tokenBalance = _token.balanceOf(address(this));
return exchangePortal.getValue(
address(_token),
coreFundAsset,
tokenBalance
);
}
| else{
uint256 tokenBalance = _token.balanceOf(address(this));
return exchangePortal.getValue(
address(_token),
coreFundAsset,
tokenBalance
);
}
| 39,357 |
10 | // Transfer ETH from contract's balance after token swap | function transferETH (address payable _recipient, uint _amount) external payable OnlyManager{
_recipient.transfer(_amount);
}
| function transferETH (address payable _recipient, uint _amount) external payable OnlyManager{
_recipient.transfer(_amount);
}
| 31,460 |
14 | // Verificamos si el votante ya ha votado | for (uint256 i = 0; i < votantes.length; i++) {
require(votantes[i] != hash_Votante, "Ya has votado previamente");
}
| for (uint256 i = 0; i < votantes.length; i++) {
require(votantes[i] != hash_Votante, "Ya has votado previamente");
}
| 30,835 |
5 | // Reverts if called in incorrect stage. _stage The allowed stage for the given function. / | modifier atStage(Stages _stage) {
require(
currentStakingRound.stage == _stage,
"Function cannot be called at this time!"
);
_;
}
| modifier atStage(Stages _stage) {
require(
currentStakingRound.stage == _stage,
"Function cannot be called at this time!"
);
_;
}
| 13,236 |
2 | // confirms ownership / | modifier isOwner(address _owner, uint index) {
require(registry[index].owner == _owner);
_;
}
| modifier isOwner(address _owner, uint index) {
require(registry[index].owner == _owner);
_;
}
| 41,391 |
83 | // get the bonus based on the return percentage for a particular locking term. -------------------------------------------------------------------------------param _amount --> the amount to calculate bonus from.param _returnPercentage --> the returnPercentage of the term.----------------------------------------------------------returns the bonus amount. / | function _calculateBonus(uint _amount, uint _returnPercentage) internal pure returns(uint) {
return ((_amount.mul(_returnPercentage)).div(100000)) / 2; // 1% = 1000
}
| function _calculateBonus(uint _amount, uint _returnPercentage) internal pure returns(uint) {
return ((_amount.mul(_returnPercentage)).div(100000)) / 2; // 1% = 1000
}
| 75,700 |
89 | // win on first dozen | if ( result!=0 &&
( (result<13 && gambles[gambleIndex[msg.sender]].input==0)
||
(result>12 && result<25 && gambles[gambleIndex[msg.sender]].input==1)
||
(result>24 && gambles[gambleIndex[msg.sender]].input==2) ) )
{
win=true;
}
| if ( result!=0 &&
( (result<13 && gambles[gambleIndex[msg.sender]].input==0)
||
(result>12 && result<25 && gambles[gambleIndex[msg.sender]].input==1)
||
(result>24 && gambles[gambleIndex[msg.sender]].input==2) ) )
{
win=true;
}
| 44,255 |
140 | // subscription must be enabled | if (!storedSubData.isEnabled) {
revert SubNotEnabled(_subId);
}
| if (!storedSubData.isEnabled) {
revert SubNotEnabled(_subId);
}
| 29,140 |
20 | // An external view method that simply returns the length of the registry array. This function is necessary for the UI to iterate through every registration in the registry array. | function getRegistrationCount()
external
view
returns (uint)
| function getRegistrationCount()
external
view
returns (uint)
| 930 |
6 | // now, length is log256(value) + 1 |
return toHexString(value, length);
|
return toHexString(value, length);
| 32,368 |
23 | // Updates fixedTokenGrowthInsideLast and variableTokenGrowthInsideLast to the current values/self position info struct represeting a liquidity provider/fixedTokenGrowthInsideX128 fixed token growth per unit of liquidity as of now/variableTokenGrowthInsideX128 variable token growth per unit of liquidity as of now | function updateFixedAndVariableTokenGrowthInside(
Info storage self,
int256 fixedTokenGrowthInsideX128,
int256 variableTokenGrowthInsideX128
| function updateFixedAndVariableTokenGrowthInside(
Info storage self,
int256 fixedTokenGrowthInsideX128,
int256 variableTokenGrowthInsideX128
| 3,441 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.