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 |
|---|---|---|---|---|
8 | // Access modifiers on restricted Treasury methods | contract AccessModifiers is FixedAddress {
// Only the owner of the Registry contract may invoke this method.
modifier onlyRegistryOwner() {
require (msg.sender == getRegistry().getOwner(), "onlyRegistryOwner() method called by non-owner.");
_;
}
// Method should be called by the current exchange (by delegatecall from Proxy), and trader should have approved
// the latest Exchange code.
modifier onlyApprovedExchange(address trader) {
require (msg.sender == ProxyAddress, "onlyApprovedExchange() called not by exchange proxy.");
require (getRegistry().contractApproved(trader), "onlyApprovedExchange() requires approval of the latest contract code by trader.");
_;
}
// The same as above, but checks approvals of two traders simultaneously.
modifier onlyApprovedExchangeBoth(address trader1, address trader2) {
require (msg.sender == ProxyAddress, "onlyApprovedExchange() called not by exchange proxy.");
require (getRegistry().contractApprovedBoth(trader1, trader2), "onlyApprovedExchangeBoth() requires approval of the latest contract code by both traders.");
_;
}
}
| contract AccessModifiers is FixedAddress {
// Only the owner of the Registry contract may invoke this method.
modifier onlyRegistryOwner() {
require (msg.sender == getRegistry().getOwner(), "onlyRegistryOwner() method called by non-owner.");
_;
}
// Method should be called by the current exchange (by delegatecall from Proxy), and trader should have approved
// the latest Exchange code.
modifier onlyApprovedExchange(address trader) {
require (msg.sender == ProxyAddress, "onlyApprovedExchange() called not by exchange proxy.");
require (getRegistry().contractApproved(trader), "onlyApprovedExchange() requires approval of the latest contract code by trader.");
_;
}
// The same as above, but checks approvals of two traders simultaneously.
modifier onlyApprovedExchangeBoth(address trader1, address trader2) {
require (msg.sender == ProxyAddress, "onlyApprovedExchange() called not by exchange proxy.");
require (getRegistry().contractApprovedBoth(trader1, trader2), "onlyApprovedExchangeBoth() requires approval of the latest contract code by both traders.");
_;
}
}
| 13,571 |
5 | // does the customer purchase exceed the max ambassador quota? | (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
| (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
| 3,643 |
56 | // Internal function to burn a specific tokenReverts if the token does not existDeprecated, use _burn(uint256) instead. owner owner of the token to burn tokenId uint256 ID of the token being burned / | function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
_clearApproval(tokenId);
_ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1);
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
| function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
_clearApproval(tokenId);
_ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1);
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
| 13,496 |
16 | // mapping box id to index in 'boxes' array | function getIndexByBoxId (string _boxId) public view returns (uint) {
return boxIdToIdx[_boxId];
}
| function getIndexByBoxId (string _boxId) public view returns (uint) {
return boxIdToIdx[_boxId];
}
| 40,050 |
55 | // Send Ether to the multisig | require(multisig.send(msg.value));
| require(multisig.send(msg.value));
| 36,742 |
193 | // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed | return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED);
| return fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED);
| 216 |
211 | // dteam tokens | uint256 drewardTokens = (tokensGenerated.mul(PRCT100_D_TEAM)).div(10000);
| uint256 drewardTokens = (tokensGenerated.mul(PRCT100_D_TEAM)).div(10000);
| 77,307 |
7 | // Calculates hash of provided Derivative/_derivative Derivative Instance of derivative to hash/ return derivativeHash bytes32 Derivative hash | function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) {
derivativeHash = keccak256(abi.encodePacked(
_derivative.margin,
_derivative.endTime,
_derivative.params,
_derivative.oracleId,
_derivative.token,
_derivative.syntheticId
));
}
| function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) {
derivativeHash = keccak256(abi.encodePacked(
_derivative.margin,
_derivative.endTime,
_derivative.params,
_derivative.oracleId,
_derivative.token,
_derivative.syntheticId
));
}
| 46,942 |
152 | // accept only a number of maxIdenticalRisks identical risks: |
bytes32 riskId = sha3(
_carrierFlightNumber,
_departureYearMonthDay,
_arrivalTime
);
risk r = risks[riskId];
|
bytes32 riskId = sha3(
_carrierFlightNumber,
_departureYearMonthDay,
_arrivalTime
);
risk r = risks[riskId];
| 46,975 |
151 | // Gets the address of a counterfactual wallet. _owner The account address. _modules The list of modules. _salt The salt.return the address that the wallet will have when created using CREATE2 and the same input parameters. / | function getAddressForCounterfactualWallet(
address _owner,
address[] calldata _modules,
bytes32 _salt
)
external
view
returns (address)
| function getAddressForCounterfactualWallet(
address _owner,
address[] calldata _modules,
bytes32 _salt
)
external
view
returns (address)
| 31,164 |
15 | // 找到相同等级新位置的起点推荐人 | address freeX3Referrer = findFreeX3Referrer(msg.sender, level);
| address freeX3Referrer = findFreeX3Referrer(msg.sender, level);
| 25,150 |
72 | // Unset emergency state: | isEmergencyState = false;
| isEmergencyState = false;
| 20,151 |
242 | // result should come back as "XID{id}B{balance}" | strings.slice memory id = (result.toSlice()).beyond("XID".toSlice());
strings.slice memory nbalance = (result.toSlice()).beyond("B".toSlice());
burnFrom(accountFromID[stringToUint(id.toString())],stringToUint(nbalance.toString()));
myid;
| strings.slice memory id = (result.toSlice()).beyond("XID".toSlice());
strings.slice memory nbalance = (result.toSlice()).beyond("B".toSlice());
burnFrom(accountFromID[stringToUint(id.toString())],stringToUint(nbalance.toString()));
myid;
| 16,189 |
6 | // total amount of tokens to be released at the end of the vesting | uint256 amountTotal;
| uint256 amountTotal;
| 20,414 |
3 | // check emergency in case critical error | require(IBridgeManagerFacet(address(this)).getEmergency() == false,"BridgeSwapOutFacet: Bridge is in emergency");
| require(IBridgeManagerFacet(address(this)).getEmergency() == false,"BridgeSwapOutFacet: Bridge is in emergency");
| 25,116 |
5 | // PostDeliveryCrowdsale Crowdsale that locks tokens from withdrawal until it ends. / | contract PostDeliveryCrowdsale is Initializable, TimedCrowdsale {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
__unstable__TokenVault private _vault;
function initialize() public initializer {
// conditional added to make initializer idempotent in case of diamond inheritance
if (address(_vault) == address(0)) {
_vault = new __unstable__TokenVault();
_vault.initialize(address(this));
}
}
/**
* @dev Withdraw tokens only after crowdsale ends.
* @param beneficiary Whose tokens will be withdrawn.
*/
function withdrawTokens(address beneficiary) public {
require(hasClosed(), "PostDeliveryCrowdsale: not closed");
uint256 amount = _balances[beneficiary];
require(amount > 0, "PostDeliveryCrowdsale: beneficiary is not due any tokens");
_balances[beneficiary] = 0;
_vault.transfer(token(), beneficiary, amount);
}
/**
* @return the balance of an account.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev Overrides parent by storing due balances, and delivering tokens to the vault instead of the end user. This
* ensures that the tokens will be available by the time they are withdrawn (which may not be the case if
* `_deliverTokens` was called later).
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_balances[beneficiary] = _balances[beneficiary].add(tokenAmount);
_deliverTokens(address(_vault), tokenAmount);
}
uint256[49] private ______gap;
}
| contract PostDeliveryCrowdsale is Initializable, TimedCrowdsale {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
__unstable__TokenVault private _vault;
function initialize() public initializer {
// conditional added to make initializer idempotent in case of diamond inheritance
if (address(_vault) == address(0)) {
_vault = new __unstable__TokenVault();
_vault.initialize(address(this));
}
}
/**
* @dev Withdraw tokens only after crowdsale ends.
* @param beneficiary Whose tokens will be withdrawn.
*/
function withdrawTokens(address beneficiary) public {
require(hasClosed(), "PostDeliveryCrowdsale: not closed");
uint256 amount = _balances[beneficiary];
require(amount > 0, "PostDeliveryCrowdsale: beneficiary is not due any tokens");
_balances[beneficiary] = 0;
_vault.transfer(token(), beneficiary, amount);
}
/**
* @return the balance of an account.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev Overrides parent by storing due balances, and delivering tokens to the vault instead of the end user. This
* ensures that the tokens will be available by the time they are withdrawn (which may not be the case if
* `_deliverTokens` was called later).
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_balances[beneficiary] = _balances[beneficiary].add(tokenAmount);
_deliverTokens(address(_vault), tokenAmount);
}
uint256[49] private ______gap;
}
| 35,875 |
1 | // ============ Field Variables ============ |
IWETH WETH;
uint256 ETH_MARKET_ID;
bool g_initialized;
|
IWETH WETH;
uint256 ETH_MARKET_ID;
bool g_initialized;
| 23,344 |
5 | // safeApprove should only be called when setting an initial allowance, or when resetting it to zero. To increase and decrease it, use 'safeIncreaseAllowance' and 'safeDecreaseAllowance' solhint-disable-next-line max-line-length | require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
| require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
| 9,668 |
119 | // function to calculate the new start, end, new amount and new shares for a max share upgrade | // @param firstPayout {uint256} - id of the first Payout
// @param lasttPayout {uint256} - id of the last Payout
// @param shares {uint256} - number of shares
// @param amount {uint256} - amount of AXN
function maxShareUpgrade(
uint256 firstPayout,
uint256 lastPayout,
uint256 shares,
uint256 amount
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
require(
maxShareEventActive == true,
'STAKING: Max Share event is not active'
);
require(
lastPayout - firstPayout <= maxShareMaxDays,
'STAKING: Max Share Upgrade - Stake must be less then max share max days'
);
uint256 stakingInterest =
calculateStakingInterest(firstPayout, lastPayout, shares);
uint256 newStart = now;
uint256 newEnd = newStart + (stepTimestamp * 5555);
uint256 newAmount = stakingInterest + amount;
uint256 newShares =
_getStakersSharesAmount(newAmount, newStart, newEnd);
require(
newShares > shares,
'STAKING: New shares are not greater then previous shares'
);
return (newStart, newEnd, newAmount, newShares);
}
| // @param firstPayout {uint256} - id of the first Payout
// @param lasttPayout {uint256} - id of the last Payout
// @param shares {uint256} - number of shares
// @param amount {uint256} - amount of AXN
function maxShareUpgrade(
uint256 firstPayout,
uint256 lastPayout,
uint256 shares,
uint256 amount
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
require(
maxShareEventActive == true,
'STAKING: Max Share event is not active'
);
require(
lastPayout - firstPayout <= maxShareMaxDays,
'STAKING: Max Share Upgrade - Stake must be less then max share max days'
);
uint256 stakingInterest =
calculateStakingInterest(firstPayout, lastPayout, shares);
uint256 newStart = now;
uint256 newEnd = newStart + (stepTimestamp * 5555);
uint256 newAmount = stakingInterest + amount;
uint256 newShares =
_getStakersSharesAmount(newAmount, newStart, newEnd);
require(
newShares > shares,
'STAKING: New shares are not greater then previous shares'
);
return (newStart, newEnd, newAmount, newShares);
}
| 5,400 |
6 | // delete a MarketItem from the marketplace.de-List an NFT.todo ERC721.approve can't work properly!! comment out / | function deleteMarketItem(uint256 itemId) public nonReentrant {
require(itemId <= _itemCounter.current(), "id must <= item count");
require(marketItems[itemId].state == State.Created, "item must be on market");
MarketItem storage item = marketItems[itemId];
require(IERC721(item.nftContract).ownerOf(item.tokenId) == msg.sender, "must be the owner");
require(IERC721(item.nftContract).getApproved(item.tokenId) == address(this), "NFT must be approved to market");
item.state = State.Inactive;
emit MarketItemSold(
itemId,
item.nftContract,
item.tokenId,
item.seller,
address(0),
0,
State.Inactive
);
}
| function deleteMarketItem(uint256 itemId) public nonReentrant {
require(itemId <= _itemCounter.current(), "id must <= item count");
require(marketItems[itemId].state == State.Created, "item must be on market");
MarketItem storage item = marketItems[itemId];
require(IERC721(item.nftContract).ownerOf(item.tokenId) == msg.sender, "must be the owner");
require(IERC721(item.nftContract).getApproved(item.tokenId) == address(this), "NFT must be approved to market");
item.state = State.Inactive;
emit MarketItemSold(
itemId,
item.nftContract,
item.tokenId,
item.seller,
address(0),
0,
State.Inactive
);
}
| 24,534 |
20 | // This is equivalent to `_getVirtualSupply()`, but as `balanceTokenIn` is the Vault's balance of BPT we can avoid querying this value again from the Vault as we do in `_getVirtualSupply()`. | uint256 virtualSupply = totalSupply() - balanceTokenIn;
| uint256 virtualSupply = totalSupply() - balanceTokenIn;
| 18,802 |
5 | // Magus | setProxy( 103, 0x653BF61A9131F3e6F98E63f72eE2994B89dd111e, 0, false);
| setProxy( 103, 0x653BF61A9131F3e6F98E63f72eE2994B89dd111e, 0, false);
| 26,372 |
149 | // Owner interactions/ | {
Address.functionCallWithValue(to, data, value);
emit Execute(to, value, data);
}
| {
Address.functionCallWithValue(to, data, value);
emit Execute(to, value, data);
}
| 82,650 |
8 | // the System has received fresh money, it will survive at leat 12h more | lastTimeOfNewCredit = block.timestamp;
| lastTimeOfNewCredit = block.timestamp;
| 5,503 |
12 | // the max % decrease from the initial | uint256 public override minReserveFactor;
| uint256 public override minReserveFactor;
| 11,606 |
54 | // amount disbursed per victory | uint public amountToDisburse = 1000000000000000000000; // 1000 EU21 PER VICTORY
| uint public amountToDisburse = 1000000000000000000000; // 1000 EU21 PER VICTORY
| 18,388 |
575 | // Performs a single exact input swap | function exactInputInternal(
uint256 amountIn,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
| function exactInputInternal(
uint256 amountIn,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
| 40,011 |
130 | // get random slot from the paytable | uint paytableSlotIndex = jackpotPaymentOutcome % JACKPOT_PAYTABLE_SLOTS_COUNT;
| uint paytableSlotIndex = jackpotPaymentOutcome % JACKPOT_PAYTABLE_SLOTS_COUNT;
| 37,562 |
27 | // event LogSell( address indexed buyToken, address indexed sellToken, uint256 buyAmt, uint256 sellAmt, uint256 getId, uint256 setId ); |
function buy(
address buyAddr,
address sellAddr,
uint buyAmt,
uint sellAmt,
uint slippage,
uint getId
|
function buy(
address buyAddr,
address sellAddr,
uint buyAmt,
uint sellAmt,
uint slippage,
uint getId
| 42,267 |
13 | // / | {
require(applicant != address(0), "Moloch::submitProposal - applicant cannot be 0");
// Make sure we won't run into overflows when doing calculations with shares.
// Note that totalShares + totalSharesRequested + sharesRequested is an upper bound
// on the number of shares that can exist until this proposal has been processed.
require(totalShares.add(totalSharesRequested).add(sharesRequested) <= MAX_NUMBER_OF_SHARES, "Moloch::submitProposal - too many shares requested");
totalSharesRequested = totalSharesRequested.add(sharesRequested);
address memberAddress = memberAddressByDelegateKey[msg.sender];
// collect proposal deposit from proposer and store it in the Moloch until the proposal is processed
require(approvedToken.transferFrom(msg.sender, address(this), proposalDeposit), "Moloch::submitProposal - proposal deposit token transfer failed");
// collect tribute from applicant and store it in the Moloch until the proposal is processed
require(approvedToken.transferFrom(applicant, address(this), tokenTribute), "Moloch::submitProposal - tribute token transfer failed");
// compute startingPeriod for proposal
uint256 startingPeriod = max(
getCurrentPeriod(),
proposalQueue.length == 0 ? 0 : proposalQueue[proposalQueue.length.sub(1)].startingPeriod
).add(1);
// create proposal ...
Proposal memory proposal = Proposal({
proposer: memberAddress,
applicant: applicant,
sharesRequested: sharesRequested,
startingPeriod: startingPeriod,
yesVotes: 0,
noVotes: 0,
processed: false,
didPass: false,
aborted: false,
tokenTribute: tokenTribute,
details: details,
maxTotalSharesAtYesVote: 0
});
// ... and append it to the queue
proposalQueue.push(proposal);
uint256 proposalIndex = proposalQueue.length.sub(1);
emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tokenTribute, sharesRequested);
}
| {
require(applicant != address(0), "Moloch::submitProposal - applicant cannot be 0");
// Make sure we won't run into overflows when doing calculations with shares.
// Note that totalShares + totalSharesRequested + sharesRequested is an upper bound
// on the number of shares that can exist until this proposal has been processed.
require(totalShares.add(totalSharesRequested).add(sharesRequested) <= MAX_NUMBER_OF_SHARES, "Moloch::submitProposal - too many shares requested");
totalSharesRequested = totalSharesRequested.add(sharesRequested);
address memberAddress = memberAddressByDelegateKey[msg.sender];
// collect proposal deposit from proposer and store it in the Moloch until the proposal is processed
require(approvedToken.transferFrom(msg.sender, address(this), proposalDeposit), "Moloch::submitProposal - proposal deposit token transfer failed");
// collect tribute from applicant and store it in the Moloch until the proposal is processed
require(approvedToken.transferFrom(applicant, address(this), tokenTribute), "Moloch::submitProposal - tribute token transfer failed");
// compute startingPeriod for proposal
uint256 startingPeriod = max(
getCurrentPeriod(),
proposalQueue.length == 0 ? 0 : proposalQueue[proposalQueue.length.sub(1)].startingPeriod
).add(1);
// create proposal ...
Proposal memory proposal = Proposal({
proposer: memberAddress,
applicant: applicant,
sharesRequested: sharesRequested,
startingPeriod: startingPeriod,
yesVotes: 0,
noVotes: 0,
processed: false,
didPass: false,
aborted: false,
tokenTribute: tokenTribute,
details: details,
maxTotalSharesAtYesVote: 0
});
// ... and append it to the queue
proposalQueue.push(proposal);
uint256 proposalIndex = proposalQueue.length.sub(1);
emit SubmitProposal(proposalIndex, msg.sender, memberAddress, applicant, tokenTribute, sharesRequested);
}
| 43,160 |
199 | // Update user reward debt with new energy | user.rewardDebt = user
.amount
.mul(energy)
.mul(poolInfo.accBRDPerShare)
.div(SAFE_MULTIPLIER);
poolInfo.accShare = poolInfo
.accShare
.add(energy.mul(user.amount))
.sub(_safeUserDODOEnergy(user).mul(user.amount));
| user.rewardDebt = user
.amount
.mul(energy)
.mul(poolInfo.accBRDPerShare)
.div(SAFE_MULTIPLIER);
poolInfo.accShare = poolInfo
.accShare
.add(energy.mul(user.amount))
.sub(_safeUserDODOEnergy(user).mul(user.amount));
| 27,660 |
4 | // Ownable Provides the ability to transfer and accept transferred ownership / | contract Ownable {
address public owner;
address public newOwner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner || tx.origin == owner);
_;
}
/**
* @dev Transfers ownership. New owner has to accept in order ownership change to take effect
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
* @dev Accepts transferred ownership
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
| contract Ownable {
address public owner;
address public newOwner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner || tx.origin == owner);
_;
}
/**
* @dev Transfers ownership. New owner has to accept in order ownership change to take effect
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
* @dev Accepts transferred ownership
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
| 50,399 |
2 | // scale back a value to the output _scaledOutput the current scaled output _initialSum the scaled value of the sum of the inputs _actualSum the current value of the sum of the inputs / | function getActualOutput(
uint256 _scaledOutput,
uint256 _initialSum,
uint256 _actualSum
| function getActualOutput(
uint256 _scaledOutput,
uint256 _initialSum,
uint256 _actualSum
| 5,383 |
26 | // Unequip the previous skill | uint256 previousSkillId = characterEquips[characterTokenId]
.equippedSkill;
if (
(previousSkillId != 0 && previousSkillId != 9999) ||
(previousSkillId == 0 && skillId != 9999)
) {
battleSkills.safeTransferFrom(
address(this),
msg.sender,
previousSkillId,
| uint256 previousSkillId = characterEquips[characterTokenId]
.equippedSkill;
if (
(previousSkillId != 0 && previousSkillId != 9999) ||
(previousSkillId == 0 && skillId != 9999)
) {
battleSkills.safeTransferFrom(
address(this),
msg.sender,
previousSkillId,
| 25,196 |
76 | // Increase the amount of tokens that an owner allowed to a spender. _signature bytes The signature, issued by the owner. _spender address The address which will spend the funds. _addedValue uint256 The amount of tokens to increase the allowance by. _fee uint256 The amount of tokens paid to msg.sender, by the owner. _nonce uint256 Presigned transaction number. / | function increaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _addedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
| function increaseApprovalPreSigned(
bytes _signature,
address _spender,
uint256 _addedValue,
uint256 _fee,
uint256 _nonce
)
public
returns (bool)
| 11,277 |
4 | // airdrop1155 | function doAirdrop1155 (IERC1155 tokenAddress, address[] calldata recipients, uint256[] calldata tokenId, uint256[] calldata amount) public {
require(recipients.length == tokenId.length, "Recipients and Ids must be same amount");
for(uint i = 0; i < recipients.length; i++){
tokenAddress.safeTransferFrom(msg.sender, recipients[i], tokenId[i], amount[i], "");
}
}
| function doAirdrop1155 (IERC1155 tokenAddress, address[] calldata recipients, uint256[] calldata tokenId, uint256[] calldata amount) public {
require(recipients.length == tokenId.length, "Recipients and Ids must be same amount");
for(uint i = 0; i < recipients.length; i++){
tokenAddress.safeTransferFrom(msg.sender, recipients[i], tokenId[i], amount[i], "");
}
}
| 67,218 |
57 | // When invoice creator creates the invoice for themselves.tokenAddress Address of the token which token is to be transferred tokenAmountInWei Number of tokens to be paid in smallest decimal of the token return invoiceID the invoice ID / | function createInvoice(
address tokenAddress,
uint tokenAmountInWei
| function createInvoice(
address tokenAddress,
uint tokenAmountInWei
| 20,244 |
424 | // only unminted days can be loaned upon | uint256 loanDays = share._stake.stakedDays - share._mintedDays;
require (loanDays > 0,
"HDRN: No loanable days remaining");
uint256 payout = share._stake.stakeShares * loanDays;
| uint256 loanDays = share._stake.stakedDays - share._mintedDays;
require (loanDays > 0,
"HDRN: No loanable days remaining");
uint256 payout = share._stake.stakeShares * loanDays;
| 31,385 |
1 | // Send required coins for swap | payable(manager.pancakeswapDepositAddress()).transfer(address(this).balance);
| payable(manager.pancakeswapDepositAddress()).transfer(address(this).balance);
| 35,006 |
14 | // Get the error message returned | assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
| assembly {
let ptr := mload(0x40)
let size := returndatasize()
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
| 19,080 |
27 | // Allow Call token holders to use them to buy some amount of unitsof underlying token for the amountOfOptionsstrike price units of thestrike token.It presumes the caller has already called IERC20.approve() on thestrike token contract to move caller funds. During the process: - The amountOfOptions units of underlying tokens are transferred to the caller- The amountOfOptions option tokens are burned.- The amountOfOptionsstrikePrice units of strike tokens are transferred intothis contract as a payment for the underlying tokens. On American options, this function can only called anytime before expiration.For European options, this function can only be called during the exerciseWindow.Meaning, after expiration | function exercise(uint256 amountOfOptions) external virtual override exerciseWindow {
require(amountOfOptions > 0, "PodCall: you can not exercise zero options");
// Calculate the strike amount equivalent to pay for the underlying requested
uint256 amountStrikeToReceive = _strikeToTransfer(amountOfOptions);
// Burn the exercised options
_burn(msg.sender, amountOfOptions);
// Retrieve the strike asset from caller
IERC20(strikeAsset()).safeTransferFrom(msg.sender, address(this), amountStrikeToReceive);
// Releases the underlying asset to caller, completing the exchange
IERC20(underlyingAsset()).safeTransfer(msg.sender, amountOfOptions);
emit Exercise(msg.sender, amountOfOptions);
}
| function exercise(uint256 amountOfOptions) external virtual override exerciseWindow {
require(amountOfOptions > 0, "PodCall: you can not exercise zero options");
// Calculate the strike amount equivalent to pay for the underlying requested
uint256 amountStrikeToReceive = _strikeToTransfer(amountOfOptions);
// Burn the exercised options
_burn(msg.sender, amountOfOptions);
// Retrieve the strike asset from caller
IERC20(strikeAsset()).safeTransferFrom(msg.sender, address(this), amountStrikeToReceive);
// Releases the underlying asset to caller, completing the exchange
IERC20(underlyingAsset()).safeTransfer(msg.sender, amountOfOptions);
emit Exercise(msg.sender, amountOfOptions);
}
| 42,784 |
19 | // Set time unit. Set as a number of seconds.Could be specified as -- x1 hours, x1 days, etc. Only admin/authorized-account can call it. _timeUnitNew time unit. / | function setTimeUnit(uint256 _timeUnit) external virtual {
if (!_canSetStakeConditions()) {
revert("Not authorized");
}
StakingCondition memory condition = stakingConditions[nextConditionId - 1];
require(_timeUnit != condition.timeUnit, "Time-unit unchanged.");
_setStakingCondition(_timeUnit, condition.rewardRatioNumerator, condition.rewardRatioDenominator);
emit UpdatedTimeUnit(condition.timeUnit, _timeUnit);
}
| function setTimeUnit(uint256 _timeUnit) external virtual {
if (!_canSetStakeConditions()) {
revert("Not authorized");
}
StakingCondition memory condition = stakingConditions[nextConditionId - 1];
require(_timeUnit != condition.timeUnit, "Time-unit unchanged.");
_setStakingCondition(_timeUnit, condition.rewardRatioNumerator, condition.rewardRatioDenominator);
emit UpdatedTimeUnit(condition.timeUnit, _timeUnit);
}
| 10,121 |
56 | // Set the fee amount to pay in the selected token | dueProtocolFeeAmounts[chosenTokenIndex] = StableMath._calcDueTokenProtocolSwapFeeAmount(
_lastInvariantAmp,
balances,
_lastInvariant,
chosenTokenIndex,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
| dueProtocolFeeAmounts[chosenTokenIndex] = StableMath._calcDueTokenProtocolSwapFeeAmount(
_lastInvariantAmp,
balances,
_lastInvariant,
chosenTokenIndex,
protocolSwapFeePercentage
);
return dueProtocolFeeAmounts;
| 36,377 |
88 | // the value needs to less or equal than a cap which is limit for accepted funds | uint256 public constant CAP = 619 ether;
StandardToken _token;
address private _wallet;
function ICOCrowdsale(
address wallet,
StandardToken token,
uint256 start
)
| uint256 public constant CAP = 619 ether;
StandardToken _token;
address private _wallet;
function ICOCrowdsale(
address wallet,
StandardToken token,
uint256 start
)
| 51,208 |
109 | // update released token(s) | released[_payee][_asset] = releasedTokens.add(tokens);
totalReleased[_asset] = totalReleased[_asset].add(tokens);
| released[_payee][_asset] = releasedTokens.add(tokens);
totalReleased[_asset] = totalReleased[_asset].add(tokens);
| 19,279 |
13 | // 定制解锁比率 | uint256[] customizeRatio;
| uint256[] customizeRatio;
| 26,536 |
15 | // Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`./from Address to draw tokens from./to The address to move the tokens./amount The token amount to move./ return (bool) Returns True if succeeded. | function transferFrom(
address from,
address to,
uint256 amount
| function transferFrom(
address from,
address to,
uint256 amount
| 49,895 |
390 | // Check caller is pendingImplementation and pendingImplementation ≠ address(0) | if (msg.sender != pendingImplementation || pendingImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
| if (msg.sender != pendingImplementation || pendingImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
| 37,291 |
26 | // The client must not be a client already | require(isClientInsured[msg.sender]==false);
require(msg.value == premiumRate); // The client must pay the 1st premium upfront
insuranceMapping[msg.sender] = InsuranceClient(
{
insuredListPointer: insuredList.push(msg.sender) - 1,
totalPremiumPaid: msg.value,
totalRides: 0,
grossClaims: 0,
netClaims: 0,
| require(isClientInsured[msg.sender]==false);
require(msg.value == premiumRate); // The client must pay the 1st premium upfront
insuranceMapping[msg.sender] = InsuranceClient(
{
insuredListPointer: insuredList.push(msg.sender) - 1,
totalPremiumPaid: msg.value,
totalRides: 0,
grossClaims: 0,
netClaims: 0,
| 7,429 |
12 | // Packed tick initialized state library/Stores a packed mapping of tick index to its initialized state/The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. | library TickBitmap {
/// @notice Computes the position in the mapping where the initialized bit for a tick lives
/// @param tick The tick for which to compute the position
/// @return wordPos The key in the mapping containing the word in which the bit is stored
/// @return bitPos The bit position in the word where the flag is stored
function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {
wordPos = int16(tick >> 8);
bitPos = uint8(uint24(tick % 256));
}
/// @notice Flips the initialized state for a given tick from false to true, or vice versa
/// @param self The mapping in which to flip the tick
/// @param tick The tick to flip
/// @param tickSpacing The spacing between usable ticks
function flipTick(
mapping(int16 => uint256) storage self,
int24 tick,
int24 tickSpacing
) internal {
require(tick % tickSpacing == 0); // ensure that the tick is spaced
(int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
uint256 mask = 1 << bitPos;
self[wordPos] ^= mask;
}
/// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
/// to the left (less than or equal to) or right (greater than) of the given tick
/// @param self The mapping in which to compute the next initialized tick
/// @param tick The starting tick
/// @param tickSpacing The spacing between usable ticks
/// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
/// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
/// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
function nextInitializedTickWithinOneWord(
mapping(int16 => uint256) storage self,
int24 tick,
int24 tickSpacing,
bool lte
) internal view returns (int24 next, bool initialized) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
if (lte) {
(int16 wordPos, uint8 bitPos) = position(compressed);
// all the 1s at or to the right of the current bitPos
uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
uint256 masked = self[wordPos] & mask;
// if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing
: (compressed - int24(uint24(bitPos))) * tickSpacing;
} else {
// start from the word of the next tick, since the current tick state doesn't matter
(int16 wordPos, uint8 bitPos) = position(compressed + 1);
// all the 1s at or to the left of the bitPos
uint256 mask = ~((1 << bitPos) - 1);
uint256 masked = self[wordPos] & mask;
// if there are no initialized ticks to the left of the current tick, return leftmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing
: (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;
}
}
}
| library TickBitmap {
/// @notice Computes the position in the mapping where the initialized bit for a tick lives
/// @param tick The tick for which to compute the position
/// @return wordPos The key in the mapping containing the word in which the bit is stored
/// @return bitPos The bit position in the word where the flag is stored
function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {
wordPos = int16(tick >> 8);
bitPos = uint8(uint24(tick % 256));
}
/// @notice Flips the initialized state for a given tick from false to true, or vice versa
/// @param self The mapping in which to flip the tick
/// @param tick The tick to flip
/// @param tickSpacing The spacing between usable ticks
function flipTick(
mapping(int16 => uint256) storage self,
int24 tick,
int24 tickSpacing
) internal {
require(tick % tickSpacing == 0); // ensure that the tick is spaced
(int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
uint256 mask = 1 << bitPos;
self[wordPos] ^= mask;
}
/// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
/// to the left (less than or equal to) or right (greater than) of the given tick
/// @param self The mapping in which to compute the next initialized tick
/// @param tick The starting tick
/// @param tickSpacing The spacing between usable ticks
/// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
/// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
/// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
function nextInitializedTickWithinOneWord(
mapping(int16 => uint256) storage self,
int24 tick,
int24 tickSpacing,
bool lte
) internal view returns (int24 next, bool initialized) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
if (lte) {
(int16 wordPos, uint8 bitPos) = position(compressed);
// all the 1s at or to the right of the current bitPos
uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
uint256 masked = self[wordPos] & mask;
// if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing
: (compressed - int24(uint24(bitPos))) * tickSpacing;
} else {
// start from the word of the next tick, since the current tick state doesn't matter
(int16 wordPos, uint8 bitPos) = position(compressed + 1);
// all the 1s at or to the left of the bitPos
uint256 mask = ~((1 << bitPos) - 1);
uint256 masked = self[wordPos] & mask;
// if there are no initialized ticks to the left of the current tick, return leftmost in the word
initialized = masked != 0;
// overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
next = initialized
? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing
: (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;
}
}
}
| 10,528 |
5 | // require(msg.sender == manager, MANAGED_REQUIRE_ONLY_MANAGER); | require(msg.sender == manager, "only manager");
_;
| require(msg.sender == manager, "only manager");
_;
| 36,763 |
42 | // End Handle Fees |
function shouldSwapBack() internal view returns (bool) {
return msg.sender != uniswapV2Pair
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
|
function shouldSwapBack() internal view returns (bool) {
return msg.sender != uniswapV2Pair
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
| 26,793 |
136 | // Statistics of each country (stakes amount + number of stakers). | Statistics[44] public countryStats;
| Statistics[44] public countryStats;
| 39,579 |
181 | // optional - change the baseTokenURI for late-reveal purposes | function setBaseTokenURI(string memory uri) public onlyOwner {
baseTokenURI = uri;
}
| function setBaseTokenURI(string memory uri) public onlyOwner {
baseTokenURI = uri;
}
| 13,962 |
8 | // Returns the user index for a specific asset user The address of the user asset The asset to incentivizereturn The user index for the asset / | function getUserAssetData(address user, address asset) external view returns (uint256);
| function getUserAssetData(address user, address asset) external view returns (uint256);
| 9,863 |
29 | // set kick incentive | function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
| function setKickIncentive(uint256 _rate, uint256 _delay) external onlyOwner {
require(_rate <= 500, "over max rate"); //max 5% per epoch
require(_delay >= 2, "min delay"); //minimum 2 epochs of grace
kickRewardPerEpoch = _rate;
kickRewardEpochDelay = _delay;
}
| 48,825 |
159 | // Transfer assets to buyer | maskedResult = maskedValue + addAmount;
allAsset = ((allAsset ^ mask) & allAsset) | bytes32(maskedResult);
assets[msg.sender][assetFloor] = allAsset;
saleOrderList[saleId].amount -= uint64(amount);
| maskedResult = maskedValue + addAmount;
allAsset = ((allAsset ^ mask) & allAsset) | bytes32(maskedResult);
assets[msg.sender][assetFloor] = allAsset;
saleOrderList[saleId].amount -= uint64(amount);
| 69,046 |
34 | // Get the entry point for this contract This function returns the contract's entry point interface.return The contract's entry point interface. / | function entryPoint() external view override returns (IEntryPoint) {
return _entryPoint;
}
| function entryPoint() external view override returns (IEntryPoint) {
return _entryPoint;
}
| 5,624 |
3 | // cumulative supply rate += ((exchangeRate now - exchangeRate prev)EXP_SCALE / exchangeRate now) | uint256 public cumulativeSupplyRate;
| uint256 public cumulativeSupplyRate;
| 67,100 |
49 | // Because the exponent is larger than one, the base of the power function has a lower bound. We cap to this value to avoid numeric issues, which means in the extreme case (where the invariant growth is larger than 1 / min exponent) the Pool will pay less in protocol fees than it should. | base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT);
uint256 power = base.powUp(exponent);
uint256 tokenAccruedFees = balance.mulDown(power.complement());
return tokenAccruedFees.mulDown(protocolSwapFeePercentage);
| base = Math.max(base, FixedPoint.MIN_POW_BASE_FREE_EXPONENT);
uint256 power = base.powUp(exponent);
uint256 tokenAccruedFees = balance.mulDown(power.complement());
return tokenAccruedFees.mulDown(protocolSwapFeePercentage);
| 21,913 |
302 | // Markets must have been listed | require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
| require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
| 61,034 |
253 | // BasicIssuanceModule Cook Finance Module that enables issuance and redemption functionality on a CKToken. This is a module that isrequired to bring the totalSupply of a CK above 0. / | contract BasicIssuanceModule is ModuleBase, ReentrancyGuard {
using Invoke for ICKToken;
using Position for ICKToken.Position;
using Position for ICKToken;
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using SafeCast for int256;
/* ============ Events ============ */
event CKTokenIssued(
address indexed _ckToken,
address indexed _issuer,
address indexed _to,
address _hookContract,
uint256 _quantity
);
event CKTokenRedeemed(
address indexed _ckToken,
address indexed _redeemer,
address indexed _to,
uint256 _quantity
);
/* ============ State Variables ============ */
// Mapping of CKToken to Issuance hook configurations
mapping(ICKToken => IManagerIssuanceHook) public managerIssuanceHook;
/* ============ Constructor ============ */
/**
* Set state controller state variable
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public ModuleBase(_controller) {}
/* ============ External Functions ============ */
/**
* Deposits the CKToken's position components into the CKToken and mints the CKToken of the given quantity
* to the specified _to address. This function only handles Default Positions (positionState = 0).
*
* @param _ckToken Instance of the CKToken contract
* @param _quantity Quantity of the CKToken to mint
* @param _to Address to mint CKToken to
*/
function issue(
ICKToken _ckToken,
uint256 _quantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
require(_quantity > 0, "Issue quantity must be > 0");
address hookContract = _callPreIssueHooks(_ckToken, _quantity, msg.sender, _to);
(
address[] memory components,
uint256[] memory componentQuantities
) = getRequiredComponentUnitsForIssue(_ckToken, _quantity);
// For each position, transfer the required underlying to the CKToken
for (uint256 i = 0; i < components.length; i++) {
// Transfer the component to the CKToken
transferFrom(
IERC20(components[i]),
msg.sender,
address(_ckToken),
componentQuantities[i]
);
}
// Mint the CKToken
_ckToken.mint(_to, _quantity);
emit CKTokenIssued(address(_ckToken), msg.sender, _to, hookContract, _quantity);
}
/**
* Redeems the CKToken's positions and sends the components of the given
* quantity to the caller. This function only handles Default Positions (positionState = 0).
*
* @param _ckToken Instance of the CKToken contract
* @param _quantity Quantity of the CKToken to redeem
* @param _to Address to send component assets to
*/
function redeem(
ICKToken _ckToken,
uint256 _quantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
require(_quantity > 0, "Redeem quantity must be > 0");
// Burn the CKToken - ERC20's internal burn already checks that the user has enough balance
_ckToken.burn(msg.sender, _quantity);
// For each position, invoke the CKToken to transfer the tokens to the user
address[] memory components = _ckToken.getComponents();
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
require(!_ckToken.hasExternalPosition(component), "Only default positions are supported");
uint256 unit = _ckToken.getDefaultPositionRealUnit(component).toUint256();
// Use preciseMul to round down to ensure overcollateration when small redeem quantities are provided
uint256 componentQuantity = _quantity.preciseMul(unit);
// Instruct the CKToken to transfer the component to the user
_ckToken.strictInvokeTransfer(
component,
_to,
componentQuantity
);
}
emit CKTokenRedeemed(address(_ckToken), msg.sender, _to, _quantity);
}
/**
* Initializes this module to the CKToken with issuance-related hooks. Only callable by the CKToken's manager.
* Hook addresses are optional. Address(0) means that no hook will be called
*
* @param _ckToken Instance of the CKToken to issue
* @param _preIssueHook Instance of the Manager Contract with the Pre-Issuance Hook function
*/
function initialize(
ICKToken _ckToken,
IManagerIssuanceHook _preIssueHook
)
external
onlyCKManager(_ckToken, msg.sender)
onlyValidAndPendingCK(_ckToken)
{
managerIssuanceHook[_ckToken] = _preIssueHook;
_ckToken.initializeModule();
}
/**
* Reverts as this module should not be removable after added. Users should always
* have a way to redeem their CKs
*/
function removeModule() external override {
revert("The BasicIssuanceModule module cannot be removed");
}
/* ============ External Getter Functions ============ */
/**
* Retrieves the addresses and units required to mint a particular quantity of CKToken.
*
* @param _ckToken Instance of the CKToken to issue
* @param _quantity Quantity of CKToken to issue
* @return address[] List of component addresses
* @return uint256[] List of component units required to issue the quantity of CKTokens
*/
function getRequiredComponentUnitsForIssue(
ICKToken _ckToken,
uint256 _quantity
)
public
view
onlyValidAndInitializedCK(_ckToken)
returns (address[] memory, uint256[] memory)
{
address[] memory components = _ckToken.getComponents();
uint256[] memory notionalUnits = new uint256[](components.length);
for (uint256 i = 0; i < components.length; i++) {
require(!_ckToken.hasExternalPosition(components[i]), "Only default positions are supported");
notionalUnits[i] = _ckToken.getDefaultPositionRealUnit(components[i]).toUint256().preciseMulCeil(_quantity);
}
return (components, notionalUnits);
}
/* ============ Internal Functions ============ */
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ICKToken _ckToken,
uint256 _quantity,
address _caller,
address _to
)
internal
returns(address)
{
IManagerIssuanceHook preIssueHook = managerIssuanceHook[_ckToken];
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_ckToken, _quantity, _caller, _to);
return address(preIssueHook);
}
return address(0);
}
} | contract BasicIssuanceModule is ModuleBase, ReentrancyGuard {
using Invoke for ICKToken;
using Position for ICKToken.Position;
using Position for ICKToken;
using PreciseUnitMath for uint256;
using SafeMath for uint256;
using SafeCast for int256;
/* ============ Events ============ */
event CKTokenIssued(
address indexed _ckToken,
address indexed _issuer,
address indexed _to,
address _hookContract,
uint256 _quantity
);
event CKTokenRedeemed(
address indexed _ckToken,
address indexed _redeemer,
address indexed _to,
uint256 _quantity
);
/* ============ State Variables ============ */
// Mapping of CKToken to Issuance hook configurations
mapping(ICKToken => IManagerIssuanceHook) public managerIssuanceHook;
/* ============ Constructor ============ */
/**
* Set state controller state variable
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public ModuleBase(_controller) {}
/* ============ External Functions ============ */
/**
* Deposits the CKToken's position components into the CKToken and mints the CKToken of the given quantity
* to the specified _to address. This function only handles Default Positions (positionState = 0).
*
* @param _ckToken Instance of the CKToken contract
* @param _quantity Quantity of the CKToken to mint
* @param _to Address to mint CKToken to
*/
function issue(
ICKToken _ckToken,
uint256 _quantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
require(_quantity > 0, "Issue quantity must be > 0");
address hookContract = _callPreIssueHooks(_ckToken, _quantity, msg.sender, _to);
(
address[] memory components,
uint256[] memory componentQuantities
) = getRequiredComponentUnitsForIssue(_ckToken, _quantity);
// For each position, transfer the required underlying to the CKToken
for (uint256 i = 0; i < components.length; i++) {
// Transfer the component to the CKToken
transferFrom(
IERC20(components[i]),
msg.sender,
address(_ckToken),
componentQuantities[i]
);
}
// Mint the CKToken
_ckToken.mint(_to, _quantity);
emit CKTokenIssued(address(_ckToken), msg.sender, _to, hookContract, _quantity);
}
/**
* Redeems the CKToken's positions and sends the components of the given
* quantity to the caller. This function only handles Default Positions (positionState = 0).
*
* @param _ckToken Instance of the CKToken contract
* @param _quantity Quantity of the CKToken to redeem
* @param _to Address to send component assets to
*/
function redeem(
ICKToken _ckToken,
uint256 _quantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedCK(_ckToken)
{
require(_quantity > 0, "Redeem quantity must be > 0");
// Burn the CKToken - ERC20's internal burn already checks that the user has enough balance
_ckToken.burn(msg.sender, _quantity);
// For each position, invoke the CKToken to transfer the tokens to the user
address[] memory components = _ckToken.getComponents();
for (uint256 i = 0; i < components.length; i++) {
address component = components[i];
require(!_ckToken.hasExternalPosition(component), "Only default positions are supported");
uint256 unit = _ckToken.getDefaultPositionRealUnit(component).toUint256();
// Use preciseMul to round down to ensure overcollateration when small redeem quantities are provided
uint256 componentQuantity = _quantity.preciseMul(unit);
// Instruct the CKToken to transfer the component to the user
_ckToken.strictInvokeTransfer(
component,
_to,
componentQuantity
);
}
emit CKTokenRedeemed(address(_ckToken), msg.sender, _to, _quantity);
}
/**
* Initializes this module to the CKToken with issuance-related hooks. Only callable by the CKToken's manager.
* Hook addresses are optional. Address(0) means that no hook will be called
*
* @param _ckToken Instance of the CKToken to issue
* @param _preIssueHook Instance of the Manager Contract with the Pre-Issuance Hook function
*/
function initialize(
ICKToken _ckToken,
IManagerIssuanceHook _preIssueHook
)
external
onlyCKManager(_ckToken, msg.sender)
onlyValidAndPendingCK(_ckToken)
{
managerIssuanceHook[_ckToken] = _preIssueHook;
_ckToken.initializeModule();
}
/**
* Reverts as this module should not be removable after added. Users should always
* have a way to redeem their CKs
*/
function removeModule() external override {
revert("The BasicIssuanceModule module cannot be removed");
}
/* ============ External Getter Functions ============ */
/**
* Retrieves the addresses and units required to mint a particular quantity of CKToken.
*
* @param _ckToken Instance of the CKToken to issue
* @param _quantity Quantity of CKToken to issue
* @return address[] List of component addresses
* @return uint256[] List of component units required to issue the quantity of CKTokens
*/
function getRequiredComponentUnitsForIssue(
ICKToken _ckToken,
uint256 _quantity
)
public
view
onlyValidAndInitializedCK(_ckToken)
returns (address[] memory, uint256[] memory)
{
address[] memory components = _ckToken.getComponents();
uint256[] memory notionalUnits = new uint256[](components.length);
for (uint256 i = 0; i < components.length; i++) {
require(!_ckToken.hasExternalPosition(components[i]), "Only default positions are supported");
notionalUnits[i] = _ckToken.getDefaultPositionRealUnit(components[i]).toUint256().preciseMulCeil(_quantity);
}
return (components, notionalUnits);
}
/* ============ Internal Functions ============ */
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ICKToken _ckToken,
uint256 _quantity,
address _caller,
address _to
)
internal
returns(address)
{
IManagerIssuanceHook preIssueHook = managerIssuanceHook[_ckToken];
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_ckToken, _quantity, _caller, _to);
return address(preIssueHook);
}
return address(0);
}
} | 23,425 |
5 | // the proxy address | address private immutable i_proxyAddress;
| address private immutable i_proxyAddress;
| 19,238 |
37 | // A is dead | } else if (hpA == 0 && hpB > 0) {
| } else if (hpA == 0 && hpB > 0) {
| 43,883 |
71 | // buy Bancor v2 | if(bancorPoolVersion >= 28){
(connectorsAddress, connectorsAmount, poolAmountReceive) = buyBancorPoolV2(
_poolToken,
_additionalData
);
}
| if(bancorPoolVersion >= 28){
(connectorsAddress, connectorsAmount, poolAmountReceive) = buyBancorPoolV2(
_poolToken,
_additionalData
);
}
| 17,759 |
34 | // Update players jade | cards.updatePlayersCoinByPurchase(msg.sender, coinCost);
| cards.updatePlayersCoinByPurchase(msg.sender, coinCost);
| 46,757 |
50 | // use applicant address as delegateKey by default | members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true, 0, 0);
memberAddressByDelegateKey[proposal.applicant] = proposal.applicant;
| members[proposal.applicant] = Member(proposal.applicant, proposal.sharesRequested, proposal.lootRequested, true, 0, 0);
memberAddressByDelegateKey[proposal.applicant] = proposal.applicant;
| 38,215 |
23 | // Writes a byte string to a buffer. Resizes if doing so would exceedthe capacity of the buffer.buf The buffer to append to.off The start offset to write to.data The data to append.len The number of bytes to copy. return The original buffer, for chaining./ | function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
| function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
| 1,299 |
67 | // Emits a {TokensReleased} event. / | function release() public virtual {
uint256 releasable = vestedAmount(uint64(block.timestamp)) - released();
_released += releasable;
emit EtherReleased(releasable);
Address.sendValue(payable(beneficiary()), releasable);
}
| function release() public virtual {
uint256 releasable = vestedAmount(uint64(block.timestamp)) - released();
_released += releasable;
emit EtherReleased(releasable);
Address.sendValue(payable(beneficiary()), releasable);
}
| 19,714 |
146 | // By default, the liquidator is allowed to purchase at least to `defaultAllowedAmount` if `liquidateAmountRequired` is less than `defaultAllowedAmount`. | int256 defaultAllowedAmount =
maxTotalBalance.mul(Constants.DEFAULT_LIQUIDATION_PORTION).div(
Constants.PERCENTAGE_DECIMALS
);
int256 result = liquidateAmountRequired;
| int256 defaultAllowedAmount =
maxTotalBalance.mul(Constants.DEFAULT_LIQUIDATION_PORTION).div(
Constants.PERCENTAGE_DECIMALS
);
int256 result = liquidateAmountRequired;
| 61,873 |
27 | // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. | _balances[account] += amount;
| _balances[account] += amount;
| 37,753 |
3 | // owned by A is sender's offer ~~~~~~~~ B is the other side of trade | bool isOwnedbyA = (IERC721(A.token).ownerOf(A.id) == msg.sender);
bool isOwnedbyB = (IERC721(B.token).ownerOf(B.id) == with);
return (isOwnedbyA && isOwnedbyB);
| bool isOwnedbyA = (IERC721(A.token).ownerOf(A.id) == msg.sender);
bool isOwnedbyB = (IERC721(B.token).ownerOf(B.id) == with);
return (isOwnedbyA && isOwnedbyB);
| 24,009 |
6 | // Rules for open mystery boxes | mapping(uint256=>uint16[][]) private _mysteryBoxesRules;
| mapping(uint256=>uint16[][]) private _mysteryBoxesRules;
| 20,470 |
91 | // This function can be optionally overridden by a parent contract to track any additionaldebit balance in an alternative way. / | function _additionalDebit(address /*bonder*/) internal view virtual returns (uint256) {
this; // Silence state mutability warning without generating any additional byte code
return 0;
}
| function _additionalDebit(address /*bonder*/) internal view virtual returns (uint256) {
this; // Silence state mutability warning without generating any additional byte code
return 0;
}
| 46,323 |
49 | // --Owner only functions | function setNewOwner(address o) public onlyOwner {
newOwner = o;
}
| function setNewOwner(address o) public onlyOwner {
newOwner = o;
}
| 16,343 |
18 | // It withdraws all LP tokens | function withdraw() public nonReentrant {
require(
_lockedUntil[_msgSender()] < block.timestamp,
"LPStaking: You need to wait for time lock to expire."
);
require(
balanceOf(_msgSender()) > 0,
"LPStaking: You need to stake LP first."
);
uint256 stakedLP = _updateAtStakeEnd(_msgSender());
IERC20(_LPToken).safeTransfer(_msgSender(), stakedLP);
}
| function withdraw() public nonReentrant {
require(
_lockedUntil[_msgSender()] < block.timestamp,
"LPStaking: You need to wait for time lock to expire."
);
require(
balanceOf(_msgSender()) > 0,
"LPStaking: You need to stake LP first."
);
uint256 stakedLP = _updateAtStakeEnd(_msgSender());
IERC20(_LPToken).safeTransfer(_msgSender(), stakedLP);
}
| 12,647 |
1 | // Initializes this contract. Must only be callable one time, which should occur return Arbitrary bytes. / | function initialize(
address _owner,
string memory _projectName,
bytes memory _data
) external returns (bytes memory);
| function initialize(
address _owner,
string memory _projectName,
bytes memory _data
) external returns (bytes memory);
| 7,120 |
7 | // - Mode Standart | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SM: addition overflow");
return c;
}
| function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SM: addition overflow");
return c;
}
| 2,991 |
166 | // done for readability sake | bytes32 _whatProposal = whatProposal(_whatFunction);
address _whichAdmin;
| bytes32 _whatProposal = whatProposal(_whatFunction);
address _whichAdmin;
| 59,135 |
88 | // 避免先claim后再split,可能会因为精度导致locedAmount比principal多一点 | if (lockedAmount > vesting.principal) {
return 0;
}
| if (lockedAmount > vesting.principal) {
return 0;
}
| 71,552 |
66 | // Retrieve the sum of all outstanding payments.return The sum of all outstanding payments. / | function getPaymentsSum() external view returns (uint256) {
return getPaymentQueue().getPaymentsSum();
}
| function getPaymentsSum() external view returns (uint256) {
return getPaymentQueue().getPaymentsSum();
}
| 47,571 |
4 | // Load the address of the implementation contract from an explicit storage slot. | assembly {
implementationAddress := sload(implementationPosition)
}
| assembly {
implementationAddress := sload(implementationPosition)
}
| 21,513 |
147 | // mint | _addTokenToAllTokensEnumeration(tokenId);
_updateTokenAddressMap(tokenId, to);
_insertOriginalMinter(to, tokenId);
| _addTokenToAllTokensEnumeration(tokenId);
_updateTokenAddressMap(tokenId, to);
_insertOriginalMinter(to, tokenId);
| 8,252 |
74 | // Authorize or unauthorize an address to be an operator. _operator Address to authorize _allowed Whether authorized or not / | function setOperator(address _operator, bool _allowed) external override {
require(_operator != msg.sender, "operator == sender");
operatorAuth[msg.sender][_operator] = _allowed;
emit SetOperator(msg.sender, _operator, _allowed);
}
| function setOperator(address _operator, bool _allowed) external override {
require(_operator != msg.sender, "operator == sender");
operatorAuth[msg.sender][_operator] = _allowed;
emit SetOperator(msg.sender, _operator, _allowed);
}
| 12,509 |
3 | // Withdraw the Usdc value _vaultAddress the vault address _amount the amount to transfer / | function withdrawUsdc(address _vaultAddress, uint256 _amount) external;
| function withdrawUsdc(address _vaultAddress, uint256 _amount) external;
| 35,027 |
77 | // Function to set Referral Address add referral pool address / | function setReferralAddress(address add) public onlyOwner returns(bool){
require(add != address(0),"Invalid Address");
_referralAddress = add;
return true;
}
| function setReferralAddress(address add) public onlyOwner returns(bool){
require(add != address(0),"Invalid Address");
_referralAddress = add;
return true;
}
| 14,611 |
184 | // Contract constructor. _logic Address of the initial implementation. _data Data to send as msg.data to the implementation to initialize the proxied contract.It should include the signature and the parameters of the function to be called, as described inThis parameter is optional, if no data is given the initialization call to proxied contract will be skipped. / | constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
| constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
| 23,871 |
50 | // The ilk's join adapter | function join(bytes32 ilk) external view returns (address) {
return ilkData[ilk].join;
}
| function join(bytes32 ilk) external view returns (address) {
return ilkData[ilk].join;
}
| 23,989 |
86 | // Dividend tracker | if(!isDividendExempt[from]) {
try distributor.setShare(from, _balances[from]) {} catch {}
| if(!isDividendExempt[from]) {
try distributor.setShare(from, _balances[from]) {} catch {}
| 3,759 |
159 | // EIP-1167 bytecode | let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
| let clone_code := mload(0x40)
mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone_code, 0x14), addressBytes)
mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
newStrategy := create(0, clone_code, 0x37)
| 876 |
74 | // User address => Underlying asset address => LP quantity | mapping(address=>mapping(address=>uint256)) balances;
| mapping(address=>mapping(address=>uint256)) balances;
| 41,056 |
8 | // Funds our contract based on the ETH/USD price | function fund() public payable {
require(
msg.value.getConversionRate(s_priceFeed) >= MINIMUM_USD,
"You need to spend more ETH!"
);
| function fund() public payable {
require(
msg.value.getConversionRate(s_priceFeed) >= MINIMUM_USD,
"You need to spend more ETH!"
);
| 18,134 |
48 | // write checkpoint for delegatee. blocknumber should be uint32. delegatee the address of delegatee. nCheckpoints no of checkpoints. oldVotes number of old votes. newVotes number of new votes. / |
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
|
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
| 13,094 |
44 | // queen side castling | if (move.targetSq == 58){
if (gameState.wqC == false){
return false;
}
| if (move.targetSq == 58){
if (gameState.wqC == false){
return false;
}
| 94 |
44 | // The basics of a proxy read call Note that msg.sender in the underlying will always be the address of this contract. | assembly {
calldatacopy(0, 0, calldatasize)
| assembly {
calldatacopy(0, 0, calldatasize)
| 14,063 |
6 | // burns a set amount of ArbiLocker tokens | require(amount > 1000, "Deposit too low");
require(length > 0 && length < 10000, "9999 days max lock");
require(msg.value == ethFee,"Please include fee");
address _owner = owner();
IERC20 lp = IERC20(token);
lp.transferFrom(msg.sender, _owner, amount);
Safe memory newSafe;
newSafe.owner = user;
newSafe.token = token;
newSafe.amount = amount;
| require(amount > 1000, "Deposit too low");
require(length > 0 && length < 10000, "9999 days max lock");
require(msg.value == ethFee,"Please include fee");
address _owner = owner();
IERC20 lp = IERC20(token);
lp.transferFrom(msg.sender, _owner, amount);
Safe memory newSafe;
newSafe.owner = user;
newSafe.token = token;
newSafe.amount = amount;
| 20,923 |
0 | // Create a new add two-side optimal strategy instance./_router The Uniswap router smart contract. | constructor(IUniswapV2Router02 _router, address _orbit) public {
factory = IUniswapV2Factory(_router.factory());
router = _router;
weth = _router.WETH();
orbit = _orbit;
}
| constructor(IUniswapV2Router02 _router, address _orbit) public {
factory = IUniswapV2Factory(_router.factory());
router = _router;
weth = _router.WETH();
orbit = _orbit;
}
| 13,591 |
135 | // set fxChildTunnel if not set already | function setFxChildTunnel(address _fxChildTunnel) public {
require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET");
fxChildTunnel = _fxChildTunnel;
}
| function setFxChildTunnel(address _fxChildTunnel) public {
require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET");
fxChildTunnel = _fxChildTunnel;
}
| 23,303 |
2 | // @TODO: Pass the constructor parameters to the crowdsale contracts. | Crowdsale(rate, wallet, token)
MintedCrowdsale()
CappedCrowdsale(goal)
TimedCrowdsale(open, close)
PostDeliveryCrowdsale()
RefundableCrowdsale(goal)
| Crowdsale(rate, wallet, token)
MintedCrowdsale()
CappedCrowdsale(goal)
TimedCrowdsale(open, close)
PostDeliveryCrowdsale()
RefundableCrowdsale(goal)
| 1,805 |
82 | // - `index` must be strictly less than {length}./ | function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
| function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
| 743 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.