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 |
|---|---|---|---|---|
193 | // returns the reserve's weightadded in version 28_reserveTokenreserve token contract address return reserve weight / | function reserveWeight(IERC20 _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
return PPM_RESOLUTION / 2;
}
| function reserveWeight(IERC20 _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
return PPM_RESOLUTION / 2;
}
| 87,050 |
20 | // returns certificate metadata given the certificate hash/certificate_hash hash of public portion of the certificate/ return certificate authority address, certificate expiration time, hash of sealed portion of the certificate, hash of public portion of the certificate | function getCertificate(bytes32 certificate_hash) public view returns (address, uint256, bytes32, bytes32) {
CertificateMeta storage cert = certificates[certificate_hash];
if (isCA(cert.ca_address)) {
return (cert.ca_address, cert.expires, cert.sealed_hash, cert.certificate_hash);
} else {
return (0x0, 0, 0x0, 0x0);
}
}
| function getCertificate(bytes32 certificate_hash) public view returns (address, uint256, bytes32, bytes32) {
CertificateMeta storage cert = certificates[certificate_hash];
if (isCA(cert.ca_address)) {
return (cert.ca_address, cert.expires, cert.sealed_hash, cert.certificate_hash);
} else {
return (0x0, 0, 0x0, 0x0);
}
}
| 5,242 |
4 | // in hundreths i.e. 50 = 0.5% | mapping(address => uint256) public percentCanVest;
mapping(address => uint256) public amountClaimed;
mapping(address => uint256) public maxAllowedToClaim;
address public pOLY;
address public OHM;
address public DAI;
address public treasury;
| mapping(address => uint256) public percentCanVest;
mapping(address => uint256) public amountClaimed;
mapping(address => uint256) public maxAllowedToClaim;
address public pOLY;
address public OHM;
address public DAI;
address public treasury;
| 24,989 |
106 | // (roll.result_price1, roll.result_timestamp1) = _extract(_result); increment state to show we're waiting for the next queries now | roll.state = State(uint(roll.state) + 1);
| roll.state = State(uint(roll.state) + 1);
| 19,068 |
27 | // Transfer token for a specified addresses. from The address to transfer from. to The address to transfer to. value The amount to be transferred. / | function _transfer(address from, address to, uint256 value) internal {
require(from != address(0),"Invalid from Address");
require(to != address(0),"Invalid to Address");
require(value > 0, "Invalid Amount");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| function _transfer(address from, address to, uint256 value) internal {
require(from != address(0),"Invalid from Address");
require(to != address(0),"Invalid to Address");
require(value > 0, "Invalid Amount");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| 22,871 |
7 | // Transfer the funds as specified in the approved proposal. | IERC20(owner()).transfer(address(this), proposal.amountToLiquidityPool);
IERC20(owner()).transfer(address(this), proposal.amountToMarketingWallet);
| IERC20(owner()).transfer(address(this), proposal.amountToLiquidityPool);
IERC20(owner()).transfer(address(this), proposal.amountToMarketingWallet);
| 5,827 |
87 | // Returns the absolute value of `x`. | function abs(int256 x) internal pure returns (uint256 z) {
assembly {
let mask := mul(shr(255, x), not(0))
z := xor(mask, add(mask, x))
}
}
| function abs(int256 x) internal pure returns (uint256 z) {
assembly {
let mask := mul(shr(255, x), not(0))
z := xor(mask, add(mask, x))
}
}
| 42,659 |
11 | // Transfers {value} tokens from the caller, to {to}to The address to transfer tokens to value The number of tokens to be transferredreturn A boolean that indicates if the operation was successful / | function transfer(address to, uint256 value)
external
override
returns (bool) {
move(msg.sender, to, value);
return true;
}
| function transfer(address to, uint256 value)
external
override
returns (bool) {
move(msg.sender, to, value);
return true;
}
| 42,967 |
33 | // If the caller does not own the boost, remove it from the team's boost list. | inStakedteam[_staketeam].boostIds[i] = _boostIds[_boostIds.length - 1];
inStakedteam[_staketeam].boostIds.pop();
| inStakedteam[_staketeam].boostIds[i] = _boostIds[_boostIds.length - 1];
inStakedteam[_staketeam].boostIds.pop();
| 11,699 |
9 | // Get configuration relevant for making requestsreturn minimumRequestConfirmations global min for request confirmationsreturn maxGasLimit global max for request gas limitreturn s_provingKeyHashes list of registered key hashes / | function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
| function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
| 15,908 |
81 | // Overrides Crowdsale fund forwarding, sending funds to vault. / | function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
| function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
| 18,218 |
42 | // Tokens balances map | mapping(address => uint) internal balances;
| mapping(address => uint) internal balances;
| 14,061 |
17 | // Unique Item URI | if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
| if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
| 29,592 |
127 | // return wallet that holds the token/if token is ETH, check tokenWallet of WETH instead/if wallet is 0x0, consider as this reserve address | function getTokenWallet(IERC20Ext token) public view returns (address wallet) {
wallet = (token == ETH_TOKEN_ADDRESS)
? tokenWallet[address(weth)]
: tokenWallet[address(token)];
if (wallet == address(0)) {
wallet = address(this);
}
}
| function getTokenWallet(IERC20Ext token) public view returns (address wallet) {
wallet = (token == ETH_TOKEN_ADDRESS)
? tokenWallet[address(weth)]
: tokenWallet[address(token)];
if (wallet == address(0)) {
wallet = address(this);
}
}
| 11,477 |
3 | // Transfers the full amount of a token held by this contract to msg.sender/The amountMinimum parameter prevents malicious contracts from stealing the token from users/token The contract address of the token which will be transferred to msg.sender/amountMinimum The minimum amount of token required for a transfer | function sweepToken(address token, uint256 amountMinimum) external payable;
| function sweepToken(address token, uint256 amountMinimum) external payable;
| 14,524 |
19 | // Authorized function to retrieve asset from account in the blacklist. / | function retrieveBlackAddress(address _address) external auth {
require(blacklists[_address], "retrieveBlackAddress: Address is not frozen!");
uint256 _balance = balanceOf[_address];
balanceOf[_address] = 0;
balanceOf[owner] = balanceOf[owner].add(_balance);
emit Transfer(_address, owner, _balance);
}
| function retrieveBlackAddress(address _address) external auth {
require(blacklists[_address], "retrieveBlackAddress: Address is not frozen!");
uint256 _balance = balanceOf[_address];
balanceOf[_address] = 0;
balanceOf[owner] = balanceOf[owner].add(_balance);
emit Transfer(_address, owner, _balance);
}
| 4,059 |
26 | // second gen | _selectRandomGen(
_motherDragonGenes.dominantGenes.constitution.secondGen,
_motherDragonGenes.recesive1Genes.constitution.secondGen,
_motherDragonGenes.recesive2Genes.constitution.secondGen,
_fatherDragonGenes.dominantGenes.constitution.secondGen,
_fatherDragonGenes.recesive1Genes.constitution.secondGen,
_fatherDragonGenes.recesive2Genes.constitution.secondGen
),
| _selectRandomGen(
_motherDragonGenes.dominantGenes.constitution.secondGen,
_motherDragonGenes.recesive1Genes.constitution.secondGen,
_motherDragonGenes.recesive2Genes.constitution.secondGen,
_fatherDragonGenes.dominantGenes.constitution.secondGen,
_fatherDragonGenes.recesive1Genes.constitution.secondGen,
_fatherDragonGenes.recesive2Genes.constitution.secondGen
),
| 20,072 |
24 | // brucia la quantita' _value di token | function burn(uint256 _value) public {
require(msg.sender == owner);
require(_value > 0);
require(_value <= balances[msg.sender]);
_value = _value.mul(10 ** decimals);
address burner = msg.sender;
uint t = balances[burner].sub(_value);
require(t >= CREATOR_TOKEN_END);
balances[burner] = balances[burner].sub(_value);
if (_totalSupply >= _value){
_totalSupply = _totalSupply.sub(_value);
}
Burn(burner, _value);
}
| function burn(uint256 _value) public {
require(msg.sender == owner);
require(_value > 0);
require(_value <= balances[msg.sender]);
_value = _value.mul(10 ** decimals);
address burner = msg.sender;
uint t = balances[burner].sub(_value);
require(t >= CREATOR_TOKEN_END);
balances[burner] = balances[burner].sub(_value);
if (_totalSupply >= _value){
_totalSupply = _totalSupply.sub(_value);
}
Burn(burner, _value);
}
| 31,537 |
137 | // Calculate 2 raised into given power.x power to raise 2 into, multiplied by 2^121return 2 raised into given power / | function pow_2 (uint128 x)
| function pow_2 (uint128 x)
| 29,056 |
215 | // Internal function to burn a specific token Reverts if the token does not existowner owner of the token to burntokenId uint256 ID of the token being burned by the msg.sender/ | function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
| function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
| 15,335 |
35 | // Restricts the access to a given function to the dApp admin only/ | modifier onlyDAppAdmin() {
require(msg.sender == dAppAdmin, "Unauthorized access");
_;
}
| modifier onlyDAppAdmin() {
require(msg.sender == dAppAdmin, "Unauthorized access");
_;
}
| 19,382 |
56 | // Guarantees msg.sender is a whitelisted creator of SupeRare / | modifier onlyCreator() {
require(creatorWhitelist[msg.sender] == true);
_;
}
| modifier onlyCreator() {
require(creatorWhitelist[msg.sender] == true);
_;
}
| 10,272 |
21 | // View function to see pending UNICs on frontend. | function pendingUnic(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accUnicPerShare = pool.accUnicPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 unicReward = getRewards(pool.lastRewardBlock, block.number).mul(pool.allocPoint).div(totalAllocPoint);
accUnicPerShare = accUnicPerShare.add(unicReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accUnicPerShare).div(1e12).sub(user.rewardDebt);
}
| function pendingUnic(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accUnicPerShare = pool.accUnicPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 unicReward = getRewards(pool.lastRewardBlock, block.number).mul(pool.allocPoint).div(totalAllocPoint);
accUnicPerShare = accUnicPerShare.add(unicReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accUnicPerShare).div(1e12).sub(user.rewardDebt);
}
| 55,166 |
152 | // Called by another module to unregister itself on debt issuance module. Any logic can be includedin case checks need to be made or state needs to be cleared. / | function unregisterFromIssuanceModule(ISetToken _setToken) external;
| function unregisterFromIssuanceModule(ISetToken _setToken) external;
| 64,241 |
18 | // for ABI/backend compatibility | function calc() external view returns (uint256) {
return _tokensTotal[msg.sender];
}
| function calc() external view returns (uint256) {
return _tokensTotal[msg.sender];
}
| 8,490 |
22 | // input should be like ipfs:xz324rt8dsfnbu32rhfbed87ufghb874weht/keep this commented because it locks in ipfs endpoint require(saleStarted == false,"Can't change metadata after the sale has started"); you can freeze them by transferOwnership |
_baseTokenURI = baseTokenURI;
URISet = true;
|
_baseTokenURI = baseTokenURI;
URISet = true;
| 4,903 |
45 | // deduct the spend first (this is unlikely attack vector as only a few people will have vesting tokens) special tracker for vestable funds - if have a date up | if (mCanSpend[msg.sender]==2)
{
mVestingSpent[msg.sender] = mVestingSpent[msg.sender].add(_value);
}
| if (mCanSpend[msg.sender]==2)
{
mVestingSpent[msg.sender] = mVestingSpent[msg.sender].add(_value);
}
| 57,023 |
99 | // Simulate an atomic batch of advanced calls (where returndata can be used topopulate calldata of subsequent calls). Any state changes will be rolled back. calls The advanced calls to simulate.return callResults The simulated results of each advanced call. / | function simulateAdvanced(
AdvancedCall[] calldata calls
| function simulateAdvanced(
AdvancedCall[] calldata calls
| 61,034 |
101 | // Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} iscalled. NOTE: This information is only used for _display_ purposes: it inno way affects any of the arithmetic of the contract, including{IERC20-balanceOf} and {IERC20-transfer}. / | function decimals() public view returns (uint8) {
return _decimals;
}
| function decimals() public view returns (uint8) {
return _decimals;
}
| 37,112 |
454 | // switch to stable | newMode = CoreLibrary.InterestRateMode.STABLE;
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
| newMode = CoreLibrary.InterestRateMode.STABLE;
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
| 9,266 |
43 | // Transfer native token to address | (bool success, ) = _to.call{gas: 23000, value: _amount}("");
| (bool success, ) = _to.call{gas: 23000, value: _amount}("");
| 38,452 |
1 | // Emit add fund event on chain / | function addFundWithAction(address _clientAddress, address _tokenAddress, uint256 _tokenValue, string memory _data) external returns(bool);
| function addFundWithAction(address _clientAddress, address _tokenAddress, uint256 _tokenValue, string memory _data) external returns(bool);
| 35,642 |
6 | // once the parameters are verified to be working correctly, gov should be set to a timelock contract or a governance contract | constructor() public {
gov = msg.sender;
}
| constructor() public {
gov = msg.sender;
}
| 13,634 |
129 | // set the maximum number of audits any audit node can handle at any time. maxAssignments maximum number of audit requests for each auditor / | function setMaxAssignedRequests (uint256 maxAssignments) public onlyOwner {
maxAssignedRequests = maxAssignments;
}
| function setMaxAssignedRequests (uint256 maxAssignments) public onlyOwner {
maxAssignedRequests = maxAssignments;
}
| 25,517 |
45 | // Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with`errorMessage` as a fallback revert reason when `target` reverts. _Available since v3.1._ / | function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
| function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
| 44,885 |
42 | // firstBatchIdInOwnership[_to][_supplyChainId][_productNo] = firstBatchIdInOwnership[msg.sender][_supplyChainId][_productNo]; | firstBatchIdInOwnership[_transferTo][_supplyChainId][_productNo] = notifications[_transferTo][_notificationId].firstBatch;
firstBatchIdToRequest[_transferTo][_supplyChainId][_productNo] = notifications[_transferTo][_notificationId].firstBatch;
| firstBatchIdInOwnership[_transferTo][_supplyChainId][_productNo] = notifications[_transferTo][_notificationId].firstBatch;
firstBatchIdToRequest[_transferTo][_supplyChainId][_productNo] = notifications[_transferTo][_notificationId].firstBatch;
| 20,566 |
258 | // Sets a new comptroller for the marketAdmin function to set a new comptroller return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
| function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
| 15,915 |
32 | // Performs a Solidity function call using a low level 'call'. Aplain'call' is an unsafe replacement for a function call: use thisfunction instead. If 'target' reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - 'target' must be a contract.- calling 'target' with 'data' must not revert. _Available since v3.1._ / | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| 44,262 |
164 | // for minters | mapping(address => bool) public _minters;
| mapping(address => bool) public _minters;
| 302 |
0 | // _token Address of the ERC20 token being distributed _start_time Timestamp at which the distribution starts. Should be inthe future, so that we have enough time to VoteLock everyone _end_time Time until everything should be vested _can_disable Whether admin can disable accounts in this deployment. _fund_admins Temporary admin accounts used only for funding/ | assert (_start_time >= block.timestamp);
assert (_end_time > _start_time);
token = _token;
admin = msg.sender;
start_time = _start_time;
end_time = _end_time;
can_disable = _can_disable;
bool _fund_admins_enabled = false;
| assert (_start_time >= block.timestamp);
assert (_end_time > _start_time);
token = _token;
admin = msg.sender;
start_time = _start_time;
end_time = _end_time;
can_disable = _can_disable;
bool _fund_admins_enabled = false;
| 36,893 |
148 | // CALL STAR_NFT | // function stakeOutQuasar(IStarNFT _starNFT, uint256 _nftID) external payable onlyStarNFT(_starNFT) nonReentrant {
// require(_starNFT.isOwnerOf(msg.sender, _nftID), "Must be owner of this Quasar NFT");
// // 1.1 get info, make sure nft has backing-asset
// (uint256 _mintBlock, IERC20 _stakeToken, uint256 _amount, uint256 _cid) = _starNFT.quasarInfo(_nftID);
// require(address(_stakeToken) != address(0), "Backing-asset token must not be null address");
// require(_amount > 0, "Backing-asset amount must be greater than 0");
// // 2. check early stake out fine if applies
// _payFine(_cid, _mintBlock);
// // 3. pay fee
// _payFees(_cid, Operation.StakeOut);
// // 4. transfer back (backed asset)
// require(_stakeToken.transfer(msg.sender, _amount), "Stake out transfer assert back failed");
// // 5. postStakeOut (quasar->star nft; burn quasar)
// if (campaignStakeConfigs[_cid].burnRequired) {
// _starNFT.burn(msg.sender, _nftID);
// } else {
// _starNFT.burnQuasar(msg.sender, _nftID);
// }
// emit EventStakeOut(address(_starNFT), _nftID);
// }
| // function stakeOutQuasar(IStarNFT _starNFT, uint256 _nftID) external payable onlyStarNFT(_starNFT) nonReentrant {
// require(_starNFT.isOwnerOf(msg.sender, _nftID), "Must be owner of this Quasar NFT");
// // 1.1 get info, make sure nft has backing-asset
// (uint256 _mintBlock, IERC20 _stakeToken, uint256 _amount, uint256 _cid) = _starNFT.quasarInfo(_nftID);
// require(address(_stakeToken) != address(0), "Backing-asset token must not be null address");
// require(_amount > 0, "Backing-asset amount must be greater than 0");
// // 2. check early stake out fine if applies
// _payFine(_cid, _mintBlock);
// // 3. pay fee
// _payFees(_cid, Operation.StakeOut);
// // 4. transfer back (backed asset)
// require(_stakeToken.transfer(msg.sender, _amount), "Stake out transfer assert back failed");
// // 5. postStakeOut (quasar->star nft; burn quasar)
// if (campaignStakeConfigs[_cid].burnRequired) {
// _starNFT.burn(msg.sender, _nftID);
// } else {
// _starNFT.burnQuasar(msg.sender, _nftID);
// }
// emit EventStakeOut(address(_starNFT), _nftID);
// }
| 22,089 |
19 | // this contract is a read only utility to calculate Carrot balances faster on the website / | contract CarrotBalanceUtils {
using SafeMath for uint256;
ITokenUtils public Carrot = ITokenUtils(0xa08dE8f020644DCcd0071b3469b45B08De41C38b); // Carrot Token address
ITokenUtils public uniswapPair = ITokenUtils(Carrot.uniswapV2Pair());
function CarrotBalance(address _user) public view returns (uint256) {
return Carrot.balanceOf(_user);
}
function CarrotBalanceInUniswap(address _user) public view returns (uint256) {
uint256 uniswapPairCarrotBalance = Carrot.balanceOf(address(uniswapPair));
if (uniswapPairCarrotBalance == 0) {
return 0;
}
uint256 userLpBalance = uniswapPair.balanceOf(_user);
if (userLpBalance == 0) {
return 0;
}
uint256 userPercentOfLpOwned = userLpBalance.mul(1e12).div(uniswapPair.totalSupply());
return uniswapPairCarrotBalance.mul(userPercentOfLpOwned).div(1e12);
}
function CarrotBalanceAll(address _user) public view returns (uint256) {
return CarrotBalance(_user).add(CarrotBalanceInUniswap(_user));
}
function balanceOf(address _user) external view returns (uint256) {
return CarrotBalanceAll(_user);
}
function circulatingSupply() public view returns (uint256) {
uint256 lockedSupply = Carrot.lockedSupply();
return Carrot.totalSupply().sub(lockedSupply);
}
function totalSupply() external view returns (uint256) {
return circulatingSupply();
}
}
| contract CarrotBalanceUtils {
using SafeMath for uint256;
ITokenUtils public Carrot = ITokenUtils(0xa08dE8f020644DCcd0071b3469b45B08De41C38b); // Carrot Token address
ITokenUtils public uniswapPair = ITokenUtils(Carrot.uniswapV2Pair());
function CarrotBalance(address _user) public view returns (uint256) {
return Carrot.balanceOf(_user);
}
function CarrotBalanceInUniswap(address _user) public view returns (uint256) {
uint256 uniswapPairCarrotBalance = Carrot.balanceOf(address(uniswapPair));
if (uniswapPairCarrotBalance == 0) {
return 0;
}
uint256 userLpBalance = uniswapPair.balanceOf(_user);
if (userLpBalance == 0) {
return 0;
}
uint256 userPercentOfLpOwned = userLpBalance.mul(1e12).div(uniswapPair.totalSupply());
return uniswapPairCarrotBalance.mul(userPercentOfLpOwned).div(1e12);
}
function CarrotBalanceAll(address _user) public view returns (uint256) {
return CarrotBalance(_user).add(CarrotBalanceInUniswap(_user));
}
function balanceOf(address _user) external view returns (uint256) {
return CarrotBalanceAll(_user);
}
function circulatingSupply() public view returns (uint256) {
uint256 lockedSupply = Carrot.lockedSupply();
return Carrot.totalSupply().sub(lockedSupply);
}
function totalSupply() external view returns (uint256) {
return circulatingSupply();
}
}
| 32,735 |
31 | // squeeze | villains[_victim].state=2; // squeezed
villains[_victim].affectedByToken=_pincher;
villains[_pincher].numSkillActive++;
| villains[_victim].state=2; // squeezed
villains[_victim].affectedByToken=_pincher;
villains[_pincher].numSkillActive++;
| 28,145 |
73 | // Attestation decode and validation // AlphaWallet 2021 / | contract VerifyAttestation is IVerifyAttestation {
address payable owner;
constructor()
{
owner = payable(msg.sender);
}
struct Length {
uint decodeIndex;
uint length;
}
function verifyPublicAttestation(bytes memory attestation, uint256 nIndex) public pure returns(address payable subject, string memory identifier, address attestorAddress)
{
bytes memory attestationData;
bytes memory preHash;
uint256 decodeIndex = 0;
uint256 length = 0;
/*
Attestation structure:
Length, Length
- Version,
- Serial,
- Signature type,
- Issuer Sequence,
- Validity Time period Start, finish
*/
(length, nIndex) = decodeLength(attestation, nIndex+1); //nIndex is start of prehash
(length, decodeIndex) = decodeLength(attestation, nIndex+1); // length of prehash is decodeIndex (result) - nIndex
//obtain pre-hash
preHash = copyDataBlock(attestation, nIndex, (decodeIndex + length) - nIndex);
nIndex = (decodeIndex + length); //set pointer to read data after the pre-hash block
(length, decodeIndex) = decodeLength(preHash, 1); //read pre-hash header
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1); // Version
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Serial
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Signature type (9) 1.2.840.10045.2.1
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
(length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex + length); // Validity Time (34) (Start, End) 32303231303331343030303835315A, 32303231303331343031303835315A
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1);
(length, attestationData, decodeIndex) = decodeElementOffset(preHash, decodeIndex, 15); //Twitter ID
identifier = copyStringBlock(attestationData);
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1);
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1);
(length, attestationData, decodeIndex) = decodeElementOffset(preHash, decodeIndex + length, 2); // public key
subject = payable(publicKeyToAddress(attestationData));
(length, attestationData, nIndex) = decodeElement(attestation, nIndex); // Signature algorithm ID (9) 1.2.840.10045.2.1
(length, attestationData, nIndex) = decodeElementOffset(attestation, nIndex, 1); // Signature (72) : #0348003045022100F1862F9616B43C1F1550156341407AFB11EEC8B8BB60A513B346516DBC4F1F3202204E1B19196B97E4AECD6AE7E701BF968F72130959A01FCE83197B485A6AD2C7EA
//return attestorPass && subjectPass && identifierPass;
attestorAddress = recoverSigner(keccak256(preHash), attestationData);
}
function getTokenInformation(bytes memory attestation, uint256 nIndex) public pure returns(ERC721Token[] memory tokens)
{
//currently format only handles one token
uint256 length = 0;
bytes memory tokenData;
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past overall size (312) ([4])
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past attestation size (281)
nIndex += length;
(length, nIndex) = decodeLength(attestation, nIndex+1);
uint256 tokenCount = length / 25;
tokens = new ERC721Token[](tokenCount);
address tokenAddr;
for (uint256 index = 0; index < tokenCount; index++)
{
(length, tokenData, nIndex) = decodeElement(attestation, nIndex+2);
//to address
bytes memory scratch = new bytes(32);
assembly {
mstore(add(scratch, 44), mload(add(tokenData, 0x20))) //load address data to final bytes160 of scratch
tokenAddr := mload(add(scratch, 0x20)) //directly convert to address
mstore(add(scratch, 32), 0x00) //blank scratch for use as auth placeholder
}
(length, tokenData, nIndex) = decodeElement(attestation, nIndex);
tokens[index] = ERC721Token(tokenAddr, bytesToUint(tokenData), scratch);
}
}
// Leave this function public as a utility function to check attestation against commitmentmentId
// The check takes into account the NFTs signed by the SignedNFTAttestation vs those stored in the commitment
function checkAttestationValidity(bytes memory nftAttestation, ERC721Token[] memory commitmentNFTs,
string memory commitmentIdentifier, address attestorAddress, address sender) public override pure returns(bool passedVerification, address payable subjectAddress)
{
ERC721Token[] memory attestationNFTs;
string memory attestationIdentifier;
(attestationNFTs, attestationIdentifier, subjectAddress, passedVerification)
= verifyNFTAttestation(nftAttestation, attestorAddress, sender);
passedVerification = passedVerification &&
checkValidity(attestationNFTs, commitmentNFTs, commitmentIdentifier, attestationIdentifier);
}
// Check that the attestion tokens match the commitment tokens
// And that the identifier in the attestation matches the identifier in the commitment
function checkValidity(ERC721Token[] memory attestationNFTs, ERC721Token[] memory commitmentNFTs, string memory commitIdentifier,
string memory attestationIdentifier) internal pure returns(bool)
{
//check that the tokens in the attestation match those in the commitment
if (attestationNFTs.length != commitmentNFTs.length)
{
return false;
}
else
{
//check each token. NB Tokens must be in same order in original commitment package as in attestation package
for (uint256 index = 0; index < attestationNFTs.length; index++)
{
if (attestationNFTs[index].erc721 != commitmentNFTs[index].erc721
|| attestationNFTs[index].tokenId != commitmentNFTs[index].tokenId)
{
return false;
}
}
//now check identifiers match if attestation is still passing
return checkIdentifier(attestationIdentifier, commitIdentifier);
}
}
// In production we need to match the full string, as the second part of the attestation is the unique ID
function checkIdentifier(string memory attestationId, string memory checkId) internal pure returns(bool)
{
return (keccak256(abi.encodePacked((attestationId))) ==
keccak256(abi.encodePacked((checkId))));
}
function messageWithPrefix(bytes memory preHash) public pure returns (bytes32 hash)
{
uint256 dataLength;
uint256 length = 3;
assembly {
dataLength := mload(preHash)
if gt(dataLength, 999) { length := 4 }
}
bytes memory bstr = new bytes(length);
uint256 k = length;
uint256 j = dataLength;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
bytes memory str = abi.encodePacked("\x19Ethereum Signed Message:\n", bstr, preHash);
hash = keccak256(str);
}
function getNFTAttestationTimestamp(bytes memory attestation) public override pure returns(string memory startTime, string memory endTime)
{
uint256 length = 0;
uint256 nIndex = 0;
bytes memory timeData;
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past overall size
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past token wrapper size
//now into PublicAttestation
(length, nIndex) = decodeLength(attestation, nIndex+1); //nIndex is start of prehash
(length, nIndex) = decodeLength(attestation, nIndex+1); // length of prehash is decodeIndex (result) - nIndex
(length, nIndex) = decodeLength(attestation, nIndex + 1); // Version
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Serial
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Signature type (9) 1.2.840.10045.2.1
//startTime = nIndex;
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Time sequence header
(length, timeData, nIndex) = decodeElement(attestation, nIndex);
startTime = copyStringBlock(timeData);
(length, timeData, nIndex) = decodeElement(attestation, nIndex);
endTime = copyStringBlock(timeData);
}
function verifyNFTAttestation(bytes memory attestation) public override pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, address attestorAddress)
{
bool isValid;
(tokens, identifier, subject, attestorAddress, isValid) = verifyNFTAttestation(attestation, address(0));
if (!isValid)
{
identifier = "";
subject = payable(address(0));
attestorAddress = address(0);
}
}
function verifyNFTAttestation(bytes memory attestation, address attestorAddress, address sender) public override pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, bool isValid)
{
address receivedAttestorAddress;
(tokens, identifier, subject, receivedAttestorAddress, isValid) = verifyNFTAttestation(attestation, sender);
isValid = isValid && (receivedAttestorAddress == attestorAddress);
}
function verifyNFTAttestation(bytes memory attestation, address sender) public pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, address attestorAddress, bool isValid)
{
bytes memory signatureData;
uint256 nIndex = 1;
uint256 length = 0;
uint256 preHashStart = 0;
uint256 preHashLength = 0;
(length, nIndex) = decodeLength(attestation, nIndex); //move past overall size (395)
preHashStart = nIndex;
tokens = getTokenInformation(attestation, nIndex); // handle tokenData
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past token wrapper size (312)
preHashLength = length + (nIndex - preHashStart);
(subject, identifier, attestorAddress) = verifyPublicAttestation(attestation, nIndex); //pull out subject, identifier and check attesting signature
//If the sender is the NFT subject, then no need to check the wrapping signature, the intention is signed from transaction
if (subject != sender)
{
//check wrapping signature equals subject signature
nIndex += length;
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past the signature type
(length, signatureData, nIndex) = decodeElementOffset(attestation, nIndex+length, 1); //extract signature
bytes memory preHash = copyDataBlock(attestation, preHashStart, preHashLength);
//check SignedNFTAddress
isValid = (recoverSigner(messageWithPrefix(preHash), signatureData) == subject); //Note we sign with SignPersonal
}
else
{
isValid = true;
}
}
function publicKeyToAddress(bytes memory publicKey) pure internal returns(address)
{
return address(uint160(uint256(keccak256(publicKey))));
}
function recoverSigner(bytes32 hash, bytes memory signature) internal pure returns(address signer)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(signature);
return ECDSA.recover(hash, v, r, s);
}
function splitSignature(bytes memory sig)
internal pure returns (bytes32 r, bytes32 s, uint8 v)
{
require(sig.length == 65, "invalid signature length");
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
}
//Truncates if input is greater than 32 bytes; we only handle 32 byte values.
function bytesToUint(bytes memory b) internal pure returns (uint256 conv)
{
if (b.length < 0x20) //if b is less than 32 bytes we need to pad to get correct value
{
bytes memory b2 = new bytes(32);
uint startCopy = 0x20 + 0x20 - b.length;
assembly
{
let bcc := add(b, 0x20) // pointer to start of b's data
let bbc := add(b2, startCopy) // pointer to where we want to start writing to b2's data
mstore(bbc, mload(bcc)) // store
conv := mload(add(b2, 32))
}
}
else
{
assembly
{
conv := mload(add(b, 32))
}
}
}
function decodeDERData(bytes memory byteCode, uint dIndex) internal pure returns(bytes memory data, uint256 index, uint256 length)
{
return decodeDERData(byteCode, dIndex, 0);
}
function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) internal pure returns(bytes memory data)
{
uint256 blank = 0;
uint256 index = dIndex;
uint dStart = 0x20 + index;
uint cycles = length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank
}
data = new bytes(requiredAlloc);
assembly {
let mc := add(data, 0x20) //offset into bytes we're writing into
let cycle := 0
for
{
let cc := add(byteCode, dStart)
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(data, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back
mstore(data, length)
}
}
}
function copyStringBlock(bytes memory byteCode) internal pure returns(string memory stringData)
{
uint256 blank = 0; //blank 32 byte value
uint256 length = byteCode.length;
uint cycles = byteCode.length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - to avoid looping with single byte writes
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank, so we don't smack the next stack entry
}
stringData = new string(requiredAlloc);
//copy data in 32 byte blocks
assembly {
let cycle := 0
for
{
let mc := add(stringData, 0x20) //pointer into bytes we're writing to
let cc := add(byteCode, 0x20) //pointer to where we're reading from
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size (part of the optimisation to avoid looping adding blank bytes1)
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(stringData, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back so the returned object is the correct size
mstore(stringData, length)
}
}
}
function decodeDERData(bytes memory byteCode, uint dIndex, uint offset) internal pure returns(bytes memory data, uint256 index, uint256 length)
{
index = dIndex + 1;
(length, index) = decodeLength(byteCode, index);
if (offset <= length)
{
uint requiredLength = length - offset;
uint dStart = index + offset;
data = copyDataBlock(byteCode, dStart, requiredLength);
}
else
{
data = bytes("");
}
index += length;
}
function decodeElement(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, bytes memory content, uint256 newIndex)
{
(content, newIndex, length) = decodeDERData(byteCode, decodeIndex);
}
function decodeElementOffset(bytes memory byteCode, uint decodeIndex, uint offset) internal pure returns(uint256 length, bytes memory content, uint256 newIndex)
{
(content, newIndex, length) = decodeDERData(byteCode, decodeIndex, offset);
}
function decodeLength(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, uint256 newIndex)
{
uint codeLength = 1;
length = 0;
newIndex = decodeIndex;
if ((byteCode[newIndex] & 0x80) == 0x80)
{
codeLength = uint8((byteCode[newIndex++] & 0x7f));
}
for (uint i = 0; i < codeLength; i++)
{
length |= uint(uint8(byteCode[newIndex++] & 0xFF)) << ((codeLength - i - 1) * 8);
}
}
function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) internal pure returns(Status memory)
{
uint length = uint8(byteCode[decodeIndex++]);
bytes32 store = 0;
for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8);
objCodes[objCodeIndex++] = uint256(store);
Status memory retVal;
retVal.decodeIndex = decodeIndex;
retVal.objCodeIndex = objCodeIndex;
return retVal;
}
function mapTo256BitInteger(bytes memory input) internal pure returns(uint256 res)
{
bytes32 idHash = keccak256(input);
res = uint256(idHash);
}
struct Status {
uint decodeIndex;
uint objCodeIndex;
}
function endContract() public payable
{
if(msg.sender == owner)
{
selfdestruct(owner);
}
else revert();
}
} | contract VerifyAttestation is IVerifyAttestation {
address payable owner;
constructor()
{
owner = payable(msg.sender);
}
struct Length {
uint decodeIndex;
uint length;
}
function verifyPublicAttestation(bytes memory attestation, uint256 nIndex) public pure returns(address payable subject, string memory identifier, address attestorAddress)
{
bytes memory attestationData;
bytes memory preHash;
uint256 decodeIndex = 0;
uint256 length = 0;
/*
Attestation structure:
Length, Length
- Version,
- Serial,
- Signature type,
- Issuer Sequence,
- Validity Time period Start, finish
*/
(length, nIndex) = decodeLength(attestation, nIndex+1); //nIndex is start of prehash
(length, decodeIndex) = decodeLength(attestation, nIndex+1); // length of prehash is decodeIndex (result) - nIndex
//obtain pre-hash
preHash = copyDataBlock(attestation, nIndex, (decodeIndex + length) - nIndex);
nIndex = (decodeIndex + length); //set pointer to read data after the pre-hash block
(length, decodeIndex) = decodeLength(preHash, 1); //read pre-hash header
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1); // Version
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Serial
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Signature type (9) 1.2.840.10045.2.1
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
(length, attestationData, decodeIndex) = decodeElement(preHash, decodeIndex + length); // Validity Time (34) (Start, End) 32303231303331343030303835315A, 32303231303331343031303835315A
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1);
(length, attestationData, decodeIndex) = decodeElementOffset(preHash, decodeIndex, 15); //Twitter ID
identifier = copyStringBlock(attestationData);
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1);
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1);
(length, attestationData, decodeIndex) = decodeElementOffset(preHash, decodeIndex + length, 2); // public key
subject = payable(publicKeyToAddress(attestationData));
(length, attestationData, nIndex) = decodeElement(attestation, nIndex); // Signature algorithm ID (9) 1.2.840.10045.2.1
(length, attestationData, nIndex) = decodeElementOffset(attestation, nIndex, 1); // Signature (72) : #0348003045022100F1862F9616B43C1F1550156341407AFB11EEC8B8BB60A513B346516DBC4F1F3202204E1B19196B97E4AECD6AE7E701BF968F72130959A01FCE83197B485A6AD2C7EA
//return attestorPass && subjectPass && identifierPass;
attestorAddress = recoverSigner(keccak256(preHash), attestationData);
}
function getTokenInformation(bytes memory attestation, uint256 nIndex) public pure returns(ERC721Token[] memory tokens)
{
//currently format only handles one token
uint256 length = 0;
bytes memory tokenData;
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past overall size (312) ([4])
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past attestation size (281)
nIndex += length;
(length, nIndex) = decodeLength(attestation, nIndex+1);
uint256 tokenCount = length / 25;
tokens = new ERC721Token[](tokenCount);
address tokenAddr;
for (uint256 index = 0; index < tokenCount; index++)
{
(length, tokenData, nIndex) = decodeElement(attestation, nIndex+2);
//to address
bytes memory scratch = new bytes(32);
assembly {
mstore(add(scratch, 44), mload(add(tokenData, 0x20))) //load address data to final bytes160 of scratch
tokenAddr := mload(add(scratch, 0x20)) //directly convert to address
mstore(add(scratch, 32), 0x00) //blank scratch for use as auth placeholder
}
(length, tokenData, nIndex) = decodeElement(attestation, nIndex);
tokens[index] = ERC721Token(tokenAddr, bytesToUint(tokenData), scratch);
}
}
// Leave this function public as a utility function to check attestation against commitmentmentId
// The check takes into account the NFTs signed by the SignedNFTAttestation vs those stored in the commitment
function checkAttestationValidity(bytes memory nftAttestation, ERC721Token[] memory commitmentNFTs,
string memory commitmentIdentifier, address attestorAddress, address sender) public override pure returns(bool passedVerification, address payable subjectAddress)
{
ERC721Token[] memory attestationNFTs;
string memory attestationIdentifier;
(attestationNFTs, attestationIdentifier, subjectAddress, passedVerification)
= verifyNFTAttestation(nftAttestation, attestorAddress, sender);
passedVerification = passedVerification &&
checkValidity(attestationNFTs, commitmentNFTs, commitmentIdentifier, attestationIdentifier);
}
// Check that the attestion tokens match the commitment tokens
// And that the identifier in the attestation matches the identifier in the commitment
function checkValidity(ERC721Token[] memory attestationNFTs, ERC721Token[] memory commitmentNFTs, string memory commitIdentifier,
string memory attestationIdentifier) internal pure returns(bool)
{
//check that the tokens in the attestation match those in the commitment
if (attestationNFTs.length != commitmentNFTs.length)
{
return false;
}
else
{
//check each token. NB Tokens must be in same order in original commitment package as in attestation package
for (uint256 index = 0; index < attestationNFTs.length; index++)
{
if (attestationNFTs[index].erc721 != commitmentNFTs[index].erc721
|| attestationNFTs[index].tokenId != commitmentNFTs[index].tokenId)
{
return false;
}
}
//now check identifiers match if attestation is still passing
return checkIdentifier(attestationIdentifier, commitIdentifier);
}
}
// In production we need to match the full string, as the second part of the attestation is the unique ID
function checkIdentifier(string memory attestationId, string memory checkId) internal pure returns(bool)
{
return (keccak256(abi.encodePacked((attestationId))) ==
keccak256(abi.encodePacked((checkId))));
}
function messageWithPrefix(bytes memory preHash) public pure returns (bytes32 hash)
{
uint256 dataLength;
uint256 length = 3;
assembly {
dataLength := mload(preHash)
if gt(dataLength, 999) { length := 4 }
}
bytes memory bstr = new bytes(length);
uint256 k = length;
uint256 j = dataLength;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
bytes memory str = abi.encodePacked("\x19Ethereum Signed Message:\n", bstr, preHash);
hash = keccak256(str);
}
function getNFTAttestationTimestamp(bytes memory attestation) public override pure returns(string memory startTime, string memory endTime)
{
uint256 length = 0;
uint256 nIndex = 0;
bytes memory timeData;
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past overall size
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past token wrapper size
//now into PublicAttestation
(length, nIndex) = decodeLength(attestation, nIndex+1); //nIndex is start of prehash
(length, nIndex) = decodeLength(attestation, nIndex+1); // length of prehash is decodeIndex (result) - nIndex
(length, nIndex) = decodeLength(attestation, nIndex + 1); // Version
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Serial
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Signature type (9) 1.2.840.10045.2.1
//startTime = nIndex;
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
(length, nIndex) = decodeLength(attestation, nIndex + 1 + length); // Time sequence header
(length, timeData, nIndex) = decodeElement(attestation, nIndex);
startTime = copyStringBlock(timeData);
(length, timeData, nIndex) = decodeElement(attestation, nIndex);
endTime = copyStringBlock(timeData);
}
function verifyNFTAttestation(bytes memory attestation) public override pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, address attestorAddress)
{
bool isValid;
(tokens, identifier, subject, attestorAddress, isValid) = verifyNFTAttestation(attestation, address(0));
if (!isValid)
{
identifier = "";
subject = payable(address(0));
attestorAddress = address(0);
}
}
function verifyNFTAttestation(bytes memory attestation, address attestorAddress, address sender) public override pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, bool isValid)
{
address receivedAttestorAddress;
(tokens, identifier, subject, receivedAttestorAddress, isValid) = verifyNFTAttestation(attestation, sender);
isValid = isValid && (receivedAttestorAddress == attestorAddress);
}
function verifyNFTAttestation(bytes memory attestation, address sender) public pure returns(ERC721Token[] memory tokens, string memory identifier, address payable subject, address attestorAddress, bool isValid)
{
bytes memory signatureData;
uint256 nIndex = 1;
uint256 length = 0;
uint256 preHashStart = 0;
uint256 preHashLength = 0;
(length, nIndex) = decodeLength(attestation, nIndex); //move past overall size (395)
preHashStart = nIndex;
tokens = getTokenInformation(attestation, nIndex); // handle tokenData
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past token wrapper size (312)
preHashLength = length + (nIndex - preHashStart);
(subject, identifier, attestorAddress) = verifyPublicAttestation(attestation, nIndex); //pull out subject, identifier and check attesting signature
//If the sender is the NFT subject, then no need to check the wrapping signature, the intention is signed from transaction
if (subject != sender)
{
//check wrapping signature equals subject signature
nIndex += length;
(length, nIndex) = decodeLength(attestation, nIndex+1); //move past the signature type
(length, signatureData, nIndex) = decodeElementOffset(attestation, nIndex+length, 1); //extract signature
bytes memory preHash = copyDataBlock(attestation, preHashStart, preHashLength);
//check SignedNFTAddress
isValid = (recoverSigner(messageWithPrefix(preHash), signatureData) == subject); //Note we sign with SignPersonal
}
else
{
isValid = true;
}
}
function publicKeyToAddress(bytes memory publicKey) pure internal returns(address)
{
return address(uint160(uint256(keccak256(publicKey))));
}
function recoverSigner(bytes32 hash, bytes memory signature) internal pure returns(address signer)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(signature);
return ECDSA.recover(hash, v, r, s);
}
function splitSignature(bytes memory sig)
internal pure returns (bytes32 r, bytes32 s, uint8 v)
{
require(sig.length == 65, "invalid signature length");
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
}
//Truncates if input is greater than 32 bytes; we only handle 32 byte values.
function bytesToUint(bytes memory b) internal pure returns (uint256 conv)
{
if (b.length < 0x20) //if b is less than 32 bytes we need to pad to get correct value
{
bytes memory b2 = new bytes(32);
uint startCopy = 0x20 + 0x20 - b.length;
assembly
{
let bcc := add(b, 0x20) // pointer to start of b's data
let bbc := add(b2, startCopy) // pointer to where we want to start writing to b2's data
mstore(bbc, mload(bcc)) // store
conv := mload(add(b2, 32))
}
}
else
{
assembly
{
conv := mload(add(b, 32))
}
}
}
function decodeDERData(bytes memory byteCode, uint dIndex) internal pure returns(bytes memory data, uint256 index, uint256 length)
{
return decodeDERData(byteCode, dIndex, 0);
}
function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) internal pure returns(bytes memory data)
{
uint256 blank = 0;
uint256 index = dIndex;
uint dStart = 0x20 + index;
uint cycles = length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank
}
data = new bytes(requiredAlloc);
assembly {
let mc := add(data, 0x20) //offset into bytes we're writing into
let cycle := 0
for
{
let cc := add(byteCode, dStart)
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(data, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back
mstore(data, length)
}
}
}
function copyStringBlock(bytes memory byteCode) internal pure returns(string memory stringData)
{
uint256 blank = 0; //blank 32 byte value
uint256 length = byteCode.length;
uint cycles = byteCode.length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - to avoid looping with single byte writes
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank, so we don't smack the next stack entry
}
stringData = new string(requiredAlloc);
//copy data in 32 byte blocks
assembly {
let cycle := 0
for
{
let mc := add(stringData, 0x20) //pointer into bytes we're writing to
let cc := add(byteCode, 0x20) //pointer to where we're reading from
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size (part of the optimisation to avoid looping adding blank bytes1)
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(stringData, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back so the returned object is the correct size
mstore(stringData, length)
}
}
}
function decodeDERData(bytes memory byteCode, uint dIndex, uint offset) internal pure returns(bytes memory data, uint256 index, uint256 length)
{
index = dIndex + 1;
(length, index) = decodeLength(byteCode, index);
if (offset <= length)
{
uint requiredLength = length - offset;
uint dStart = index + offset;
data = copyDataBlock(byteCode, dStart, requiredLength);
}
else
{
data = bytes("");
}
index += length;
}
function decodeElement(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, bytes memory content, uint256 newIndex)
{
(content, newIndex, length) = decodeDERData(byteCode, decodeIndex);
}
function decodeElementOffset(bytes memory byteCode, uint decodeIndex, uint offset) internal pure returns(uint256 length, bytes memory content, uint256 newIndex)
{
(content, newIndex, length) = decodeDERData(byteCode, decodeIndex, offset);
}
function decodeLength(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, uint256 newIndex)
{
uint codeLength = 1;
length = 0;
newIndex = decodeIndex;
if ((byteCode[newIndex] & 0x80) == 0x80)
{
codeLength = uint8((byteCode[newIndex++] & 0x7f));
}
for (uint i = 0; i < codeLength; i++)
{
length |= uint(uint8(byteCode[newIndex++] & 0xFF)) << ((codeLength - i - 1) * 8);
}
}
function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) internal pure returns(Status memory)
{
uint length = uint8(byteCode[decodeIndex++]);
bytes32 store = 0;
for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8);
objCodes[objCodeIndex++] = uint256(store);
Status memory retVal;
retVal.decodeIndex = decodeIndex;
retVal.objCodeIndex = objCodeIndex;
return retVal;
}
function mapTo256BitInteger(bytes memory input) internal pure returns(uint256 res)
{
bytes32 idHash = keccak256(input);
res = uint256(idHash);
}
struct Status {
uint decodeIndex;
uint objCodeIndex;
}
function endContract() public payable
{
if(msg.sender == owner)
{
selfdestruct(owner);
}
else revert();
}
} | 13,345 |
73 | // Tell if a Result is errored. _result An instance of Result.return `true` if errored, `false` if successful. / | function isError(Result memory _result) public pure returns(bool) {
return !_result.success;
}
| function isError(Result memory _result) public pure returns(bool) {
return !_result.success;
}
| 32,113 |
385 | // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. This will give us the correct result modulo 2256. Since the precoditions guarantee that the outcome is less than 2256, this is the final result. We don't need to compute the high bits of the result and prod1 is no longer required. | result = prod0 * inv;
return result;
| result = prod0 * inv;
return result;
| 30,529 |
61 | // Max fee is 1% of the total supply. | uint256 private _maxTxAmount = _tTotal / 100;
| uint256 private _maxTxAmount = _tTotal / 100;
| 39,705 |
66 | // clear any previously approved ownership exchange | delete powIndexToApproved[_tokenId];
| delete powIndexToApproved[_tokenId];
| 38,019 |
28 | // Non transferable token contract, implementing ERC-1155, but preventing transfers / | interface IERC1155NonTransferable {
/**
* @notice Mint an amount of a desired token
* Currently no restrictions as to who is allowed to mint - so, it is external.
* @dev ERC-1155
* @param _to owner of the minted token
* @param _tokenId ID of the token to be minted
* @param _value Amount of the token to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mint(
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
) external;
/**
* @notice Burn an amount of tokens with the given ID
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenId ID of the token
* @param _value Amount of the token
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _value
) external;
/**
* @notice Pause all token mint, transfer, burn
*/
function pause() external;
/**
* @notice Unpause the contract and allows mint, transfer, burn
*/
function unpause() external;
}
| interface IERC1155NonTransferable {
/**
* @notice Mint an amount of a desired token
* Currently no restrictions as to who is allowed to mint - so, it is external.
* @dev ERC-1155
* @param _to owner of the minted token
* @param _tokenId ID of the token to be minted
* @param _value Amount of the token to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mint(
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
) external;
/**
* @notice Burn an amount of tokens with the given ID
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenId ID of the token
* @param _value Amount of the token
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _value
) external;
/**
* @notice Pause all token mint, transfer, burn
*/
function pause() external;
/**
* @notice Unpause the contract and allows mint, transfer, burn
*/
function unpause() external;
}
| 5,902 |
26 | // Returns the absolute unsigned value of a signed value. / | function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
| function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
| 23,770 |
26 | // See {IGovernor-hasVoted}. / | function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
return
_proposalDetails[proposalId].receipts[account].hasVoted ||
_proposalDetails[proposalId].receipts[account].hasVoted;
}
| function hasVoted(uint256 proposalId, address account) public view virtual override returns (bool) {
return
_proposalDetails[proposalId].receipts[account].hasVoted ||
_proposalDetails[proposalId].receipts[account].hasVoted;
}
| 11,995 |
33 | // Allows to claim the ETH for an account/account the account we want to claim for/percent the allocation for this account | 2 decimal basis, meaning 1 = 100, 2.5 = 250 etc.../merkleProof the merkle proof used to ensure this claim is legit | function claimETH(
address account,
uint256 percent,
bytes32[] memory merkleProof
| function claimETH(
address account,
uint256 percent,
bytes32[] memory merkleProof
| 24,837 |
5 | // IERC721 optional extension | function burn(uint256 tokenId) external {
require(_isApprovedOrOwner(msg.sender, tokenId), ALLOWED_ERROR);
_burn(tokenId);
supplyCounter -= 1;
}
| function burn(uint256 tokenId) external {
require(_isApprovedOrOwner(msg.sender, tokenId), ALLOWED_ERROR);
_burn(tokenId);
supplyCounter -= 1;
}
| 7,380 |
73 | // Overflow not possible: value <= fromBalance <= totalSupply. | _balances[from] = fromBalance - value;
| _balances[from] = fromBalance - value;
| 9,309 |
45 | // Whether or not a vote has been cast | bool hasVoted;
| bool hasVoted;
| 1,884 |
10 | // Function to mint new NFTs, presale | function presaleMint(uint256 numOfTokens) external payable nonReentrant {
require(presaleActive, "Presale not ongoing");
require(msg.sender == tx.origin, "Wallet Error");
require(presaleAddresses[msg.sender], "Not whitelisted");
require(
presaleClaimed[msg.sender] + numOfTokens <= PRESALE_PURCHASE_LIMIT,
"Address limit reached"
);
require(numOfTokens * tokenPrice == msg.value, "Ether value mismatch");
presaleClaimed[msg.sender] += numOfTokens;
_safeMint(msg.sender, numOfTokens);
payable(beneficiary).transfer(msg.value);
}
| function presaleMint(uint256 numOfTokens) external payable nonReentrant {
require(presaleActive, "Presale not ongoing");
require(msg.sender == tx.origin, "Wallet Error");
require(presaleAddresses[msg.sender], "Not whitelisted");
require(
presaleClaimed[msg.sender] + numOfTokens <= PRESALE_PURCHASE_LIMIT,
"Address limit reached"
);
require(numOfTokens * tokenPrice == msg.value, "Ether value mismatch");
presaleClaimed[msg.sender] += numOfTokens;
_safeMint(msg.sender, numOfTokens);
payable(beneficiary).transfer(msg.value);
}
| 14,492 |
16 | // Restricted: used internally to Synthetix | function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
| function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
| 45,685 |
15 | // If there are no tokens with fee-exempt yield, then the total non-exempt growth will equal the total growth: all yield growth is non-exempt. There's also no point in adjusting balances, since we already know none are exempt. |
totalNonExemptGrowthInvariant = StableMath._calculateInvariant(lastJoinExitAmp, balances);
totalGrowthInvariant = totalNonExemptGrowthInvariant;
|
totalNonExemptGrowthInvariant = StableMath._calculateInvariant(lastJoinExitAmp, balances);
totalGrowthInvariant = totalNonExemptGrowthInvariant;
| 21,637 |
0 | // invariant {:msg "x is positive"} x>0; | int x;
constructor() public {
}
| int x;
constructor() public {
}
| 8,787 |
37 | // Cumulative sum of all charged commissions./ | uint[] commissionCumulative;
| uint[] commissionCumulative;
| 23,219 |
3 | // use bigModExp precompile | assembly {
let p := mload(0x40)
mstore(p, 0x20)
mstore(add(p, 0x20), 0x20)
mstore(add(p, 0x40), 0x20)
mstore(add(p, 0x60), a)
mstore(add(p, 0x80), e)
mstore(add(p, 0xa0), m)
if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) {
revert(0, 0)
| assembly {
let p := mload(0x40)
mstore(p, 0x20)
mstore(add(p, 0x20), 0x20)
mstore(add(p, 0x40), 0x20)
mstore(add(p, 0x60), a)
mstore(add(p, 0x80), e)
mstore(add(p, 0xa0), m)
if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) {
revert(0, 0)
| 44,999 |
7 | // require(tknv.balanceOf(msg.sender) >= tknvRequired, 'membership required'); | require(id <= currentid, 'invalid id');
if(inaddress[id] == uniswapRouter.WETH()){
require(outaddress[id] == path[path.length - 1], 'invalid path');
require(paymentBalance[id] == flatcost + inamt[id], 'request cancelled');
| require(id <= currentid, 'invalid id');
if(inaddress[id] == uniswapRouter.WETH()){
require(outaddress[id] == path[path.length - 1], 'invalid path');
require(paymentBalance[id] == flatcost + inamt[id], 'request cancelled');
| 16,052 |
87 | // Returns data about a specific observation index/index The element of the observations array to fetch/You most likely want to use observe() instead of this method to get an observation as of some amount of time/ ago, rather than at a specific index in the array./ return blockTimestamp The timestamp of the observation,/ Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,/ Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,/ Returns initialized whether the observation has been initialized and the | function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
| function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
| 3,633 |
8 | // Returns the total value of the plus token in terms of the peg value.All underlying token amounts have been scaled to 18 decimals and expressed in WAD. / | function _totalUnderlyingInWad() internal view virtual override returns (uint256) {
uint256 _amount = 0;
for (uint256 i = 0; i < tokens.length; i++) {
// Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount
// minted is the amount of all plus tokens in the basket added.
// Note: All plus tokens, single or composite, have 18 decimals.
_amount = _amount.add(IERC20Upgradeable(tokens[i]).balanceOf(address(this)));
}
// Plus tokens are in 18 decimals, need to return in WAD.
return _amount.mul(WAD);
}
| function _totalUnderlyingInWad() internal view virtual override returns (uint256) {
uint256 _amount = 0;
for (uint256 i = 0; i < tokens.length; i++) {
// Since all underlying tokens in the baskets are plus tokens with the same value peg, the amount
// minted is the amount of all plus tokens in the basket added.
// Note: All plus tokens, single or composite, have 18 decimals.
_amount = _amount.add(IERC20Upgradeable(tokens[i]).balanceOf(address(this)));
}
// Plus tokens are in 18 decimals, need to return in WAD.
return _amount.mul(WAD);
}
| 16,955 |
135 | // Override the transfer function with transferWithProofsA proof of ownership will be made if any claims can be made by the participants / | function transfer(address _to, uint256 _value) public returns (bool) {
bool proofFrom = hasClaims(msg.sender);
bool proofTo = hasClaims(_to);
return super.transferWithProofs(
_to,
_value,
proofFrom,
proofTo
);
}
| function transfer(address _to, uint256 _value) public returns (bool) {
bool proofFrom = hasClaims(msg.sender);
bool proofTo = hasClaims(_to);
return super.transferWithProofs(
_to,
_value,
proofFrom,
proofTo
);
}
| 13,113 |
33 | // BEP-721 Non-Fungible Token Standard, optional metadata extension / | interface IBEP721Metadata is IBEP721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
| interface IBEP721Metadata is IBEP721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
| 23,443 |
6 | // check if identity is either contract owner or CA | modifier isAuthorized() {
require(authorizedList[msg.sender] == true, "Only authorized parties have access to this function!");
_;
}
| modifier isAuthorized() {
require(authorizedList[msg.sender] == true, "Only authorized parties have access to this function!");
_;
}
| 9,130 |
2 | // eg. cDAI address | address private cToken;
| address private cToken;
| 33,577 |
9 | // Convert limited uint256 value into bytes v The uint256 valuereturnConverted bytes array/ | function WriteUint255(uint256 v) internal pure returns (bytes memory) {
require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds uint255 range");
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x20
mstore(buff, byteLen)
for {
let mindex := 0x00
let vindex := 0x1f
} lt(mindex, byteLen) {
mindex := add(mindex, 0x01)
vindex := sub(vindex, 0x01)
}{
mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
}
mstore(0x40, add(buff, 0x40))
}
return buff;
}
| function WriteUint255(uint256 v) internal pure returns (bytes memory) {
require(v <= 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, "Value exceeds uint255 range");
bytes memory buff;
assembly{
buff := mload(0x40)
let byteLen := 0x20
mstore(buff, byteLen)
for {
let mindex := 0x00
let vindex := 0x1f
} lt(mindex, byteLen) {
mindex := add(mindex, 0x01)
vindex := sub(vindex, 0x01)
}{
mstore8(add(add(buff, 0x20), mindex), byte(vindex, v))
}
mstore(0x40, add(buff, 0x40))
}
return buff;
}
| 12,009 |
12 | // Signature verified by wallet contract without data validation. | } else if (signatureType == SignatureType.WalletBytes32) {
| } else if (signatureType == SignatureType.WalletBytes32) {
| 20,229 |
132 | // Limit the number of shares to liquidate up to the maximum allowed. | uint256 actualShares = shares > maximumShares ? maximumShares : shares;
| uint256 actualShares = shares > maximumShares ? maximumShares : shares;
| 10,663 |
157 | // ______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___ This is a 256 value limit (uint8) | enum InterfaceType {
NULL, // 0
ERC20, // 1
ERC721, // 2
ERC1155 // 3
}
| enum InterfaceType {
NULL, // 0
ERC20, // 1
ERC721, // 2
ERC1155 // 3
}
| 72,499 |
58 | // FPTCoin mine pool, which manager contract is FPTCoin. A smart-contract which distribute some mine coins by FPTCoin balance./ | contract MinePoolData is Managerable,AddressWhiteList,ReentrancyGuard {
//Special decimals for calculation
uint256 constant calDecimals = 1e18;
// miner's balance
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerBalances;
// miner's origins, specially used for mine distribution
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerOrigins;
// mine coins total worth, specially used for mine distribution
mapping(address=>uint256) internal totalMinedWorth;
// total distributed mine coin amount
mapping(address=>uint256) internal totalMinedCoin;
// latest time to settlement
mapping(address=>uint256) internal latestSettleTime;
//distributed mine amount
mapping(address=>uint256) internal mineAmount;
//distributed time interval
mapping(address=>uint256) internal mineInterval;
//distributed mine coin amount for buy options user.
mapping(address=>uint256) internal buyingMineMap;
// user's Opterator indicator
uint256 constant internal opBurnCoin = 1;
uint256 constant internal opMintCoin = 2;
uint256 constant internal opTransferCoin = 3;
/**
* @dev Emitted when `account` mint `amount` miner shares.
*/
event MintMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `account` burn `amount` miner shares.
*/
event BurnMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `from` redeem `value` mineCoins.
*/
event RedeemMineCoin(address indexed from, address indexed mineCoin, uint256 value);
/**
* @dev Emitted when `from` transfer to `to` `amount` mineCoins.
*/
event TranserMiner(address indexed from, address indexed to, uint256 amount);
/**
* @dev Emitted when `account` buying options get `amount` mineCoins.
*/
event BuyingMiner(address indexed account,address indexed mineCoin,uint256 amount);
}
| contract MinePoolData is Managerable,AddressWhiteList,ReentrancyGuard {
//Special decimals for calculation
uint256 constant calDecimals = 1e18;
// miner's balance
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerBalances;
// miner's origins, specially used for mine distribution
// map mineCoin => user => balance
mapping(address=>mapping(address=>uint256)) internal minerOrigins;
// mine coins total worth, specially used for mine distribution
mapping(address=>uint256) internal totalMinedWorth;
// total distributed mine coin amount
mapping(address=>uint256) internal totalMinedCoin;
// latest time to settlement
mapping(address=>uint256) internal latestSettleTime;
//distributed mine amount
mapping(address=>uint256) internal mineAmount;
//distributed time interval
mapping(address=>uint256) internal mineInterval;
//distributed mine coin amount for buy options user.
mapping(address=>uint256) internal buyingMineMap;
// user's Opterator indicator
uint256 constant internal opBurnCoin = 1;
uint256 constant internal opMintCoin = 2;
uint256 constant internal opTransferCoin = 3;
/**
* @dev Emitted when `account` mint `amount` miner shares.
*/
event MintMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `account` burn `amount` miner shares.
*/
event BurnMiner(address indexed account,uint256 amount);
/**
* @dev Emitted when `from` redeem `value` mineCoins.
*/
event RedeemMineCoin(address indexed from, address indexed mineCoin, uint256 value);
/**
* @dev Emitted when `from` transfer to `to` `amount` mineCoins.
*/
event TranserMiner(address indexed from, address indexed to, uint256 amount);
/**
* @dev Emitted when `account` buying options get `amount` mineCoins.
*/
event BuyingMiner(address indexed account,address indexed mineCoin,uint256 amount);
}
| 56,490 |
19 | // used by owner of contract to halt crowdsale and no longer except ether. | function toggleHalt(bool _halted) only_owner {
halted = _halted;
}
| function toggleHalt(bool _halted) only_owner {
halted = _halted;
}
| 21,762 |
19 | // Getter for the current variables that include the 5 requests Id'sreturn _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip / | function getNewCurrentVariables()
| function getNewCurrentVariables()
| 2,125 |
147 | // Sends funds to funds collector wallet. | address(uint160(fundsReceiver)).sendValue(msg.value);
| address(uint160(fundsReceiver)).sendValue(msg.value);
| 29,842 |
44 | // Total amount of tokens at a specific `_blockNumber`./_blockNumber The block number when the totalSupply is queried/ return The total amount of tokens at `_blockNumber` | function totalSupplyAt(uint _blockNumber) public view returns(uint) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
| function totalSupplyAt(uint _blockNumber) public view returns(uint) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
| 21,271 |
8 | // Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)/ that may remain in the router after the swap./params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata/ return amountIn The amount of the input token | function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
| function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
| 18,948 |
6 | // Whether the seeder can be updated | bool public isSeederLocked;
| bool public isSeederLocked;
| 30,410 |
29 | // contract to control vesting schedule for company and team tokens | contract Vesting is Ownable {
using SafeMath for uint;
uint public teamTokensInitial = 2e25; // max tokens amount for the team 20,000,000
uint public teamTokensCurrent = 0; // to keep record of distributed tokens so far to the team
uint public companyTokensInitial = 15e24; // max tokens amount for the company 15,000,000
uint public companyTokensCurrent = 0; // to keep record of distributed tokens so far to the company
Token public token; // token contract
uint public dateICOEnded; // date when ICO ended updated from the finalizeSale() function
uint public dateProductCompleted; // date when product has been completed
event LogTeamTokensTransferred(address indexed receipient, uint amouontOfTokens);
event LogCompanyTokensTransferred(address indexed receipient, uint amouontOfTokens);
// @notice set the handle of the token contract
// @param _token {Token} address of the token contract
// @return {bool} true if successful
function setToken(Token _token) public onlyOwner() returns(bool) {
require (token == address(0));
token = _token;
return true;
}
// @notice set the product completion date for release of dev tokens
function setProductCompletionDate() external onlyOwner() {
dateProductCompleted = now;
}
// @notice to release tokens of the team according to vesting schedule
// @param _recipient {address} of the recipient of token transfer
// @param _tokensToTransfer {uint} amount of tokens to transfer
function transferTeamTokens(address _recipient, uint _tokensToTransfer) external onlyOwner() {
require(_recipient != 0);
require(now >= 1533081600); // before Aug 1, 2018 00:00 GMT don't allow on distribution tokens to the team.
require(dateProductCompleted > 0);
if (now < dateProductCompleted + 1 years) // first year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 30) / 100);
else if (now < dateProductCompleted + 2 years) // second year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 60) / 100);
else if (now < dateProductCompleted + 3 years) // third year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 80) / 100);
else // fourth year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= teamTokensInitial);
teamTokensCurrent = teamTokensCurrent.add(_tokensToTransfer); // update released token amount
if (!token.transfer(_recipient, _tokensToTransfer))
revert();
LogTeamTokensTransferred(_recipient, _tokensToTransfer);
}
// @notice to release tokens of the company according to vesting schedule
// @param _recipient {address} of the recipient of token transfer
// @param _tokensToTransfer {uint} amount of tokens to transfer
function transferCompanyTokens(address _recipient, uint _tokensToTransfer) external onlyOwner() {
require(_recipient != 0);
require(dateICOEnded > 0);
if (now < dateICOEnded + 1 years) // first year
require(companyTokensCurrent.add(_tokensToTransfer) <= (companyTokensInitial * 50) / 100);
else if (now < dateICOEnded + 2 years) // second year
require(companyTokensCurrent.add(_tokensToTransfer) <= (companyTokensInitial * 75) / 100);
else // third year
require(companyTokensCurrent.add(_tokensToTransfer) <= companyTokensInitial);
companyTokensCurrent = companyTokensCurrent.add(_tokensToTransfer); // update released token amount
if (!token.transfer(_recipient, _tokensToTransfer))
revert();
LogCompanyTokensTransferred(_recipient, _tokensToTransfer);
}
}
| contract Vesting is Ownable {
using SafeMath for uint;
uint public teamTokensInitial = 2e25; // max tokens amount for the team 20,000,000
uint public teamTokensCurrent = 0; // to keep record of distributed tokens so far to the team
uint public companyTokensInitial = 15e24; // max tokens amount for the company 15,000,000
uint public companyTokensCurrent = 0; // to keep record of distributed tokens so far to the company
Token public token; // token contract
uint public dateICOEnded; // date when ICO ended updated from the finalizeSale() function
uint public dateProductCompleted; // date when product has been completed
event LogTeamTokensTransferred(address indexed receipient, uint amouontOfTokens);
event LogCompanyTokensTransferred(address indexed receipient, uint amouontOfTokens);
// @notice set the handle of the token contract
// @param _token {Token} address of the token contract
// @return {bool} true if successful
function setToken(Token _token) public onlyOwner() returns(bool) {
require (token == address(0));
token = _token;
return true;
}
// @notice set the product completion date for release of dev tokens
function setProductCompletionDate() external onlyOwner() {
dateProductCompleted = now;
}
// @notice to release tokens of the team according to vesting schedule
// @param _recipient {address} of the recipient of token transfer
// @param _tokensToTransfer {uint} amount of tokens to transfer
function transferTeamTokens(address _recipient, uint _tokensToTransfer) external onlyOwner() {
require(_recipient != 0);
require(now >= 1533081600); // before Aug 1, 2018 00:00 GMT don't allow on distribution tokens to the team.
require(dateProductCompleted > 0);
if (now < dateProductCompleted + 1 years) // first year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 30) / 100);
else if (now < dateProductCompleted + 2 years) // second year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 60) / 100);
else if (now < dateProductCompleted + 3 years) // third year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= (teamTokensInitial * 80) / 100);
else // fourth year after product release
require(teamTokensCurrent.add(_tokensToTransfer) <= teamTokensInitial);
teamTokensCurrent = teamTokensCurrent.add(_tokensToTransfer); // update released token amount
if (!token.transfer(_recipient, _tokensToTransfer))
revert();
LogTeamTokensTransferred(_recipient, _tokensToTransfer);
}
// @notice to release tokens of the company according to vesting schedule
// @param _recipient {address} of the recipient of token transfer
// @param _tokensToTransfer {uint} amount of tokens to transfer
function transferCompanyTokens(address _recipient, uint _tokensToTransfer) external onlyOwner() {
require(_recipient != 0);
require(dateICOEnded > 0);
if (now < dateICOEnded + 1 years) // first year
require(companyTokensCurrent.add(_tokensToTransfer) <= (companyTokensInitial * 50) / 100);
else if (now < dateICOEnded + 2 years) // second year
require(companyTokensCurrent.add(_tokensToTransfer) <= (companyTokensInitial * 75) / 100);
else // third year
require(companyTokensCurrent.add(_tokensToTransfer) <= companyTokensInitial);
companyTokensCurrent = companyTokensCurrent.add(_tokensToTransfer); // update released token amount
if (!token.transfer(_recipient, _tokensToTransfer))
revert();
LogCompanyTokensTransferred(_recipient, _tokensToTransfer);
}
}
| 33,775 |
68 | // Chain // Bootstrapping // Oracle // Epoch / | struct EpochStrategy {
uint256 offset;
uint256 start;
uint256 period;
}
| struct EpochStrategy {
uint256 offset;
uint256 start;
uint256 period;
}
| 24,958 |
259 | // Gets the `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable/ return wethToken_ The `CURVE_SETH_LIQUIDITY_WETH_TOKEN` variable value | function getCurveSethLiquidityWethToken() public view returns (address wethToken_) {
return CURVE_SETH_LIQUIDITY_WETH_TOKEN;
}
| function getCurveSethLiquidityWethToken() public view returns (address wethToken_) {
return CURVE_SETH_LIQUIDITY_WETH_TOKEN;
}
| 25,397 |
68 | // burn amount calculations | if (totalSupply > minimumSupply) {
_burnAmount = (amount.mul(burnRate)).div(1000);//Minimum burn is 0
uint256 availableBurn = totalSupply.sub(minimumSupply);
if (_burnAmount > availableBurn) { //Only half of the total supply can be burnt
_burnAmount = availableBurn;
}
| if (totalSupply > minimumSupply) {
_burnAmount = (amount.mul(burnRate)).div(1000);//Minimum burn is 0
uint256 availableBurn = totalSupply.sub(minimumSupply);
if (_burnAmount > availableBurn) { //Only half of the total supply can be burnt
_burnAmount = availableBurn;
}
| 8,819 |
11 | // token symbol | string public symbol;
| string public symbol;
| 29,231 |
35 | // called by epoch coordinator in epoch execute method/epochID id of the epoch which is executed/supplyFulfillment_ percentage (in RAY) of supply orders which have been fullfilled in the excuted epoch/redeemFulfillment_ percentage (in RAY) of redeem orders which have been fullfilled in the excuted epoch/tokenPrice_ tokenPrice of the executed epoch/epochSupplyOrderCurrency total order of currency in the executed epoch/epochRedeemOrderCurrency total order of redeems expressed in the currency value for the executed epoch | function epochUpdate(
uint256 epochID,
uint256 supplyFulfillment_,
uint256 redeemFulfillment_,
uint256 tokenPrice_,
uint256 epochSupplyOrderCurrency,
uint256 epochRedeemOrderCurrency
| function epochUpdate(
uint256 epochID,
uint256 supplyFulfillment_,
uint256 redeemFulfillment_,
uint256 tokenPrice_,
uint256 epochSupplyOrderCurrency,
uint256 epochRedeemOrderCurrency
| 15,062 |
2 | // modifiers --------------------------------------------------------- | modifier refuelIfNeeded(uint256 count) {
if (address(this).balance < (ORIGINAL_PRICE * count)) {
_refuel();
}
_;
}
| modifier refuelIfNeeded(uint256 count) {
if (address(this).balance < (ORIGINAL_PRICE * count)) {
_refuel();
}
_;
}
| 67,531 |
297 | // Signature verified by wallet contract. If used with an order, the maker of the order is the wallet contract. | } else if (signatureType == SignatureType.Wallet) {
| } else if (signatureType == SignatureType.Wallet) {
| 20,303 |
450 | // Determine what the account liquidity would be if the given amounts were redeemed/borrowed gTokenModify The market to hypothetically redeem/borrow in account The account to determine liquidity for redeemTokens The number of tokens to hypothetically redeem borrowAmount The amount of underlying to hypothetically borrow Note that we calculate the exchangeRateStored for each collateral gToken using stored data, without calculating accumulated interest.return (possible error code, hypothetical account shortfall below collateral requirements) / | function getHypotheticalAccountLiquidityInternal(
address account,
GToken gTokenModify,
uint redeemTokens,
| function getHypotheticalAccountLiquidityInternal(
address account,
GToken gTokenModify,
uint redeemTokens,
| 19,557 |
21 | // burn gas to make future issuance more costly | for (uint i=birthBlock; i<block.number; ) {
| for (uint i=birthBlock; i<block.number; ) {
| 25,122 |
2 | // Data structures. / | struct BondingDetail {
uint256 firstBondedOn;
uint256 latestBondedOn;
uint256 previousBondedOn;
}
| struct BondingDetail {
uint256 firstBondedOn;
uint256 latestBondedOn;
uint256 previousBondedOn;
}
| 45,582 |
2 | // Evaluates the value of a coin by a given Witnet price feed. | * Solidity doesn't support floats. The {valueOf} offers a solution to the problem by
* determining a quotient and a rest, which are then added to form a result.
* The 18 last digits represent the rest and everything above is equal to the quotient.
*
* For example, `2.513` would be `2513000000000000000`.
*
* The Witnet price feed service returns a value where the last 6 digits represent the
* rest (precision of 6 decimals). Thus, the function must normalise the returned price
* by a factor of 12 to ensure correct computations.
* See {https://docs.witnet.io/smart-contracts/witnet-data-feeds/using-witnet-data-feeds}
* for more information.
*
* Requirements:
*
* - `price`, returned by the Witnet oracle price feed service.
*
* Returns:
* - `quotient`
* - `rest`
* - `result`
*/
function valueOf(uint256 _amount, uint256 _price)
internal
pure
notNull(_price, "Price")
returns (
uint256 quotient,
uint256 rest,
uint256 result
)
{
uint256 factor = 10**18;
uint256 normalisedPrice = SafeMath.mul(_price, 10**12);
quotient = _amount.div(normalisedPrice);
rest = ((_amount * factor) / normalisedPrice) % factor;
bool rounding = 2 * ((_amount * factor) % normalisedPrice) >=
normalisedPrice;
if (rounding) {
rest += 1;
}
result = quotient.mul(factor) + rest;
}
| * Solidity doesn't support floats. The {valueOf} offers a solution to the problem by
* determining a quotient and a rest, which are then added to form a result.
* The 18 last digits represent the rest and everything above is equal to the quotient.
*
* For example, `2.513` would be `2513000000000000000`.
*
* The Witnet price feed service returns a value where the last 6 digits represent the
* rest (precision of 6 decimals). Thus, the function must normalise the returned price
* by a factor of 12 to ensure correct computations.
* See {https://docs.witnet.io/smart-contracts/witnet-data-feeds/using-witnet-data-feeds}
* for more information.
*
* Requirements:
*
* - `price`, returned by the Witnet oracle price feed service.
*
* Returns:
* - `quotient`
* - `rest`
* - `result`
*/
function valueOf(uint256 _amount, uint256 _price)
internal
pure
notNull(_price, "Price")
returns (
uint256 quotient,
uint256 rest,
uint256 result
)
{
uint256 factor = 10**18;
uint256 normalisedPrice = SafeMath.mul(_price, 10**12);
quotient = _amount.div(normalisedPrice);
rest = ((_amount * factor) / normalisedPrice) % factor;
bool rounding = 2 * ((_amount * factor) % normalisedPrice) >=
normalisedPrice;
if (rounding) {
rest += 1;
}
result = quotient.mul(factor) + rest;
}
| 36,416 |
27 | // Check bank not empty (empty is < betPrice eth) / | modifier bankNotEmpty() {
require(bank >= Math.percent(betPrice, rewardTwo));
require(address(this).balance >= bank);
_;
}
| modifier bankNotEmpty() {
require(bank >= Math.percent(betPrice, rewardTwo));
require(address(this).balance >= bank);
_;
}
| 61,264 |
27 | // find a slot (clean up while doing this) use either the existing slot with the exact same term, of which there can be at most one, or the first empty slot | idx = 9999;
uint[LOCK_SLOTS] storage term = lockTerm[_account];
uint[LOCK_SLOTS] storage amnt = lockAmnt[_account];
for (uint i; i < LOCK_SLOTS; i++) {
if (term[i] < now) {
term[i] = 0;
amnt[i] = 0;
if (idx == 9999) idx = i;
}
| idx = 9999;
uint[LOCK_SLOTS] storage term = lockTerm[_account];
uint[LOCK_SLOTS] storage amnt = lockAmnt[_account];
for (uint i; i < LOCK_SLOTS; i++) {
if (term[i] < now) {
term[i] = 0;
amnt[i] = 0;
if (idx == 9999) idx = i;
}
| 42,988 |
24 | // Set the new transaction amount | poolData[poolID].amountTransactions += poolData[poolID].transactions[transactionID].amount;
| poolData[poolID].amountTransactions += poolData[poolID].transactions[transactionID].amount;
| 22,458 |
918 | // After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting`withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. Might not withdraw the full requested amount in order to account for precision loss or if the full requestedamount exceeds the collateral in the position (due to paying fees).return amountWithdrawn The actual amount of collateral withdrawn. / | function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
| function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
| 12,337 |
1 | // inventorySize integers [1, quantity] are available/teamAllocation_ how many set aside for team/pricePerPack_ the cost in Wei for each pack/packSize_ how many drops can be purchased at a time | constructor(uint256 inventorySize, uint256 teamAllocation_, uint256 pricePerPack_, uint32 packSize_) {
require((inventorySize - teamAllocation_) % packSize_ == 0, "Pack size must evenly divide sale quantity");
require(inventorySize > teamAllocation_, "None for sale, no fun");
_dropInventoryIntegers.initialize(inventorySize);
_teamAllocation = teamAllocation_;
_pricePerPack = pricePerPack_;
_packSize = packSize_;
_saleDidNotBeginYet = true;
}
| constructor(uint256 inventorySize, uint256 teamAllocation_, uint256 pricePerPack_, uint32 packSize_) {
require((inventorySize - teamAllocation_) % packSize_ == 0, "Pack size must evenly divide sale quantity");
require(inventorySize > teamAllocation_, "None for sale, no fun");
_dropInventoryIntegers.initialize(inventorySize);
_teamAllocation = teamAllocation_;
_pricePerPack = pricePerPack_;
_packSize = packSize_;
_saleDidNotBeginYet = true;
}
| 37,084 |
21 | // Generating the next nonce using MMIX LGC parameters by Donald Knuth (used in RISC architecture) | nonce = (nonce * 6364136223846793005 + 1442695040888963407); // Wrap-around on 64 bits
| nonce = (nonce * 6364136223846793005 + 1442695040888963407); // Wrap-around on 64 bits
| 4,032 |
107 | // Withdraw stuked tokens | function withdrawStuckedTokens(address tokenAddress, uint256 tokens) external onlyOwner returns (bool success){
return IERC20(tokenAddress).transfer(msg.sender, tokens);
}
| function withdrawStuckedTokens(address tokenAddress, uint256 tokens) external onlyOwner returns (bool success){
return IERC20(tokenAddress).transfer(msg.sender, tokens);
}
| 1,083 |
17 | // Calculates a number of tokens to add or remove to rebalance pricingpoolAddress - Address of pool being worked on. / | function calculateBalancing(address poolAddress) public view onlyManager whenNotPaused returns (PoolAdjustments memory) {
IWeightedPool weightedPool = IWeightedPool(poolAddress);
bytes32 poolId = weightedPool.getPoolId();
(IERC20[] memory tokens, uint256[] memory balances,) = vault.getPoolTokens(poolId);
uint256[] memory normalizedWeights = weightedPool.getNormalizedWeights();
uint256[] memory oraclePrices = new uint256[](tokens.length);
int256[] memory priceDeltas = new int256[](tokens.length);
// Get oracle prices and compute deltas
for (uint256 i = 0; i < tokens.length; i++) {
oraclePrices[i] = uint256(getTokenPrice(address(tokens[i])));
}
for (uint256 i = 1; i < tokens.length; i++) {
uint256 poolTokenPrice = 0;
if (balances[i] > 0) {
poolTokenPrice = balances[0].mul(normalizedWeights[0]).div(balances[i].mul(normalizedWeights[i]));
}
// Handle potential underflow
if (int256(oraclePrices[i]) >= int256(poolTokenPrice)) {
priceDeltas[i] = int256(oraclePrices[i].sub(poolTokenPrice));
} else {
priceDeltas[i] = 0;
}
}
uint256[] memory tokenBalancesToAdd = new uint256[](tokens.length);
uint256[] memory tokenBalancesToRemove = new uint256[](tokens.length);
PoolAdjustments memory poolAdjustments;
bool isJoin = false;
bool isExit = false;
poolAdjustments.poolTolerance = weightedPools[poolAddress].tolerance;
for (uint256 i = 0; i < tokens.length; i++) {
if (priceDeltas[i] >= int256(poolAdjustments.poolTolerance)) {
tokenBalancesToRemove[i] = balances[i].mul(poolAdjustments.poolTolerance).div(PERCENTAGE_DENOMINATOR);
isExit = true;
} else if (priceDeltas[i] <= -int256(poolAdjustments.poolTolerance)) {
tokenBalancesToAdd[i] = balances[i].mul(poolAdjustments.poolTolerance).div(PERCENTAGE_DENOMINATOR);
isJoin = true;
}
}
IAsset[] memory assets = SupportLib._convertERC20sToAssets(tokens);
if (isExit) {
poolAdjustments.newExitRequest = IVault.ExitPoolRequest({
assets: assets,
userData: "",
toInternalBalance: true,
minAmountsOut: tokenBalancesToRemove
});
}
if (isJoin) {
poolAdjustments.newJoinRequest = IVault.JoinPoolRequest({
assets: assets,
userData: "",
fromInternalBalance: true,
maxAmountsIn: tokenBalancesToAdd
});
}
return poolAdjustments;
}
| function calculateBalancing(address poolAddress) public view onlyManager whenNotPaused returns (PoolAdjustments memory) {
IWeightedPool weightedPool = IWeightedPool(poolAddress);
bytes32 poolId = weightedPool.getPoolId();
(IERC20[] memory tokens, uint256[] memory balances,) = vault.getPoolTokens(poolId);
uint256[] memory normalizedWeights = weightedPool.getNormalizedWeights();
uint256[] memory oraclePrices = new uint256[](tokens.length);
int256[] memory priceDeltas = new int256[](tokens.length);
// Get oracle prices and compute deltas
for (uint256 i = 0; i < tokens.length; i++) {
oraclePrices[i] = uint256(getTokenPrice(address(tokens[i])));
}
for (uint256 i = 1; i < tokens.length; i++) {
uint256 poolTokenPrice = 0;
if (balances[i] > 0) {
poolTokenPrice = balances[0].mul(normalizedWeights[0]).div(balances[i].mul(normalizedWeights[i]));
}
// Handle potential underflow
if (int256(oraclePrices[i]) >= int256(poolTokenPrice)) {
priceDeltas[i] = int256(oraclePrices[i].sub(poolTokenPrice));
} else {
priceDeltas[i] = 0;
}
}
uint256[] memory tokenBalancesToAdd = new uint256[](tokens.length);
uint256[] memory tokenBalancesToRemove = new uint256[](tokens.length);
PoolAdjustments memory poolAdjustments;
bool isJoin = false;
bool isExit = false;
poolAdjustments.poolTolerance = weightedPools[poolAddress].tolerance;
for (uint256 i = 0; i < tokens.length; i++) {
if (priceDeltas[i] >= int256(poolAdjustments.poolTolerance)) {
tokenBalancesToRemove[i] = balances[i].mul(poolAdjustments.poolTolerance).div(PERCENTAGE_DENOMINATOR);
isExit = true;
} else if (priceDeltas[i] <= -int256(poolAdjustments.poolTolerance)) {
tokenBalancesToAdd[i] = balances[i].mul(poolAdjustments.poolTolerance).div(PERCENTAGE_DENOMINATOR);
isJoin = true;
}
}
IAsset[] memory assets = SupportLib._convertERC20sToAssets(tokens);
if (isExit) {
poolAdjustments.newExitRequest = IVault.ExitPoolRequest({
assets: assets,
userData: "",
toInternalBalance: true,
minAmountsOut: tokenBalancesToRemove
});
}
if (isJoin) {
poolAdjustments.newJoinRequest = IVault.JoinPoolRequest({
assets: assets,
userData: "",
fromInternalBalance: true,
maxAmountsIn: tokenBalancesToAdd
});
}
return poolAdjustments;
}
| 21,308 |
287 | // PancakeProfile./ | contract PancakeProfile is AccessControl, ERC721Holder {
using Counters for Counters.Counter;
using SafeBEP20 for IBEP20;
using SafeMath for uint256;
IBEP20 public cakeToken;
bytes32 public constant NFT_ROLE = keccak256("NFT_ROLE");
bytes32 public constant POINT_ROLE = keccak256("POINT_ROLE");
bytes32 public constant SPECIAL_ROLE = keccak256("SPECIAL_ROLE");
uint256 public numberActiveProfiles;
uint256 public numberCakeToReactivate;
uint256 public numberCakeToRegister;
uint256 public numberCakeToUpdate;
uint256 public numberTeams;
mapping(address => bool) public hasRegistered;
mapping(uint256 => Team) private teams;
mapping(address => User) private users;
// Used for generating the teamId
Counters.Counter private _countTeams;
// Used for generating the userId
Counters.Counter private _countUsers;
// Event to notify a new team is created
event TeamAdd(uint256 teamId, string teamName);
// Event to notify that team points are increased
event TeamPointIncrease(
uint256 indexed teamId,
uint256 numberPoints,
uint256 indexed campaignId
);
event UserChangeTeam(
address indexed userAddress,
uint256 oldTeamId,
uint256 newTeamId
);
// Event to notify that a user is registered
event UserNew(
address indexed userAddress,
uint256 teamId,
address nftAddress,
uint256 tokenId
);
// Event to notify a user pausing her profile
event UserPause(address indexed userAddress, uint256 teamId);
// Event to notify that user points are increased
event UserPointIncrease(
address indexed userAddress,
uint256 numberPoints,
uint256 indexed campaignId
);
// Event to notify that a list of users have an increase in points
event UserPointIncreaseMultiple(
address[] userAddresses,
uint256 numberPoints,
uint256 indexed campaignId
);
// Event to notify that a user is reactivating her profile
event UserReactivate(
address indexed userAddress,
uint256 teamId,
address nftAddress,
uint256 tokenId
);
// Event to notify that a user is pausing her profile
event UserUpdate(
address indexed userAddress,
address nftAddress,
uint256 tokenId
);
// Modifier for admin roles
modifier onlyOwner() {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Not the main admin"
);
_;
}
// Modifier for point roles
modifier onlyPoint() {
require(hasRole(POINT_ROLE, _msgSender()), "Not a point admin");
_;
}
// Modifier for special roles
modifier onlySpecial() {
require(hasRole(SPECIAL_ROLE, _msgSender()), "Not a special admin");
_;
}
struct Team {
string teamName;
string teamDescription;
uint256 numberUsers;
uint256 numberPoints;
bool isJoinable;
}
struct User {
uint256 userId;
uint256 numberPoints;
uint256 teamId;
address nftAddress;
uint256 tokenId;
bool isActive;
}
constructor(
IBEP20 _cakeToken,
uint256 _numberCakeToReactivate,
uint256 _numberCakeToRegister,
uint256 _numberCakeToUpdate
) public {
cakeToken = _cakeToken;
numberCakeToReactivate = _numberCakeToReactivate;
numberCakeToRegister = _numberCakeToRegister;
numberCakeToUpdate = _numberCakeToUpdate;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* @dev To create a user profile. It sends the NFT to the contract
* and sends CAKE to burn address. Requires 2 token approvals.
*/
function createProfile(
uint256 _teamId,
address _nftAddress,
uint256 _tokenId
) external {
require(!hasRegistered[_msgSender()], "Already registered");
require((_teamId <= numberTeams) && (_teamId > 0), "Invalid teamId");
require(teams[_teamId].isJoinable, "Team not joinable");
require(hasRole(NFT_ROLE, _nftAddress), "NFT address invalid");
// Loads the interface to deposit the NFT contract
IERC721 nftToken = IERC721(_nftAddress);
require(
_msgSender() == nftToken.ownerOf(_tokenId),
"Only NFT owner can register"
);
// Transfer NFT to this contract
nftToken.safeTransferFrom(_msgSender(), address(this), _tokenId);
// Transfer CAKE tokens to this contract
cakeToken.safeTransferFrom(
_msgSender(),
address(this),
numberCakeToRegister
);
// Increment the _countUsers counter and get userId
_countUsers.increment();
uint256 newUserId = _countUsers.current();
// Add data to the struct for newUserId
users[_msgSender()] = User({
userId: newUserId,
numberPoints: 0,
teamId: _teamId,
nftAddress: _nftAddress,
tokenId: _tokenId,
isActive: true
});
// Update registration status
hasRegistered[_msgSender()] = true;
// Update number of active profiles
numberActiveProfiles = numberActiveProfiles.add(1);
// Increase the number of users for the team
teams[_teamId].numberUsers = teams[_teamId].numberUsers.add(1);
// Emit an event
emit UserNew(_msgSender(), _teamId, _nftAddress, _tokenId);
}
/**
* @dev To pause user profile. It releases the NFT.
* Callable only by registered users.
*/
function pauseProfile() external {
require(hasRegistered[_msgSender()], "Has not registered");
// Checks whether user has already paused
require(users[_msgSender()].isActive, "User not active");
// Change status of user to make it inactive
users[_msgSender()].isActive = false;
// Retrieve the teamId of the user calling
uint256 userTeamId = users[_msgSender()].teamId;
// Reduce number of active users and team users
teams[userTeamId].numberUsers = teams[userTeamId].numberUsers.sub(1);
numberActiveProfiles = numberActiveProfiles.sub(1);
// Interface to deposit the NFT contract
IERC721 nftToken = IERC721(users[_msgSender()].nftAddress);
// tokenId of NFT redeemed
uint256 redeemedTokenId = users[_msgSender()].tokenId;
// Change internal statuses as extra safety
users[_msgSender()].nftAddress = address(
0x0000000000000000000000000000000000000000
);
users[_msgSender()].tokenId = 0;
// Transfer the NFT back to the user
nftToken.safeTransferFrom(address(this), _msgSender(), redeemedTokenId);
// Emit event
emit UserPause(_msgSender(), userTeamId);
}
/**
* @dev To update user profile.
* Callable only by registered users.
*/
function updateProfile(address _nftAddress, uint256 _tokenId) external {
require(hasRegistered[_msgSender()], "Has not registered");
require(hasRole(NFT_ROLE, _nftAddress), "NFT address invalid");
require(users[_msgSender()].isActive, "User not active");
address currentAddress = users[_msgSender()].nftAddress;
uint256 currentTokenId = users[_msgSender()].tokenId;
// Interface to deposit the NFT contract
IERC721 nftNewToken = IERC721(_nftAddress);
require(
_msgSender() == nftNewToken.ownerOf(_tokenId),
"Only NFT owner can update"
);
// Transfer token to new address
nftNewToken.safeTransferFrom(_msgSender(), address(this), _tokenId);
// Transfer CAKE token to this address
cakeToken.safeTransferFrom(
_msgSender(),
address(this),
numberCakeToUpdate
);
// Interface to deposit the NFT contract
IERC721 nftCurrentToken = IERC721(currentAddress);
// Transfer old token back to the owner
nftCurrentToken.safeTransferFrom(
address(this),
_msgSender(),
currentTokenId
);
// Update mapping in storage
users[_msgSender()].nftAddress = _nftAddress;
users[_msgSender()].tokenId = _tokenId;
emit UserUpdate(_msgSender(), _nftAddress, _tokenId);
}
/**
* @dev To reactivate user profile.
* Callable only by registered users.
*/
function reactivateProfile(address _nftAddress, uint256 _tokenId) external {
require(hasRegistered[_msgSender()], "Has not registered");
require(hasRole(NFT_ROLE, _nftAddress), "NFT address invalid");
require(!users[_msgSender()].isActive, "User is active");
// Interface to deposit the NFT contract
IERC721 nftToken = IERC721(_nftAddress);
require(
_msgSender() == nftToken.ownerOf(_tokenId),
"Only NFT owner can update"
);
// Transfer to this address
cakeToken.safeTransferFrom(
_msgSender(),
address(this),
numberCakeToReactivate
);
// Transfer NFT to contract
nftToken.safeTransferFrom(_msgSender(), address(this), _tokenId);
// Retrieve teamId of the user
uint256 userTeamId = users[_msgSender()].teamId;
// Update number of users for the team and number of active profiles
teams[userTeamId].numberUsers = teams[userTeamId].numberUsers.add(1);
numberActiveProfiles = numberActiveProfiles.add(1);
// Update user statuses
users[_msgSender()].isActive = true;
users[_msgSender()].nftAddress = _nftAddress;
users[_msgSender()].tokenId = _tokenId;
// Emit event
emit UserReactivate(_msgSender(), userTeamId, _nftAddress, _tokenId);
}
/**
* @dev To increase the number of points for a user.
* Callable only by point admins
*/
function increaseUserPoints(
address _userAddress,
uint256 _numberPoints,
uint256 _campaignId
) external onlyPoint {
// Increase the number of points for the user
users[_userAddress].numberPoints = users[_userAddress].numberPoints.add(
_numberPoints
);
emit UserPointIncrease(_userAddress, _numberPoints, _campaignId);
}
/**
* @dev To increase the number of points for a set of users.
* Callable only by point admins
*/
function increaseUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints,
uint256 _campaignId
) external onlyPoint {
require(_userAddresses.length < 1001, "Length must be < 1001");
for (uint256 i = 0; i < _userAddresses.length; i++) {
users[_userAddresses[i]].numberPoints = users[_userAddresses[i]]
.numberPoints
.add(_numberPoints);
}
emit UserPointIncreaseMultiple(
_userAddresses,
_numberPoints,
_campaignId
);
}
/**
* @dev To increase the number of points for a team.
* Callable only by point admins
*/
function increaseTeamPoints(
uint256 _teamId,
uint256 _numberPoints,
uint256 _campaignId
) external onlyPoint {
// Increase the number of points for the team
teams[_teamId].numberPoints = teams[_teamId].numberPoints.add(
_numberPoints
);
emit TeamPointIncrease(_teamId, _numberPoints, _campaignId);
}
/**
* @dev To remove the number of points for a user.
* Callable only by point admins
*/
function removeUserPoints(address _userAddress, uint256 _numberPoints)
external
onlyPoint
{
// Increase the number of points for the user
users[_userAddress].numberPoints = users[_userAddress].numberPoints.sub(
_numberPoints
);
}
/**
* @dev To remove a set number of points for a set of users.
*/
function removeUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints
) external onlyPoint {
require(_userAddresses.length < 1001, "Length must be < 1001");
for (uint256 i = 0; i < _userAddresses.length; i++) {
users[_userAddresses[i]].numberPoints = users[_userAddresses[i]]
.numberPoints
.sub(_numberPoints);
}
}
/**
* @dev To remove the number of points for a team.
* Callable only by point admins
*/
function removeTeamPoints(uint256 _teamId, uint256 _numberPoints)
external
onlyPoint
{
// Increase the number of points for the team
teams[_teamId].numberPoints = teams[_teamId].numberPoints.sub(
_numberPoints
);
}
/**
* @dev To add a NFT contract address for users to set their profile.
* Callable only by owner admins.
*/
function addNftAddress(address _nftAddress) external onlyOwner {
require(
IERC721(_nftAddress).supportsInterface(0x80ac58cd),
"Not ERC721"
);
grantRole(NFT_ROLE, _nftAddress);
}
/**
* @dev Add a new teamId
* Callable only by owner admins.
*/
function addTeam(
string calldata _teamName,
string calldata _teamDescription
) external onlyOwner {
// Verify length is between 3 and 16
bytes memory strBytes = bytes(_teamName);
require(strBytes.length < 20, "Must be < 20");
require(strBytes.length > 3, "Must be > 3");
// Increment the _countTeams counter and get teamId
_countTeams.increment();
uint256 newTeamId = _countTeams.current();
// Add new team data to the struct
teams[newTeamId] = Team({
teamName: _teamName,
teamDescription: _teamDescription,
numberUsers: 0,
numberPoints: 0,
isJoinable: true
});
numberTeams = newTeamId;
emit TeamAdd(newTeamId, _teamName);
}
/**
* @dev Function to change team.
* Callable only by special admins.
*/
function changeTeam(address _userAddress, uint256 _newTeamId)
external
onlySpecial
{
require(hasRegistered[_userAddress], "User doesn't exist");
require(
(_newTeamId <= numberTeams) && (_newTeamId > 0),
"teamId doesn't exist"
);
require(teams[_newTeamId].isJoinable, "Team not joinable");
require(
users[_userAddress].teamId != _newTeamId,
"Already in the team"
);
// Get old teamId
uint256 oldTeamId = users[_userAddress].teamId;
// Change number of users in old team
teams[oldTeamId].numberUsers = teams[oldTeamId].numberUsers.sub(1);
// Change teamId in user mapping
users[_userAddress].teamId = _newTeamId;
// Change number of users in new team
teams[_newTeamId].numberUsers = teams[_newTeamId].numberUsers.add(1);
emit UserChangeTeam(_userAddress, oldTeamId, _newTeamId);
}
/**
* @dev Claim CAKE to burn later.
* Callable only by owner admins.
*/
function claimFee(uint256 _amount) external onlyOwner {
cakeToken.safeTransfer(_msgSender(), _amount);
}
/**
* @dev Make a team joinable again.
* Callable only by owner admins.
*/
function makeTeamJoinable(uint256 _teamId) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
teams[_teamId].isJoinable = true;
}
/**
* @dev Make a team not joinable.
* Callable only by owner admins.
*/
function makeTeamNotJoinable(uint256 _teamId) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
teams[_teamId].isJoinable = false;
}
/**
* @dev Rename a team
* Callable only by owner admins.
*/
function renameTeam(
uint256 _teamId,
string calldata _teamName,
string calldata _teamDescription
) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
// Verify length is between 3 and 16
bytes memory strBytes = bytes(_teamName);
require(strBytes.length < 20, "Must be < 20");
require(strBytes.length > 3, "Must be > 3");
teams[_teamId].teamName = _teamName;
teams[_teamId].teamDescription = _teamDescription;
}
/**
* @dev Update the number of CAKE to register
* Callable only by owner admins.
*/
function updateNumberCake(
uint256 _newNumberCakeToReactivate,
uint256 _newNumberCakeToRegister,
uint256 _newNumberCakeToUpdate
) external onlyOwner {
numberCakeToReactivate = _newNumberCakeToReactivate;
numberCakeToRegister = _newNumberCakeToRegister;
numberCakeToUpdate = _newNumberCakeToUpdate;
}
/**
* @dev Check the user's profile for a given address
*/
function getUserProfile(address _userAddress)
external
view
returns (
uint256,
uint256,
uint256,
address,
uint256,
bool
)
{
require(hasRegistered[_userAddress], "Not registered");
return (
users[_userAddress].userId,
users[_userAddress].numberPoints,
users[_userAddress].teamId,
users[_userAddress].nftAddress,
users[_userAddress].tokenId,
users[_userAddress].isActive
);
}
/**
* @dev Check the user's status for a given address
*/
function getUserStatus(address _userAddress) external view returns (bool) {
return (users[_userAddress].isActive);
}
/**
* @dev Check a team's profile
*/
function getTeamProfile(uint256 _teamId)
external
view
returns (
string memory,
string memory,
uint256,
uint256,
bool
)
{
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
return (
teams[_teamId].teamName,
teams[_teamId].teamDescription,
teams[_teamId].numberUsers,
teams[_teamId].numberPoints,
teams[_teamId].isJoinable
);
}
}
| contract PancakeProfile is AccessControl, ERC721Holder {
using Counters for Counters.Counter;
using SafeBEP20 for IBEP20;
using SafeMath for uint256;
IBEP20 public cakeToken;
bytes32 public constant NFT_ROLE = keccak256("NFT_ROLE");
bytes32 public constant POINT_ROLE = keccak256("POINT_ROLE");
bytes32 public constant SPECIAL_ROLE = keccak256("SPECIAL_ROLE");
uint256 public numberActiveProfiles;
uint256 public numberCakeToReactivate;
uint256 public numberCakeToRegister;
uint256 public numberCakeToUpdate;
uint256 public numberTeams;
mapping(address => bool) public hasRegistered;
mapping(uint256 => Team) private teams;
mapping(address => User) private users;
// Used for generating the teamId
Counters.Counter private _countTeams;
// Used for generating the userId
Counters.Counter private _countUsers;
// Event to notify a new team is created
event TeamAdd(uint256 teamId, string teamName);
// Event to notify that team points are increased
event TeamPointIncrease(
uint256 indexed teamId,
uint256 numberPoints,
uint256 indexed campaignId
);
event UserChangeTeam(
address indexed userAddress,
uint256 oldTeamId,
uint256 newTeamId
);
// Event to notify that a user is registered
event UserNew(
address indexed userAddress,
uint256 teamId,
address nftAddress,
uint256 tokenId
);
// Event to notify a user pausing her profile
event UserPause(address indexed userAddress, uint256 teamId);
// Event to notify that user points are increased
event UserPointIncrease(
address indexed userAddress,
uint256 numberPoints,
uint256 indexed campaignId
);
// Event to notify that a list of users have an increase in points
event UserPointIncreaseMultiple(
address[] userAddresses,
uint256 numberPoints,
uint256 indexed campaignId
);
// Event to notify that a user is reactivating her profile
event UserReactivate(
address indexed userAddress,
uint256 teamId,
address nftAddress,
uint256 tokenId
);
// Event to notify that a user is pausing her profile
event UserUpdate(
address indexed userAddress,
address nftAddress,
uint256 tokenId
);
// Modifier for admin roles
modifier onlyOwner() {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Not the main admin"
);
_;
}
// Modifier for point roles
modifier onlyPoint() {
require(hasRole(POINT_ROLE, _msgSender()), "Not a point admin");
_;
}
// Modifier for special roles
modifier onlySpecial() {
require(hasRole(SPECIAL_ROLE, _msgSender()), "Not a special admin");
_;
}
struct Team {
string teamName;
string teamDescription;
uint256 numberUsers;
uint256 numberPoints;
bool isJoinable;
}
struct User {
uint256 userId;
uint256 numberPoints;
uint256 teamId;
address nftAddress;
uint256 tokenId;
bool isActive;
}
constructor(
IBEP20 _cakeToken,
uint256 _numberCakeToReactivate,
uint256 _numberCakeToRegister,
uint256 _numberCakeToUpdate
) public {
cakeToken = _cakeToken;
numberCakeToReactivate = _numberCakeToReactivate;
numberCakeToRegister = _numberCakeToRegister;
numberCakeToUpdate = _numberCakeToUpdate;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/**
* @dev To create a user profile. It sends the NFT to the contract
* and sends CAKE to burn address. Requires 2 token approvals.
*/
function createProfile(
uint256 _teamId,
address _nftAddress,
uint256 _tokenId
) external {
require(!hasRegistered[_msgSender()], "Already registered");
require((_teamId <= numberTeams) && (_teamId > 0), "Invalid teamId");
require(teams[_teamId].isJoinable, "Team not joinable");
require(hasRole(NFT_ROLE, _nftAddress), "NFT address invalid");
// Loads the interface to deposit the NFT contract
IERC721 nftToken = IERC721(_nftAddress);
require(
_msgSender() == nftToken.ownerOf(_tokenId),
"Only NFT owner can register"
);
// Transfer NFT to this contract
nftToken.safeTransferFrom(_msgSender(), address(this), _tokenId);
// Transfer CAKE tokens to this contract
cakeToken.safeTransferFrom(
_msgSender(),
address(this),
numberCakeToRegister
);
// Increment the _countUsers counter and get userId
_countUsers.increment();
uint256 newUserId = _countUsers.current();
// Add data to the struct for newUserId
users[_msgSender()] = User({
userId: newUserId,
numberPoints: 0,
teamId: _teamId,
nftAddress: _nftAddress,
tokenId: _tokenId,
isActive: true
});
// Update registration status
hasRegistered[_msgSender()] = true;
// Update number of active profiles
numberActiveProfiles = numberActiveProfiles.add(1);
// Increase the number of users for the team
teams[_teamId].numberUsers = teams[_teamId].numberUsers.add(1);
// Emit an event
emit UserNew(_msgSender(), _teamId, _nftAddress, _tokenId);
}
/**
* @dev To pause user profile. It releases the NFT.
* Callable only by registered users.
*/
function pauseProfile() external {
require(hasRegistered[_msgSender()], "Has not registered");
// Checks whether user has already paused
require(users[_msgSender()].isActive, "User not active");
// Change status of user to make it inactive
users[_msgSender()].isActive = false;
// Retrieve the teamId of the user calling
uint256 userTeamId = users[_msgSender()].teamId;
// Reduce number of active users and team users
teams[userTeamId].numberUsers = teams[userTeamId].numberUsers.sub(1);
numberActiveProfiles = numberActiveProfiles.sub(1);
// Interface to deposit the NFT contract
IERC721 nftToken = IERC721(users[_msgSender()].nftAddress);
// tokenId of NFT redeemed
uint256 redeemedTokenId = users[_msgSender()].tokenId;
// Change internal statuses as extra safety
users[_msgSender()].nftAddress = address(
0x0000000000000000000000000000000000000000
);
users[_msgSender()].tokenId = 0;
// Transfer the NFT back to the user
nftToken.safeTransferFrom(address(this), _msgSender(), redeemedTokenId);
// Emit event
emit UserPause(_msgSender(), userTeamId);
}
/**
* @dev To update user profile.
* Callable only by registered users.
*/
function updateProfile(address _nftAddress, uint256 _tokenId) external {
require(hasRegistered[_msgSender()], "Has not registered");
require(hasRole(NFT_ROLE, _nftAddress), "NFT address invalid");
require(users[_msgSender()].isActive, "User not active");
address currentAddress = users[_msgSender()].nftAddress;
uint256 currentTokenId = users[_msgSender()].tokenId;
// Interface to deposit the NFT contract
IERC721 nftNewToken = IERC721(_nftAddress);
require(
_msgSender() == nftNewToken.ownerOf(_tokenId),
"Only NFT owner can update"
);
// Transfer token to new address
nftNewToken.safeTransferFrom(_msgSender(), address(this), _tokenId);
// Transfer CAKE token to this address
cakeToken.safeTransferFrom(
_msgSender(),
address(this),
numberCakeToUpdate
);
// Interface to deposit the NFT contract
IERC721 nftCurrentToken = IERC721(currentAddress);
// Transfer old token back to the owner
nftCurrentToken.safeTransferFrom(
address(this),
_msgSender(),
currentTokenId
);
// Update mapping in storage
users[_msgSender()].nftAddress = _nftAddress;
users[_msgSender()].tokenId = _tokenId;
emit UserUpdate(_msgSender(), _nftAddress, _tokenId);
}
/**
* @dev To reactivate user profile.
* Callable only by registered users.
*/
function reactivateProfile(address _nftAddress, uint256 _tokenId) external {
require(hasRegistered[_msgSender()], "Has not registered");
require(hasRole(NFT_ROLE, _nftAddress), "NFT address invalid");
require(!users[_msgSender()].isActive, "User is active");
// Interface to deposit the NFT contract
IERC721 nftToken = IERC721(_nftAddress);
require(
_msgSender() == nftToken.ownerOf(_tokenId),
"Only NFT owner can update"
);
// Transfer to this address
cakeToken.safeTransferFrom(
_msgSender(),
address(this),
numberCakeToReactivate
);
// Transfer NFT to contract
nftToken.safeTransferFrom(_msgSender(), address(this), _tokenId);
// Retrieve teamId of the user
uint256 userTeamId = users[_msgSender()].teamId;
// Update number of users for the team and number of active profiles
teams[userTeamId].numberUsers = teams[userTeamId].numberUsers.add(1);
numberActiveProfiles = numberActiveProfiles.add(1);
// Update user statuses
users[_msgSender()].isActive = true;
users[_msgSender()].nftAddress = _nftAddress;
users[_msgSender()].tokenId = _tokenId;
// Emit event
emit UserReactivate(_msgSender(), userTeamId, _nftAddress, _tokenId);
}
/**
* @dev To increase the number of points for a user.
* Callable only by point admins
*/
function increaseUserPoints(
address _userAddress,
uint256 _numberPoints,
uint256 _campaignId
) external onlyPoint {
// Increase the number of points for the user
users[_userAddress].numberPoints = users[_userAddress].numberPoints.add(
_numberPoints
);
emit UserPointIncrease(_userAddress, _numberPoints, _campaignId);
}
/**
* @dev To increase the number of points for a set of users.
* Callable only by point admins
*/
function increaseUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints,
uint256 _campaignId
) external onlyPoint {
require(_userAddresses.length < 1001, "Length must be < 1001");
for (uint256 i = 0; i < _userAddresses.length; i++) {
users[_userAddresses[i]].numberPoints = users[_userAddresses[i]]
.numberPoints
.add(_numberPoints);
}
emit UserPointIncreaseMultiple(
_userAddresses,
_numberPoints,
_campaignId
);
}
/**
* @dev To increase the number of points for a team.
* Callable only by point admins
*/
function increaseTeamPoints(
uint256 _teamId,
uint256 _numberPoints,
uint256 _campaignId
) external onlyPoint {
// Increase the number of points for the team
teams[_teamId].numberPoints = teams[_teamId].numberPoints.add(
_numberPoints
);
emit TeamPointIncrease(_teamId, _numberPoints, _campaignId);
}
/**
* @dev To remove the number of points for a user.
* Callable only by point admins
*/
function removeUserPoints(address _userAddress, uint256 _numberPoints)
external
onlyPoint
{
// Increase the number of points for the user
users[_userAddress].numberPoints = users[_userAddress].numberPoints.sub(
_numberPoints
);
}
/**
* @dev To remove a set number of points for a set of users.
*/
function removeUserPointsMultiple(
address[] calldata _userAddresses,
uint256 _numberPoints
) external onlyPoint {
require(_userAddresses.length < 1001, "Length must be < 1001");
for (uint256 i = 0; i < _userAddresses.length; i++) {
users[_userAddresses[i]].numberPoints = users[_userAddresses[i]]
.numberPoints
.sub(_numberPoints);
}
}
/**
* @dev To remove the number of points for a team.
* Callable only by point admins
*/
function removeTeamPoints(uint256 _teamId, uint256 _numberPoints)
external
onlyPoint
{
// Increase the number of points for the team
teams[_teamId].numberPoints = teams[_teamId].numberPoints.sub(
_numberPoints
);
}
/**
* @dev To add a NFT contract address for users to set their profile.
* Callable only by owner admins.
*/
function addNftAddress(address _nftAddress) external onlyOwner {
require(
IERC721(_nftAddress).supportsInterface(0x80ac58cd),
"Not ERC721"
);
grantRole(NFT_ROLE, _nftAddress);
}
/**
* @dev Add a new teamId
* Callable only by owner admins.
*/
function addTeam(
string calldata _teamName,
string calldata _teamDescription
) external onlyOwner {
// Verify length is between 3 and 16
bytes memory strBytes = bytes(_teamName);
require(strBytes.length < 20, "Must be < 20");
require(strBytes.length > 3, "Must be > 3");
// Increment the _countTeams counter and get teamId
_countTeams.increment();
uint256 newTeamId = _countTeams.current();
// Add new team data to the struct
teams[newTeamId] = Team({
teamName: _teamName,
teamDescription: _teamDescription,
numberUsers: 0,
numberPoints: 0,
isJoinable: true
});
numberTeams = newTeamId;
emit TeamAdd(newTeamId, _teamName);
}
/**
* @dev Function to change team.
* Callable only by special admins.
*/
function changeTeam(address _userAddress, uint256 _newTeamId)
external
onlySpecial
{
require(hasRegistered[_userAddress], "User doesn't exist");
require(
(_newTeamId <= numberTeams) && (_newTeamId > 0),
"teamId doesn't exist"
);
require(teams[_newTeamId].isJoinable, "Team not joinable");
require(
users[_userAddress].teamId != _newTeamId,
"Already in the team"
);
// Get old teamId
uint256 oldTeamId = users[_userAddress].teamId;
// Change number of users in old team
teams[oldTeamId].numberUsers = teams[oldTeamId].numberUsers.sub(1);
// Change teamId in user mapping
users[_userAddress].teamId = _newTeamId;
// Change number of users in new team
teams[_newTeamId].numberUsers = teams[_newTeamId].numberUsers.add(1);
emit UserChangeTeam(_userAddress, oldTeamId, _newTeamId);
}
/**
* @dev Claim CAKE to burn later.
* Callable only by owner admins.
*/
function claimFee(uint256 _amount) external onlyOwner {
cakeToken.safeTransfer(_msgSender(), _amount);
}
/**
* @dev Make a team joinable again.
* Callable only by owner admins.
*/
function makeTeamJoinable(uint256 _teamId) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
teams[_teamId].isJoinable = true;
}
/**
* @dev Make a team not joinable.
* Callable only by owner admins.
*/
function makeTeamNotJoinable(uint256 _teamId) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
teams[_teamId].isJoinable = false;
}
/**
* @dev Rename a team
* Callable only by owner admins.
*/
function renameTeam(
uint256 _teamId,
string calldata _teamName,
string calldata _teamDescription
) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
// Verify length is between 3 and 16
bytes memory strBytes = bytes(_teamName);
require(strBytes.length < 20, "Must be < 20");
require(strBytes.length > 3, "Must be > 3");
teams[_teamId].teamName = _teamName;
teams[_teamId].teamDescription = _teamDescription;
}
/**
* @dev Update the number of CAKE to register
* Callable only by owner admins.
*/
function updateNumberCake(
uint256 _newNumberCakeToReactivate,
uint256 _newNumberCakeToRegister,
uint256 _newNumberCakeToUpdate
) external onlyOwner {
numberCakeToReactivate = _newNumberCakeToReactivate;
numberCakeToRegister = _newNumberCakeToRegister;
numberCakeToUpdate = _newNumberCakeToUpdate;
}
/**
* @dev Check the user's profile for a given address
*/
function getUserProfile(address _userAddress)
external
view
returns (
uint256,
uint256,
uint256,
address,
uint256,
bool
)
{
require(hasRegistered[_userAddress], "Not registered");
return (
users[_userAddress].userId,
users[_userAddress].numberPoints,
users[_userAddress].teamId,
users[_userAddress].nftAddress,
users[_userAddress].tokenId,
users[_userAddress].isActive
);
}
/**
* @dev Check the user's status for a given address
*/
function getUserStatus(address _userAddress) external view returns (bool) {
return (users[_userAddress].isActive);
}
/**
* @dev Check a team's profile
*/
function getTeamProfile(uint256 _teamId)
external
view
returns (
string memory,
string memory,
uint256,
uint256,
bool
)
{
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
return (
teams[_teamId].teamName,
teams[_teamId].teamDescription,
teams[_teamId].numberUsers,
teams[_teamId].numberPoints,
teams[_teamId].isJoinable
);
}
}
| 12,532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.