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 |
|---|---|---|---|---|
163 | // Address of factory that produced this instance | address public factory;
| address public factory;
| 75,330 |
389 | // Transfer owedToken to the exchange wrapper | TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
| TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
| 24,583 |
2 | // Simulates collateralization of `amountIn` ERC1155 tokens with id `batchId` for msg.sender/batchId id of the batch/amountIn ERC1155 tokens to collateralize/ return cbtUserCut ERC20 tokens to be received by msg.sender/ return cbtDaoCut ERC20 tokens to be received by feeReceiver/ return cbtForfeited ERC20 tokens forfeited for collateralizing the ERC1155 tokens | function simulateBatchCollateralization(uint batchId, uint amountIn)
external
view
returns (
uint cbtUserCut,
uint cbtDaoCut,
uint cbtForfeited
);
| function simulateBatchCollateralization(uint batchId, uint amountIn)
external
view
returns (
uint cbtUserCut,
uint cbtDaoCut,
uint cbtForfeited
);
| 7,877 |
6 | // delegatecall returns 0 on error. | case 0 { revert(0, returndatasize()) }
| case 0 { revert(0, returndatasize()) }
| 13,929 |
125 | // Wraps SynapseBridge deposit() function to make it compatible w/ ETH -> WETH conversions to address on other chain to bridge assets to chainId which chain to bridge assets onto amount Amount in native token decimals to transfer cross-chain pre-fees / | ) external payable {
require(msg.value > 0 && msg.value == amount, 'INCORRECT MSG VALUE');
IWETH9(WETH_ADDRESS).deposit{value: msg.value}();
synapseBridge.deposit(to, chainId, IERC20(WETH_ADDRESS), amount);
}
| ) external payable {
require(msg.value > 0 && msg.value == amount, 'INCORRECT MSG VALUE');
IWETH9(WETH_ADDRESS).deposit{value: msg.value}();
synapseBridge.deposit(to, chainId, IERC20(WETH_ADDRESS), amount);
}
| 58,032 |
14 | // get user health insurance details - Test data to test on Remix - ("U123") | function getUserDetails(string memory unique_identification) public view returns(bool has_health_insurance, int health_insurance_amount){
return (userRecordMapping[unique_identification].has_health_insurance, userRecordMapping[unique_identification].health_insurance_amount);
}
| function getUserDetails(string memory unique_identification) public view returns(bool has_health_insurance, int health_insurance_amount){
return (userRecordMapping[unique_identification].has_health_insurance, userRecordMapping[unique_identification].health_insurance_amount);
}
| 30,807 |
7 | // https:etherscan.io/address/0xf48F8D49Ad04C0DaA612470A91e760b3d9Fa8f88 | Issuer public constant issuer_i = Issuer(0xf48F8D49Ad04C0DaA612470A91e760b3d9Fa8f88);
| Issuer public constant issuer_i = Issuer(0xf48F8D49Ad04C0DaA612470A91e760b3d9Fa8f88);
| 15,620 |
12 | // forward and backward mappings used for enumerable standard owner -> array of tokens owned...ownershipMapIndexToToken[owner][index] = tokenNumber owner -> array of tokens owned...ownershipMapTokenToIndex[owner][tokenNumber] = index | mapping (address => mapping (uint => uint)) public ownershipMapIndexToToken;
mapping (address => mapping (uint => uint)) public ownershipMapTokenToIndex;
| mapping (address => mapping (uint => uint)) public ownershipMapIndexToToken;
mapping (address => mapping (uint => uint)) public ownershipMapTokenToIndex;
| 29,988 |
98 | // notice An event thats emitted when a delegate account's vote balance changes | event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
constructor() public
| event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
constructor() public
| 13,904 |
689 | // for ERC2981 Opensea | function contractURI() external view virtual returns (string memory) {
return _formatContractURI();
}
| function contractURI() external view virtual returns (string memory) {
return _formatContractURI();
}
| 18,579 |
614 | // allow anyone to send lost tokens (excluding principle or OHM) to the DAOreturn bool/ | // function recoverLostToken( address _token ) external returns ( bool ) {
// require( _token != OHM );
// require( _token != principle );
// IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
// return true;
// }
| // function recoverLostToken( address _token ) external returns ( bool ) {
// require( _token != OHM );
// require( _token != principle );
// IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
// return true;
// }
| 22,973 |
11 | // Initialize header start index | bytes32 _digest;
_totalDifficulty = 0;
for (uint256 _start = 0; _start < _headers.length; _start += 80) {
| bytes32 _digest;
_totalDifficulty = 0;
for (uint256 _start = 0; _start < _headers.length; _start += 80) {
| 22,913 |
58 | // Whether `memberToCheck` is a member of roleId. Reverts if roleId does not correspond to an initialized role. roleId the Role to check. memberToCheck the address to check.return True if `memberToCheck` is a member of `roleId`. / | function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
| function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
| 17,084 |
286 | // dont delete, just set next index | userBalance.nextUnlockIndex = length.to32();
| userBalance.nextUnlockIndex = length.to32();
| 41,735 |
13 | // 1 byte for the length prefix | require(item.len == 21);
return address(toUint(item));
| require(item.len == 21);
return address(toUint(item));
| 12,575 |
16 | // set merkle root for whitelist verification | function setMerkleRoot(bytes32 _set) external onlyOwner {
merkleRoot = _set;
}
| function setMerkleRoot(bytes32 _set) external onlyOwner {
merkleRoot = _set;
}
| 83,607 |
0 | // Admin Functions | function setContracts(address _tokenAddr, address _wallet) public onlyOwner whenPaused {
wallet = _wallet;
token = MintableToken(_tokenAddr);
}
| function setContracts(address _tokenAddr, address _wallet) public onlyOwner whenPaused {
wallet = _wallet;
token = MintableToken(_tokenAddr);
}
| 41,378 |
4 | // Emitted when a market deposits snxUSD in the system. marketId The id of the market that deposited snxUSD in the system. target The address of the account that provided the snxUSD in the deposit. amount The amount of snxUSD deposited in the system, denominated with 18 decimals of precision. market The address of the external market that is depositing. / | event MarketUsdDeposited(
| event MarketUsdDeposited(
| 26,101 |
1,232 | // withdraw funds to msg.sender | if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
| if (_borrowToken != ETH_ADDR) {
ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this)));
} else {
| 31,522 |
88 | // Update total MXX minted from yield contracts | mxxMintedFromContract = mxxMintedFromContract.add(valueToBeMinted);
| mxxMintedFromContract = mxxMintedFromContract.add(valueToBeMinted);
| 24,676 |
18 | // | modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
| modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
| 6,339 |
20 | // Burn tokens `ids_`/Burn token `id_`/ids_ (uint256[] calldata) Token ID | function burnBatchToken(uint256[] calldata ids_) external onlyOwner {
unchecked {
uint256 length = ids_.length;
for (uint256 i; i < length; ++i) {
_burn(ids_[i]);
_resetTokenRoyalty(ids_[i]);
}
}
}
| function burnBatchToken(uint256[] calldata ids_) external onlyOwner {
unchecked {
uint256 length = ids_.length;
for (uint256 i; i < length; ++i) {
_burn(ids_[i]);
_resetTokenRoyalty(ids_[i]);
}
}
}
| 25,946 |
34 | // address should be distinct | for (uint j = 0; j < i; j++) {
if (addrs[i] == addrs[j]) {
return false;
}
| for (uint j = 0; j < i; j++) {
if (addrs[i] == addrs[j]) {
return false;
}
| 4,941 |
138 | // Q2 Selector | {
uint256 w2 = proof.w2;
assembly {
scalar_multiplier := mulmod(w2, linear_challenge, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
let t0 := mulmod(scaling_alpha, q_ecc, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
| {
uint256 w2 = proof.w2;
assembly {
scalar_multiplier := mulmod(w2, linear_challenge, p)
scalar_multiplier := mulmod(scalar_multiplier, alpha_base, p)
scalar_multiplier := mulmod(scalar_multiplier, q_arith, p)
let t0 := mulmod(scaling_alpha, q_ecc, p)
scalar_multiplier := addmod(scalar_multiplier, mulmod(t0, linear_challenge, p), p)
}
| 48,367 |
6 | // ackFunds checks the difference between the last known balance of `token` and the current one if it goes up, the multiplier is re-calculated if it goes down, it only updates the known balance | function ackFunds() public {
uint256 balanceNow = rewardToken.balanceOf(address(this));
if (balanceNow == 0 || balanceNow <= balanceBefore) {
balanceBefore = balanceNow;
return;
}
uint256 totalStakedEntr = kernel.entrStaked();
// if there's no entr staked, it doesn't make sense to ackFunds because there's nobody to distribute them to
// and the calculation would fail anyways due to division by 0
if (totalStakedEntr == 0) {
return;
}
uint256 diff = balanceNow.sub(balanceBefore);
uint256 multiplier = currentMultiplier.add(diff.mul(decimals).div(totalStakedEntr));
balanceBefore = balanceNow;
currentMultiplier = multiplier;
}
| function ackFunds() public {
uint256 balanceNow = rewardToken.balanceOf(address(this));
if (balanceNow == 0 || balanceNow <= balanceBefore) {
balanceBefore = balanceNow;
return;
}
uint256 totalStakedEntr = kernel.entrStaked();
// if there's no entr staked, it doesn't make sense to ackFunds because there's nobody to distribute them to
// and the calculation would fail anyways due to division by 0
if (totalStakedEntr == 0) {
return;
}
uint256 diff = balanceNow.sub(balanceBefore);
uint256 multiplier = currentMultiplier.add(diff.mul(decimals).div(totalStakedEntr));
balanceBefore = balanceNow;
currentMultiplier = multiplier;
}
| 44,692 |
21 | // https:github.com/crytic/slither/wiki/Detector-Documentationdivide-before-multiply slither-disable-next-line divide-before-multiply | uint256 secondsInInterval = block.timestamp.sub(
cliffEndTimestamp.add(
intervalSeconds.add(gapSeconds).mul(intervalNumber)
)
);
totalPercentage = secondsInInterval >= intervalSeconds
? totalPercentage.add(
vestingSchedule.percentReleaseForEachInterval
)
: totalPercentage.add(
| uint256 secondsInInterval = block.timestamp.sub(
cliffEndTimestamp.add(
intervalSeconds.add(gapSeconds).mul(intervalNumber)
)
);
totalPercentage = secondsInInterval >= intervalSeconds
? totalPercentage.add(
vestingSchedule.percentReleaseForEachInterval
)
: totalPercentage.add(
| 70,110 |
5 | // Returns whether all relevant permission and other checks are met before any upgrade. | function _isAuthorizedCallToUpgrade() internal view virtual override returns (bool) {
return hasRole(keccak256("EXTENSION_ROLE"), msg.sender);
}
| function _isAuthorizedCallToUpgrade() internal view virtual override returns (bool) {
return hasRole(keccak256("EXTENSION_ROLE"), msg.sender);
}
| 27,354 |
0 | // Sets the values for {name} and {symbol}.It also mints 10000 XYZ tokens to owner address. / | constructor() ERC20("Tal Token","Tal"){
_mint(msg.sender, 10000 * 10 ** decimals());
}
| constructor() ERC20("Tal Token","Tal"){
_mint(msg.sender, 10000 * 10 ** decimals());
}
| 19,622 |
352 | // MARGIN Get margin from SyntheticId | (uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative);
| (uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative);
| 34,358 |
124 | // сжигаем 1 монетку | require(coin.burn(heroes.ownerOf(_tokenId), 1));
| require(coin.burn(heroes.ownerOf(_tokenId), 1));
| 31,750 |
111 | // Starts paused. | paused = true;
| paused = true;
| 6,778 |
187 | // @inheritdoc IVestedLPMining/Anyone may call, so we have to trust the migrator contract | function migrate(uint256 _pid) public override nonReentrant {
require(address(migrator) != address(0), "YieldFarm: no migrator");
Pool storage pool = pools[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken, pool.poolType);
require(bal == newLpToken.balanceOf(address(this)), "YieldFarm: invalid migration");
pool.lpToken = newLpToken;
delete poolPidByAddress[address(lpToken)];
poolPidByAddress[address(newLpToken)] = _pid;
emit MigrateLpToken(address(lpToken), address(newLpToken), _pid);
}
| function migrate(uint256 _pid) public override nonReentrant {
require(address(migrator) != address(0), "YieldFarm: no migrator");
Pool storage pool = pools[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken, pool.poolType);
require(bal == newLpToken.balanceOf(address(this)), "YieldFarm: invalid migration");
pool.lpToken = newLpToken;
delete poolPidByAddress[address(lpToken)];
poolPidByAddress[address(newLpToken)] = _pid;
emit MigrateLpToken(address(lpToken), address(newLpToken), _pid);
}
| 32,635 |
26 | // Ensure the ExchangeRates contract has the standalone feed for SNX; | exchangerates_i.addAggregator("SNX", 0x38D2f492B4Ef886E71D111c592c9338374e1bd8d);
| exchangerates_i.addAggregator("SNX", 0x38D2f492B4Ef886E71D111c592c9338374e1bd8d);
| 4,696 |
197 | // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 | bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
| bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
| 5,106 |
3 | // _admin Address of the administrator, that is able to perform all calls via the Firewall/_executor Address of the executor, that is able to perform only a subset of calls via the Firewall/_executorCallableSelectors Initial list of allowed selectors for the executor | constructor(address _admin, address _executor, address _destination, bytes4[] memory _executorCallableSelectors) {
LibSanitize._notZeroAddress(_executor);
LibSanitize._notZeroAddress(_destination);
_setAdmin(_admin);
executor = _executor;
destination = _destination;
emit SetExecutor(_executor);
emit SetDestination(_destination);
for (uint256 i; i < _executorCallableSelectors.length;) {
executorCanCall[_executorCallableSelectors[i]] = true;
emit SetExecutorPermissions(_executorCallableSelectors[i], true);
unchecked {
++i;
}
}
}
| constructor(address _admin, address _executor, address _destination, bytes4[] memory _executorCallableSelectors) {
LibSanitize._notZeroAddress(_executor);
LibSanitize._notZeroAddress(_destination);
_setAdmin(_admin);
executor = _executor;
destination = _destination;
emit SetExecutor(_executor);
emit SetDestination(_destination);
for (uint256 i; i < _executorCallableSelectors.length;) {
executorCanCall[_executorCallableSelectors[i]] = true;
emit SetExecutorPermissions(_executorCallableSelectors[i], true);
unchecked {
++i;
}
}
}
| 43,458 |
70 | // Append a comment to a Batch-NFT/Don't allow the contract owner to comment.When the contract owner/ can also be a verifier they should add them as a verifier first; this/ should prevent accidental comments from the wrong account. | function addComment(uint256 tokenId, string memory comment) public virtual {
require(
hasRole(VERIFIER_ROLE, _msgSender()) ||
_msgSender() == ownerOf(tokenId) ||
_msgSender() == owner(),
'Only the batch owner, contract owner and verifiers can comment'
);
require(_exists(tokenId), 'Cannot comment on non-existent batch');
nftList[tokenId].comments.push() = comment;
nftList[tokenId].commentAuthors.push() = _msgSender();
emit BatchComment(
tokenId,
nftList[tokenId].comments.length,
_msgSender(),
comment
);
}
| function addComment(uint256 tokenId, string memory comment) public virtual {
require(
hasRole(VERIFIER_ROLE, _msgSender()) ||
_msgSender() == ownerOf(tokenId) ||
_msgSender() == owner(),
'Only the batch owner, contract owner and verifiers can comment'
);
require(_exists(tokenId), 'Cannot comment on non-existent batch');
nftList[tokenId].comments.push() = comment;
nftList[tokenId].commentAuthors.push() = _msgSender();
emit BatchComment(
tokenId,
nftList[tokenId].comments.length,
_msgSender(),
comment
);
}
| 16,087 |
10 | // NSPBar is the coolest bar in town. You come in with some NSP, and leave with more! The longer you stay, the more SNP you get. This contract handles swapping to and from xNSP, NewSwap's staking token. | contract NSPBar is ERC20("NSPBar", "xNSP"){
using SafeMath for uint256;
IERC20 public nsp;
// Define the nsp token contract
constructor(IERC20 _nsp) public {
nsp = _nsp;
}
// Enter the bar. Pay some NSPs. Earn some shares.
// Locks NSP and mints xNSP
function enter(uint256 _amount) public {
// Gets the amount of NSP locked in the contract
uint256 totalNSP = nsp.balanceOf(address(this));
// Gets the amount of xNSP in existence
uint256 totalShares = totalSupply();
// If no xNSP exists, mint it 1:1 to the amount put in
if (totalShares == 0 || totalNSP == 0) {
_mint(msg.sender, _amount);
}
// Calculate and mint the amount of xNSP the NSP is worth. The ratio will change overtime, as xNSP is burned/minted and NSP deposited + gained from fees / withdrawn.
else {
uint256 what = _amount.mul(totalShares).div(totalNSP);
_mint(msg.sender, what);
}
// Lock the NSP in the contract
nsp.transferFrom(msg.sender, address(this), _amount);
}
// Leave the bar. Claim back your NSPs.
// Unclocks the staked + gained NSP and burns xNSP
function leave(uint256 _share) public {
// Gets the amount of xNSP in existence
uint256 totalShares = totalSupply();
// Calculates the amount of NSP the xNSP is worth
uint256 what = _share.mul(nsp.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
nsp.transfer(msg.sender, what);
}
} | contract NSPBar is ERC20("NSPBar", "xNSP"){
using SafeMath for uint256;
IERC20 public nsp;
// Define the nsp token contract
constructor(IERC20 _nsp) public {
nsp = _nsp;
}
// Enter the bar. Pay some NSPs. Earn some shares.
// Locks NSP and mints xNSP
function enter(uint256 _amount) public {
// Gets the amount of NSP locked in the contract
uint256 totalNSP = nsp.balanceOf(address(this));
// Gets the amount of xNSP in existence
uint256 totalShares = totalSupply();
// If no xNSP exists, mint it 1:1 to the amount put in
if (totalShares == 0 || totalNSP == 0) {
_mint(msg.sender, _amount);
}
// Calculate and mint the amount of xNSP the NSP is worth. The ratio will change overtime, as xNSP is burned/minted and NSP deposited + gained from fees / withdrawn.
else {
uint256 what = _amount.mul(totalShares).div(totalNSP);
_mint(msg.sender, what);
}
// Lock the NSP in the contract
nsp.transferFrom(msg.sender, address(this), _amount);
}
// Leave the bar. Claim back your NSPs.
// Unclocks the staked + gained NSP and burns xNSP
function leave(uint256 _share) public {
// Gets the amount of xNSP in existence
uint256 totalShares = totalSupply();
// Calculates the amount of NSP the xNSP is worth
uint256 what = _share.mul(nsp.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
nsp.transfer(msg.sender, what);
}
} | 23,403 |
58 | // Enables approved operators to burn tokens on behalf of their ownersFeature FEATURE_BURNS_ON_BEHALF must be enabled in order for `burn()` function to succeed when called by approved operator / | uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
| uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
| 3,572 |
206 | // This event MUST emit when an address withdraws their dividend./to The address which withdraws target from this contract./weiAmount The amount of withdrawn target in wei. | event RewardWithdrawn(
address indexed to,
uint256 weiAmount
);
| event RewardWithdrawn(
address indexed to,
uint256 weiAmount
);
| 27,382 |
11 | // The permit data for a token | struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
| struct PermitDetails {
// ERC20 token address
address token;
// the maximum amount allowed to spend
uint160 amount;
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
// an incrementing value indexed per owner,token,and spender for each signature
uint48 nonce;
}
| 155 |
214 | // See {ICompliance-transferred}./ | function transferred(address _from, address _to, uint256 _value) external onlyToken override {
transferActionOnCountryWhitelisting(_from, _to, _value);
}
| function transferred(address _from, address _to, uint256 _value) external onlyToken override {
transferActionOnCountryWhitelisting(_from, _to, _value);
}
| 25,264 |
41 | // epoch count must evenly dividable by 2^n in order to get extra mints. ex. epoch 2 = 1 extramint, epoch 4 = 2 extra, epoch 8 = 3 extra mints, epoch 16 = 4 extra mints w/ a divRound for the 4th mint(allows small balance token minting aka NFTs) | if(epochCount % (2**(x+1)) == 0){
TotalOwned = IERC20(ExtraFunds[x]).balanceOf(address(this));
if(TotalOwned != 0){
if( x % 3 == 0 && x != 0){
totalOwed = (TotalOwned * totalOd).divRound(100000000 * 2500);
}else{
| if(epochCount % (2**(x+1)) == 0){
TotalOwned = IERC20(ExtraFunds[x]).balanceOf(address(this));
if(TotalOwned != 0){
if( x % 3 == 0 && x != 0){
totalOwed = (TotalOwned * totalOd).divRound(100000000 * 2500);
}else{
| 14,593 |
2 | // Sets the starting timestamp for a state./_stateId The id of the state for which we want to set the start timestamp./_timestamp The start timestamp for the given state. It should be bigger than the current one. | function setStateStartTime(bytes32 _stateId, uint256 _timestamp) internal {
require(block.timestamp < _timestamp);
if (startTime[_stateId] == 0) {
addStartCondition(_stateId, hasStartTimePassed);
}
startTime[_stateId] = _timestamp;
emit SetStateStartTime(_stateId, _timestamp);
}
| function setStateStartTime(bytes32 _stateId, uint256 _timestamp) internal {
require(block.timestamp < _timestamp);
if (startTime[_stateId] == 0) {
addStartCondition(_stateId, hasStartTimePassed);
}
startTime[_stateId] = _timestamp;
emit SetStateStartTime(_stateId, _timestamp);
}
| 2,919 |
9 | // The ConfirmedOwner contract A contract with helpers for basic contract ownership. / | contract ConfirmedOwnerWithProposal is OwnableInterface {
address private s_owner;
address private s_pendingOwner;
event OwnershipTransferRequested(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
constructor(address newOwner, address pendingOwner) {
require(newOwner != address(0), "Cannot set owner to zero");
s_owner = newOwner;
if (pendingOwner != address(0)) {
_transferOwnership(pendingOwner);
}
}
/**
* @notice Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address to) public override onlyOwner {
_transferOwnership(to);
}
/**
* @notice Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership() external override {
require(msg.sender == s_pendingOwner, "Must be proposed owner");
address oldOwner = s_owner;
s_owner = msg.sender;
s_pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @notice Get the current owner
*/
function owner() public view override returns (address) {
return s_owner;
}
/**
* @notice validate, transfer ownership, and emit relevant events
*/
function _transferOwnership(address to) private {
require(to != msg.sender, "Cannot transfer to self");
s_pendingOwner = to;
emit OwnershipTransferRequested(s_owner, to);
}
/**
* @notice validate access
*/
function _validateOwnership() internal view {
require(msg.sender == s_owner, "Only callable by owner");
}
/**
* @notice Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
_validateOwnership();
_;
}
}
| contract ConfirmedOwnerWithProposal is OwnableInterface {
address private s_owner;
address private s_pendingOwner;
event OwnershipTransferRequested(address indexed from, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
constructor(address newOwner, address pendingOwner) {
require(newOwner != address(0), "Cannot set owner to zero");
s_owner = newOwner;
if (pendingOwner != address(0)) {
_transferOwnership(pendingOwner);
}
}
/**
* @notice Allows an owner to begin transferring ownership to a new address,
* pending.
*/
function transferOwnership(address to) public override onlyOwner {
_transferOwnership(to);
}
/**
* @notice Allows an ownership transfer to be completed by the recipient.
*/
function acceptOwnership() external override {
require(msg.sender == s_pendingOwner, "Must be proposed owner");
address oldOwner = s_owner;
s_owner = msg.sender;
s_pendingOwner = address(0);
emit OwnershipTransferred(oldOwner, msg.sender);
}
/**
* @notice Get the current owner
*/
function owner() public view override returns (address) {
return s_owner;
}
/**
* @notice validate, transfer ownership, and emit relevant events
*/
function _transferOwnership(address to) private {
require(to != msg.sender, "Cannot transfer to self");
s_pendingOwner = to;
emit OwnershipTransferRequested(s_owner, to);
}
/**
* @notice validate access
*/
function _validateOwnership() internal view {
require(msg.sender == s_owner, "Only callable by owner");
}
/**
* @notice Reverts if called by anyone other than the contract owner.
*/
modifier onlyOwner() {
_validateOwnership();
_;
}
}
| 11,520 |
52 | // Mode & Feemode1(BuyTax: treasury=2%, reflection=3%, SellTax: treasury=2%, reflection=3%)mode2(BuyTax: 0, SellTax: treasury=2%, reflection=2%, luck holder reward=2%)mode3(BuyTax: auto burn supply=1%, reflections to all top 150 holders=3%, SellTax: treasury=2%, reflection=3%)mode4(BuyTax: 0, SellTax: 0) / | uint8 public mode = 0; // current mode
| uint8 public mode = 0; // current mode
| 29,345 |
14 | // Transfer the tax to the tax address | super._transfer(sender, _taxAddress, taxAmount);
| super._transfer(sender, _taxAddress, taxAmount);
| 29,659 |
353 | // The loan was delinquent and collateral claimed by the lender. This is a terminal state. | Defaulted
| Defaulted
| 24,435 |
135 | // Determine if we need to adjust any shares | _sharesToAdjust = _borrowerShares - _sharesToLiquidate;
if (_sharesToAdjust > 0) {
| _sharesToAdjust = _borrowerShares - _sharesToLiquidate;
if (_sharesToAdjust > 0) {
| 24,544 |
22 | // if(balanceOf[msg.sender] < _value) throw; | require(balanceOf[msg.sender] >= _value);
| require(balanceOf[msg.sender] >= _value);
| 25,477 |
11 | // Overflow desired | timeElapsed = blockTS - lastBlockTS;
| timeElapsed = blockTS - lastBlockTS;
| 23,151 |
97 | // solium-disable-next-line no-empty-blocks | while ((gasleft() > GAS_RESERVE) && (total_attempts++ < 50) && (attempts++ < 10) && !_reward()) {}
| while ((gasleft() > GAS_RESERVE) && (total_attempts++ < 50) && (attempts++ < 10) && !_reward()) {}
| 37,373 |
306 | // External function called to make the contract update weights according to plan Still works if we poke after the end of the period; also works if the weights don't change Resets if we are poking beyond the end, so that we can do it again / | function pokeWeights() external virtual logs lock needsBPool {
require(rights.canChangeWeights, "ERR_NOT_CONFIGURABLE_WEIGHTS");
// Delegate to library to save space
SmartPoolManager.pokeWeights(bPool, gradualUpdate);
}
| function pokeWeights() external virtual logs lock needsBPool {
require(rights.canChangeWeights, "ERR_NOT_CONFIGURABLE_WEIGHTS");
// Delegate to library to save space
SmartPoolManager.pokeWeights(bPool, gradualUpdate);
}
| 40,387 |
83 | // Enable or disable auctions | function setAuctionsEnabled(bool _auctionsEnabled) external onlyAuthority {
auctionsEnabled = _auctionsEnabled;
}
| function setAuctionsEnabled(bool _auctionsEnabled) external onlyAuthority {
auctionsEnabled = _auctionsEnabled;
}
| 52,190 |
348 | // Called to `msg.sender` after minting swaping from IUniswapV3Poolswap./In the implementation you must pay to the pool for swap./amount0 The amount of token0 due to the pool for the swap/amount1 The amount of token1 due to the pool for the swap/_data Any data passed through by the caller via the IUniswapV3PoolActionsswap call | function uniswapV3SwapCallback(
int256 amount0,
int256 amount1,
bytes calldata _data
| function uniswapV3SwapCallback(
int256 amount0,
int256 amount1,
bytes calldata _data
| 32,782 |
95 | // solium-disable-next-line indentation | require(isCancelled || (!isFinalized && hasEnded()) || isInvestmentAddressRefunded,
"contract has not ended, not cancelled and ico did not refunded");
address investor = msg.sender;
uint amount = investments[investor];
investor.transfer(amount);
delete investments[investor];
emit Refund(investor, amount);
| require(isCancelled || (!isFinalized && hasEnded()) || isInvestmentAddressRefunded,
"contract has not ended, not cancelled and ico did not refunded");
address investor = msg.sender;
uint amount = investments[investor];
investor.transfer(amount);
delete investments[investor];
emit Refund(investor, amount);
| 35,464 |
391 | // See {ERC20-_burn} and {ERC20-allowance}. / | function burnFrom(address account, uint256 amount) public override {
super.burnFrom(account, amount);
emit TokenBurnedFrom(msg.sender, account, amount);
}
| function burnFrom(address account, uint256 amount) public override {
super.burnFrom(account, amount);
emit TokenBurnedFrom(msg.sender, account, amount);
}
| 26,297 |
37 | // Luck TOKEN STARTS HERE / | contract LuckToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function LuckToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
address myAddress = this;
require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | contract LuckToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* Initializes contract with initial supply tokens to the creator of the contract */
function LuckToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
address myAddress = this;
require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | 52,128 |
4 | // depositedCount, exitedCount, collateralReturnedValue stored in 1 storage slot | ValidatorData private s_validatorData;
| ValidatorData private s_validatorData;
| 27,966 |
27 | // Initiates a new rebase operation, provided the minimum time period has elapsed.The supply adjustment equals (_totalSupplyDeviationFromTargetRate) / rebaseLag Where DeviationFromTargetRate is (TokenPriceOracleRate - targetPrice) / targetPrice and targetPrice is McapOracleRate / baseMcap / | function rebase() external {
require(msg.sender == orchestrator, "you are not the orchestrator");
require(inRebaseWindow(), "the rebase window is closed");
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "cannot rebase yet");
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
uint256 linkPrice;
bool linkPriceValid;
(linkPrice, linkPriceValid) = linkPriceOracle.getData();
require(linkPriceValid, "invalid mcap");
uint mcap = getLinkMarketCapUSD(linkPrice);
uint256 targetPrice = mcap.div(10_000_000_000);
uint tokenPrice = getTokenPriceFromUniswap();
if (tokenPrice > MAX_RATE) {
tokenPrice = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(tokenPrice, targetPrice);
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (supplyDelta == 0) {
emit LogRebase(epoch, tokenPrice, mcap, supplyDelta, now);
return;
}
if (supplyDelta > 0 && LBD.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(LBD.totalSupply())).toInt256Safe();
}
applyCharity(supplyDelta);
uint256 supplyAfterRebase = LBD.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, tokenPrice, mcap, supplyDelta, now);
}
| function rebase() external {
require(msg.sender == orchestrator, "you are not the orchestrator");
require(inRebaseWindow(), "the rebase window is closed");
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "cannot rebase yet");
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
uint256 linkPrice;
bool linkPriceValid;
(linkPrice, linkPriceValid) = linkPriceOracle.getData();
require(linkPriceValid, "invalid mcap");
uint mcap = getLinkMarketCapUSD(linkPrice);
uint256 targetPrice = mcap.div(10_000_000_000);
uint tokenPrice = getTokenPriceFromUniswap();
if (tokenPrice > MAX_RATE) {
tokenPrice = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(tokenPrice, targetPrice);
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (supplyDelta == 0) {
emit LogRebase(epoch, tokenPrice, mcap, supplyDelta, now);
return;
}
if (supplyDelta > 0 && LBD.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(LBD.totalSupply())).toInt256Safe();
}
applyCharity(supplyDelta);
uint256 supplyAfterRebase = LBD.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, tokenPrice, mcap, supplyDelta, now);
}
| 5,357 |
52 | // Shift pointer over to actual start of string. | nstr := add(nstr, k)
| nstr := add(nstr, k)
| 40,801 |
135 | // end liquidity lock functions |
function rescue() public payable onlyOwner returns (bool) {
uint256 stuckAmt = address(this).balance;
msg.sender.transfer(stuckAmt);
return true;
}
|
function rescue() public payable onlyOwner returns (bool) {
uint256 stuckAmt = address(this).balance;
msg.sender.transfer(stuckAmt);
return true;
}
| 31,669 |
108 | // Uses any WETH held in the SushiSwap trader to buy back BIOS which is sent to the Kernel | function biosBuyBack() external override onlyController {
if (
IERC20MetadataUpgradeable(
IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap))
.getWethTokenAddress()
).balanceOf(moduleMap.getModuleAddress(Modules.SushiSwapTrader)) > 0
) {
// Use all ETH sent to the SushiSwap trader to buy BIOS
ISushiSwapTrader(moduleMap.getModuleAddress(Modules.SushiSwapTrader))
.biosBuyBack();
// Use all BIOS transferred to the Kernel to increase bios rewards
IUserPositions(moduleMap.getModuleAddress(Modules.UserPositions))
.increaseBiosRewards();
}
}
| function biosBuyBack() external override onlyController {
if (
IERC20MetadataUpgradeable(
IIntegrationMap(moduleMap.getModuleAddress(Modules.IntegrationMap))
.getWethTokenAddress()
).balanceOf(moduleMap.getModuleAddress(Modules.SushiSwapTrader)) > 0
) {
// Use all ETH sent to the SushiSwap trader to buy BIOS
ISushiSwapTrader(moduleMap.getModuleAddress(Modules.SushiSwapTrader))
.biosBuyBack();
// Use all BIOS transferred to the Kernel to increase bios rewards
IUserPositions(moduleMap.getModuleAddress(Modules.UserPositions))
.increaseBiosRewards();
}
}
| 70,507 |
5 | // Renew a name. name The name of a domain. duration The duration to renew. / | function renew(string calldata name, uint256 duration) external;
| function renew(string calldata name, uint256 duration) external;
| 43,942 |
39 | // size of code at target address | uint codeLength;
| uint codeLength;
| 17,030 |
13 | // Counter underflow is impossible as _currentIndex does not decrement, and it is initialized to _startTokenId() | unchecked {
return _currentIndex - _startTokenId();
}
| unchecked {
return _currentIndex - _startTokenId();
}
| 24,868 |
5 | // Adopting pet function | function setTravel(string from, string to, uint when, uint prize, uint passengers) public payable returns (uint){
//require(msg.value == 5 * passengers && passengers >= 1, "");
travelsCount++;
travels.push(
Travel(travelsCount, from, to, when, prize, passengers, 1, 0, new address[](passengers+1), new address[](passengers+1), new address[](passengers+1), msg.sender, false, false));
return travelsCount;
}
| function setTravel(string from, string to, uint when, uint prize, uint passengers) public payable returns (uint){
//require(msg.value == 5 * passengers && passengers >= 1, "");
travelsCount++;
travels.push(
Travel(travelsCount, from, to, when, prize, passengers, 1, 0, new address[](passengers+1), new address[](passengers+1), new address[](passengers+1), msg.sender, false, false));
return travelsCount;
}
| 6,211 |
133 | // calculate the amount of PLY & PULP to transfer/mint. | function calcLockAmount(address account, uint256 amount)
external
view
returns (uint256 lockAmount, uint256 claimAmount)
| function calcLockAmount(address account, uint256 amount)
external
view
returns (uint256 lockAmount, uint256 claimAmount)
| 34,890 |
29 | // Unique Item URI | if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
| if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
| 55,723 |
11 | // Withdraw accumulated ETH fees recipient The recipient of the fees / | function withdrawFees(address recipient) external onlyOwner {
uint256 amount = address(this).balance;
(bool success,) = recipient.call{value: amount}("");
if (!success) {
revert ETHTransferFailed(recipient);
}
emit FeesWithdrawn(recipient, amount);
}
| function withdrawFees(address recipient) external onlyOwner {
uint256 amount = address(this).balance;
(bool success,) = recipient.call{value: amount}("");
if (!success) {
revert ETHTransferFailed(recipient);
}
emit FeesWithdrawn(recipient, amount);
}
| 41,704 |
0 | // The Constructor assigns the message sender to be `owner` | function Owned() { owner = msg.sender;}
| function Owned() { owner = msg.sender;}
| 19,967 |
350 | // Calculates `periodFee` of the option amount The option size period The option period in seconds (1 days <= period <= 90 days) / | ) internal view returns (uint256 iv) {
uint256 poolBalance = pool.totalBalance();
require(poolBalance > 0, "Pool Error: The pool is empty");
iv = impliedVolRate * period.sqrt();
uint256 lockedAmount = pool.lockedAmount() + amount;
uint256 utilization = (lockedAmount * 100e8) / poolBalance;
if (utilization > 40e8) {
iv += (iv * (utilization - 40e8) * utilizationRate) / 40e16;
}
}
| ) internal view returns (uint256 iv) {
uint256 poolBalance = pool.totalBalance();
require(poolBalance > 0, "Pool Error: The pool is empty");
iv = impliedVolRate * period.sqrt();
uint256 lockedAmount = pool.lockedAmount() + amount;
uint256 utilization = (lockedAmount * 100e8) / poolBalance;
if (utilization > 40e8) {
iv += (iv * (utilization - 40e8) * utilizationRate) / 40e16;
}
}
| 7,213 |
18 | // 托管操作权 | function _escrow(address _owner, uint256 _tokenId) internal {
nftContract.transferFrom(_owner, address(this), _tokenId);
}
| function _escrow(address _owner, uint256 _tokenId) internal {
nftContract.transferFrom(_owner, address(this), _tokenId);
}
| 30,649 |
20 | // ============ External Functions ============ //Get factory address returnaddress Factory address / | function factory()
external
view
returns (ISetFactory);
| function factory()
external
view
returns (ISetFactory);
| 2,259 |
240 | // Set the harvest window's start timestamp. Cannot overflow 64 bits on human timescales. | lastHarvestWindowStart = uint64(block.timestamp);
| lastHarvestWindowStart = uint64(block.timestamp);
| 19,958 |
161 | // calculate minted per contribution | LPPerUnitContributed = totalLPCreated.mul(1e8).div(totalUnitsContributed); // Stored as 1e8 more for round erorrs and change
| LPPerUnitContributed = totalLPCreated.mul(1e8).div(totalUnitsContributed); // Stored as 1e8 more for round erorrs and change
| 17,804 |
180 | // ERC1155TradableERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin, / | contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable, MinterRole, WhitelistAdminRole {
using Strings for string;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
constructor(
string memory _name,
string memory _symbol
) public {
name = _name;
symbol = _symbol;
}
function removeWhitelistAdmin(address account) public onlyOwner {
_removeWhitelistAdmin(account);
}
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function uri(uint256 _id) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id));
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* @param _maxSupply max supply allowed
* @param _initialSupply Optional amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Optional data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
uint256 _maxSupply,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyWhitelistAdmin returns (uint256 tokenId) {
require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public onlyMinter {
uint256 tokenId = _id;
require(tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached");
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
//
// ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
// if (address(proxyRegistry.proxies(_owner)) == _operator) {
// return true;
// }
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
| contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable, MinterRole, WhitelistAdminRole {
using Strings for string;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
constructor(
string memory _name,
string memory _symbol
) public {
name = _name;
symbol = _symbol;
}
function removeWhitelistAdmin(address account) public onlyOwner {
_removeWhitelistAdmin(account);
}
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function uri(uint256 _id) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id));
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* @param _maxSupply max supply allowed
* @param _initialSupply Optional amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Optional data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
uint256 _maxSupply,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyWhitelistAdmin returns (uint256 tokenId) {
require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public onlyMinter {
uint256 tokenId = _id;
require(tokenSupply[tokenId] < tokenMaxSupply[tokenId], "Max supply reached");
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
//
// ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
// if (address(proxyRegistry.proxies(_owner)) == _operator) {
// return true;
// }
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
| 13,284 |
214 | // Subtract 256 bit number from 512 bit number | assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
| assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
| 1,361 |
47 | // work was done | event WorkDone(uint projectId, address performer, WorkStatus status, string link);
| event WorkDone(uint projectId, address performer, WorkStatus status, string link);
| 15,127 |
108 | // Set locks & access control | function setClaimLock(bool lock) onlyOwner external {
_setClaimLock(lock);
}
| function setClaimLock(bool lock) onlyOwner external {
_setClaimLock(lock);
}
| 5,456 |
1 | // 调用者个数 | function allWorkersLength() external view returns(uint);
| function allWorkersLength() external view returns(uint);
| 3,813 |
497 | // Update total delegated to this SP | spDelegateInfo[_serviceProvider].totalDelegatedStake = (
spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease)
);
| spDelegateInfo[_serviceProvider].totalDelegatedStake = (
spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease)
);
| 41,382 |
14 | // Convert a Date Token Index to a Julian Date. / | function _dtiToJD(uint256 dateTokenIndex) private pure returns (JulianDate memory) {
int256 jdn = int256(dateTokenIndex) - int256(_dtiMidpoint);
return JulianDate(jdn, 5);
}
| function _dtiToJD(uint256 dateTokenIndex) private pure returns (JulianDate memory) {
int256 jdn = int256(dateTokenIndex) - int256(_dtiMidpoint);
return JulianDate(jdn, 5);
}
| 29,430 |
10 | // Public function for checking whitelist eligibility.Called in the presale() function _to verify address is eligible for presale / | function whitelistEligible(address _to)
public
view
returns (bool)
| function whitelistEligible(address _to)
public
view
returns (bool)
| 5,703 |
37 | // Skip the first word, which is used to store the length | let resultsOffsets := add(results, 0x20)
| let resultsOffsets := add(results, 0x20)
| 14,808 |
52 | // Approves an ERC721 order on-chain. After pre-signing/the order, the `PRESIGNED` signature type will become/valid for that order and signer./order An ERC721 order. | function preSignERC721Order(LibNFTOrder.ERC721Order memory order)
public
override
| function preSignERC721Order(LibNFTOrder.ERC721Order memory order)
public
override
| 32,103 |
45 | // //Token deposit function for `batch()` into strategies. | function depositToken(IERC20 token, uint256 amount) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
| function depositToken(IERC20 token, uint256 amount) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
| 10,692 |
79 | // 6% Transaction Fees - 4% goes to marketing, 2% goes to development | uint256 public developmentFee = 2;
uint256 public marketingFee = 4;
uint256 public totalFees = developmentFee.add(marketingFee);
address public _marketingWalletAddress = 0xEca5D26ACdBC749c180b336Aa586a0DcC53527Ea;
address public _developmentWalletAddress = 0x16F8Eb6A2F44A159f541176a9A0D3a7e779cD170;
address public presaleAddress = address(0);
| uint256 public developmentFee = 2;
uint256 public marketingFee = 4;
uint256 public totalFees = developmentFee.add(marketingFee);
address public _marketingWalletAddress = 0xEca5D26ACdBC749c180b336Aa586a0DcC53527Ea;
address public _developmentWalletAddress = 0x16F8Eb6A2F44A159f541176a9A0D3a7e779cD170;
address public presaleAddress = address(0);
| 52,989 |
79 | // The address that will receive this contracts deposit, should match the original senders | assert(salesAgents[msg.sender].depositAddress == _sender);
| assert(salesAgents[msg.sender].depositAddress == _sender);
| 51,206 |
1 | // mapping(uint256 => mapping(uint16 => EnumerableSet.Bytes32Set))private gameBetRooms; | mapping(uint256 => mapping(uint16 => bytes32[])) private gameBetRoomsArr;
mapping(uint256 => mapping(uint16 => mapping(bytes32 => bool)))
private gameBetRoomsArrState;
mapping(address => mapping(uint256 => bool)) public usedNonce;
| mapping(uint256 => mapping(uint16 => bytes32[])) private gameBetRoomsArr;
mapping(uint256 => mapping(uint16 => mapping(bytes32 => bool)))
private gameBetRoomsArrState;
mapping(address => mapping(uint256 => bool)) public usedNonce;
| 7,315 |
78 | // Converts the amount of foreign tokens into the equivalent amount of home tokens._value amount of foreign tokens. return equivalent amount of home tokens./ | function _shiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, decimalShift());
}
| function _shiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, decimalShift());
}
| 50,388 |
5 | // Reset token approval of strategy. Called when updating strategy. | function resetApproval() external virtual onlyController {
address strategy = controller.strategy(address(this));
token.safeApprove(strategy, 0);
// IERC20(IStrategy(strategy).token()).safeApprove(strategy, 0); //Same as in approveToken()
}
| function resetApproval() external virtual onlyController {
address strategy = controller.strategy(address(this));
token.safeApprove(strategy, 0);
// IERC20(IStrategy(strategy).token()).safeApprove(strategy, 0); //Same as in approveToken()
}
| 21,369 |
102 | // calc the value of paramK. The formula for this can be referred in the AMM specs / | function _calcParamK() internal view returns (uint256 paramK) {
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
readReserveData();
paramK = Math
.rpow(xytBalance.toFP(), xytWeight)
.rmul(Math.rpow(tokenBalance.toFP(), tokenWeight))
.toInt();
}
| function _calcParamK() internal view returns (uint256 paramK) {
(uint256 xytBalance, uint256 tokenBalance, uint256 xytWeight, uint256 tokenWeight) =
readReserveData();
paramK = Math
.rpow(xytBalance.toFP(), xytWeight)
.rmul(Math.rpow(tokenBalance.toFP(), tokenWeight))
.toInt();
}
| 38,846 |
346 | // If Uses withdraws all the money, the remaining ctoken is profit. | if (totalUnderlyToken == 0 && frozenUnderlyToken == 0) {
if (cTokens > 0) {
uint256 redeemState = ICompound(lpToken).redeem(cTokens);
require(
redeemState == 0,
"SupplyTreasuryFundForCompound: !redeemState"
);
if (isErc20) {
| if (totalUnderlyToken == 0 && frozenUnderlyToken == 0) {
if (cTokens > 0) {
uint256 redeemState = ICompound(lpToken).redeem(cTokens);
require(
redeemState == 0,
"SupplyTreasuryFundForCompound: !redeemState"
);
if (isErc20) {
| 13,978 |
3 | // Integer division of two numbers, truncating the quotient. / | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| 1,351 |
288 | // POSITION FUNCTIONS // Requests to transfer ownership of the caller's current position to a new sponsor address.Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. The liveness length is the same as the withdrawal liveness. / | function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
| function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
| 34,679 |
27 | // UpgradeabilityProxy This contract represents a proxy where the implementation address to which it will delegate can be upgraded / | contract UpgradeabilityProxy is UpgradeabilityStorage {
/**
* @dev Constructor function
*/
constructor(uint256 _version) public {
registry = IRegistry(msg.sender);
upgradeTo(_version);
}
/**
* @dev Upgrades the implementation to the requested version
* @param _version representing the version name of the new implementation to be set
*/
function upgradeTo(uint256 _version) public {
require(msg.sender == address(registry),"ERR_ONLY_REGISTRERY_CAN_CALL");
_implementation = registry.getVersion(_version);
}
}
| contract UpgradeabilityProxy is UpgradeabilityStorage {
/**
* @dev Constructor function
*/
constructor(uint256 _version) public {
registry = IRegistry(msg.sender);
upgradeTo(_version);
}
/**
* @dev Upgrades the implementation to the requested version
* @param _version representing the version name of the new implementation to be set
*/
function upgradeTo(uint256 _version) public {
require(msg.sender == address(registry),"ERR_ONLY_REGISTRERY_CAN_CALL");
_implementation = registry.getVersion(_version);
}
}
| 22,765 |
3 | // Check balance of contract beforehand to avoid gas costs | require(address(this).balance > 0, "All funds already distributed!");
payable(admin).transfer((address(this).balance * adminFee) / 1000);
uint amountToPay = address(this).balance / vdrList.length;
for (uint i = 0; i < vdrList.length; i++)
payable(vdrList[i].payAddr).transfer(amountToPay);
| require(address(this).balance > 0, "All funds already distributed!");
payable(admin).transfer((address(this).balance * adminFee) / 1000);
uint amountToPay = address(this).balance / vdrList.length;
for (uint i = 0; i < vdrList.length; i++)
payable(vdrList[i].payAddr).transfer(amountToPay);
| 31,279 |
4 | // Emit when making a deposittoken Depositing token addressaccount Account addressamount Deposit amount, in wei / | event LogDeposit(address indexed token, address indexed account, uint256 amount);
| event LogDeposit(address indexed token, address indexed account, uint256 amount);
| 4,509 |
5 | // TODO: This shit is retarded. Why can I not just access the (add etc.) function directly in the Datastore contract even if it is public in the AddressSet library? | // function assignRole( Role storage self, address member ) internal {
// self.members.add( member );
// }
| // function assignRole( Role storage self, address member ) internal {
// self.members.add( member );
// }
| 28,322 |
63 | // This modifier uses the isPopulous method in the AccessManager contract AM to determine whether the msg.sender address is populous. | modifier onlyPopulous {
require(AM.isPopulous(msg.sender) == true);
_;
}
| modifier onlyPopulous {
require(AM.isPopulous(msg.sender) == true);
_;
}
| 22,162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.