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
52
// This is how devs pay the bills
function withdrawDevShare() public auth { uint value = devBalance; devBalance = 0; msg.sender.transfer(value); }
function withdrawDevShare() public auth { uint value = devBalance; devBalance = 0; msg.sender.transfer(value); }
33,513
30
// swap account to remove with the last one then pop from the array.
address lastAccount = _accounts[_accounts.length - 1]; _accounts[removedAccountIndex - 1] = lastAccount; _accountIndexes[lastAccount] = removedAccountIndex; _accounts.pop(); delete _accountIndexes[account]; emit RemovedAccount(account);
address lastAccount = _accounts[_accounts.length - 1]; _accounts[removedAccountIndex - 1] = lastAccount; _accountIndexes[lastAccount] = removedAccountIndex; _accounts.pop(); delete _accountIndexes[account]; emit RemovedAccount(account);
27,174
106
// only owner address can set emergency pause 1 /
{ gamePaused = newStatus; }
{ gamePaused = newStatus; }
9,795
12
// Performs (an) / d, without scaling for precision.
function mulDiv( int256 a, int256 n, int256 d
function mulDiv( int256 a, int256 n, int256 d
22,234
23
// Event to show that implementation address has been changed newImplementation New address of the implementation /
event ImplementationChanged(address newImplementation);
event ImplementationChanged(address newImplementation);
53,293
99
// Mark claimed
b.drpu = 0; b.drps = 0;
b.drpu = 0; b.drps = 0;
6,370
11
// The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
uint eta;
18,805
336
// Reverts unless the roleId represents an initialized, exclusive roleId. /
modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; }
modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; }
9,123
191
// MainPool must be approved to spend the SYNR
synr.safeTransferFrom(user, address(this), tokenAmountOrID, "");
synr.safeTransferFrom(user, address(this), tokenAmountOrID, "");
34,987
13
// Lists the nft for borrowing. _tokenId The Id of the token. _contractAddress The address of the token contract. _percent The interest percentage expected. _duration The duration of the loan. _expectedAmount The loan amount expected. /
function listNFTforBorrowing( uint256 _tokenId, address _contractAddress, uint16 _percent, uint32 _duration, uint256 _expectedAmount ) external onlyOwnerOfToken(_contractAddress, _tokenId) whenNotPaused
function listNFTforBorrowing( uint256 _tokenId, address _contractAddress, uint16 _percent, uint32 _duration, uint256 _expectedAmount ) external onlyOwnerOfToken(_contractAddress, _tokenId) whenNotPaused
12,415
619
// Validate the Merkle roots
require(header.merkleRootBefore == S.merkleRoot, "INVALID_MERKLE_ROOT"); require(header.merkleRootAfter != header.merkleRootBefore, "EMPTY_BLOCK_DISABLED"); require(uint(header.merkleRootAfter) < ExchangeData.SNARK_SCALAR_FIELD(), "INVALID_MERKLE_ROOT");
require(header.merkleRootBefore == S.merkleRoot, "INVALID_MERKLE_ROOT"); require(header.merkleRootAfter != header.merkleRootBefore, "EMPTY_BLOCK_DISABLED"); require(uint(header.merkleRootAfter) < ExchangeData.SNARK_SCALAR_FIELD(), "INVALID_MERKLE_ROOT");
24,252
186
// Get the installed ACL app return ACL app/
function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); }
function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); }
34,538
110
// Flag indicating if fee payment in Custom Token transfer has been permanently finished or not.
bool public transferFeePaymentFinished;
bool public transferFeePaymentFinished;
7,964
34
// IEODAO提案合约/
contract proposalContract is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; IieoCoinContract public ieoCoinContract; uint256 public minUserVotePercent; uint256 public percentVote; uint256 public uVoteWeight; uint [] private magnification = [10,20,40,50,80]; uint [] private magnificationAmount = [10,20,25,40,50]; uint256 public proposalTime; constructor( IieoCoinContract _ieoCoinContract) public { initializeOwner(); ieoCoinContract = _ieoCoinContract; minUserVotePercent = 10; percentVote = 20; uVoteWeight = 1; proposalTime = 3 days; } struct IEOProposalInfo{ uint uTimestamp; uint256 proposalNO; address createAddress; address contractAddress; uint uDaoNumber; uint256 daoCollectAmount; uint256 passVoteNumber; uint256 unpassVoteNumber; uint256 daoAmount; uint256 txid; bool bPass; bool bDAOPay; uint256 userVoteNumber; } struct userVoteProposalInfo{ uint uTimestamp; bool bStatus; uint256 passVoteNumber; uint256 unpassVoteNumber; } struct peopleInfo{ uint uTimestamp; uint256 amount; uint256 zoomAmount; bool bPeople; uint256 uVoteWeight; bool bVoteEnabled; uint uStakeTime; uint proposalNO; } event CreateIeoDAOProposal(address who,uint256 proposalNO,address coinid,uint256 daoCollectAmount,uint256 uDAONumber,uint256 daoAmount,uint256 txid); event Stake(address who,address coinid,uint256 amount,uint uStakeTime); event UnStake(address who,address coinid,uint256 amount,uint256 zoomAmount); event Vote(address who,uint256 proposalNO,uint256 uStatus,uint256 amount,uint256 txid); event SetIeoCoinDao(uint256 prosoalNO,uint256 daoAmount,uint256 uDAONumber); mapping(uint256 => IEOProposalInfo) IEOProposal; mapping(address => mapping(uint256 => userVoteProposalInfo)) public userProposalVoteStatus; mapping(uint256 => uint256 ) proposalVoteTotal; mapping(address => mapping(address => peopleInfo)) people; mapping(address => uint256) currencyProposal; mapping(address=>uint256) coinTotalStake; mapping(address =>uint256 []) proposalNOList; function setieoCoinContract(IieoCoinContract _ieoCoinContract) public onlyOwner returns(bool){ require(address(_ieoCoinContract) != address(0)); ieoCoinContract = _ieoCoinContract; return true; } function getproposalTime() public view returns(uint){ return proposalTime; } function setproposalTime(uint _number) public onlyOwner returns(bool){ require(_number >0); proposalTime = _number; return true; } function getcurrencyProposal(address coinid) public view returns(uint256){ require(coinid != address(0)); return currencyProposal[coinid]; } function getpeopleInfo(address who,address coinid) public view returns(peopleInfo memory){ require(who != address(0)); require(coinid != address(0)); return people[who][coinid]; } function getproposalVoteTotal(uint256 proposalNO) public view returns(uint256){ require(proposalNO > 0); return proposalVoteTotal[proposalNO]; } function getmagnification(uint index) public view returns(uint){ require(index < 5); return magnification[index]; } function setmagnification(uint [] memory _magnification ) public onlyOwner returns(bool){ for(uint i = 0 ;i< 5;i++){ magnification[i] = _magnification[i]; } return true; } function getmagnificationAmount(uint index) public view returns(uint){ require(index < 5); return magnificationAmount[index]; } function setmagnificationAmount(uint [] memory _magnificationAmount ) public onlyOwner returns(bool){ for(uint i = 0 ;i< 5;i++){ magnificationAmount[i] = _magnificationAmount[i]; } return true; } function getTimeMagnification( uint times ) public view returns(uint){ uint mag = 10; if( times < 30 days ){ mag = magnification[0]; }else if( times >=30 days && times < 90 days ){ mag = magnification[1]; }else if( times >= 90 days && times < 180 days ){ mag = magnification[2]; }else if( times >= 180 days && times < 360 days ){ mag = magnification[3]; }else{ mag = magnification[4]; } return mag; } function getAmountMagnification( uint256 amount ,uint256 decimals ) public view returns(uint){ uint mag = 10; uint256 TOKENDECIMALS = 10 ** uint256(decimals); if( amount < 50000 * TOKENDECIMALS ){ mag = magnificationAmount[0]; }else if( amount >= 50000 * TOKENDECIMALS && amount < 100000 * TOKENDECIMALS ){ mag = magnificationAmount[1]; }else if( amount >= 100000 * TOKENDECIMALS && amount < 500000 * TOKENDECIMALS ){ mag = magnificationAmount[2]; }else if( amount >= 500000 * TOKENDECIMALS && amount < 1000000 * TOKENDECIMALS ){ mag = magnificationAmount[3]; }else{ mag = magnificationAmount[4]; } return mag; } function getminUserVotePercent() public view returns(uint256){ return minUserVotePercent; } function setminUserVotePercent(uint256 _number) public onlyOwner returns(bool){ require(_number > 0); minUserVotePercent = _number; } function getpercentVote() public view returns(uint256){ return percentVote; } function setpercentVote(uint256 _number) public onlyOwner returns(bool){ require(_number>0); percentVote = _number; return true; } function getproposalNOListLenth(address coinid) public view returns(uint){ return proposalNOList[coinid].length; } function getproposalNOListData(address coinid,uint index) public view returns(uint256){ require(index < proposalNOList[coinid].length); return proposalNOList[coinid][index]; } function getIEOProposal(uint256 proposalNO) public view returns(IEOProposalInfo memory){ require(proposalNO > 0); return IEOProposal[proposalNO]; } function getuserProposalVoteStatus(address who ,uint256 prosoalNO) public view returns(userVoteProposalInfo memory){ require(who != address(0)); require(prosoalNO > 0); return userProposalVoteStatus[who][prosoalNO]; } function checkDaoInfo(uint256 proposalNO,address coinid,uint256 daoAmount,uint256 txid) private returns(uint256,uint256){ address contractAddress; bool bDAO; uint uDaoNumber; uint256 daoCollectAmount; address createAddress; bool bExpired; (contractAddress,bDAO,uDaoNumber,daoCollectAmount,createAddress,bExpired) = ieoCoinContract.getieoCoinInfoByDao(coinid); require(bDAO); require(bExpired); require(createAddress == msg.sender ); require(daoCollectAmount > 0); IEOProposalInfo memory newIEOProposalInfo = IEOProposalInfo({ uTimestamp: block.timestamp, proposalNO: proposalNO, createAddress: createAddress, contractAddress: contractAddress, uDaoNumber: uDaoNumber, daoCollectAmount: daoCollectAmount, passVoteNumber: 0, unpassVoteNumber: 0, daoAmount: daoAmount, txid: txid, bPass: false, bDAOPay: false, userVoteNumber: 0 }); IEOProposal[proposalNO] = newIEOProposalInfo; return( daoCollectAmount,uDaoNumber); } function createIeoDAOProposal(uint256 proposalNO, address coinid,uint256 daoAmount,uint256 txid) public returns(bool){ require(coinid != address(0)); if( currencyProposal[coinid] == 0 ){ currencyProposal[coinid] = proposalNO; }else{ require(IEOProposal[currencyProposal[coinid]].uTimestamp + proposalTime <= block.timestamp) ; //过了提案指定时间,才可以发起另外一个提案 currencyProposal[coinid] = proposalNO; } uint256 daoCollectAmount; uint uDAONumber; (daoCollectAmount,uDAONumber) = checkDaoInfo(proposalNO,coinid,daoAmount,txid); require( daoAmount <= daoCollectAmount ); proposalNOList[coinid].push(proposalNO); emit CreateIeoDAOProposal(msg.sender,proposalNO,coinid,daoCollectAmount,uDAONumber, daoAmount,txid); return true; } function checkStatus(uint256 uStatus) private returns(bool){ uint ck = 0; if( uStatus == 1 ){ ck = ck.add(1); }else if( uStatus == 2 ){ ck = ck.add(1); }else{ ck = 0; } if( ck >0 ){ return true; } else{ return false; } } function stake(address coinid,uint256 amount,uint uStakeTime) public returns(bool){ require(msg.sender != address(0)); require(coinid != address(0)); require(amount>0); uint8 decimals = IERC20( coinid ).decimals(); uint old_uStakeTime = 0 ; if( people[msg.sender][coinid].uStakeTime > block.timestamp ){ old_uStakeTime = people[msg.sender][coinid].uStakeTime - block.timestamp; } uint256 magTime = getTimeMagnification(uStakeTime.add(old_uStakeTime)); uint256 magNum = getAmountMagnification(amount.add(people[msg.sender][coinid].amount),decimals); uint256 zoomAmount = amount.mul( magTime.mul(magNum)) ; zoomAmount = zoomAmount.div(100); uint256 voteWeight = uVoteWeight; if( people[msg.sender][coinid].proposalNO != currencyProposal[coinid] ){ people[msg.sender][coinid].proposalNO = currencyProposal[coinid]; } else{ if( people[msg.sender][coinid].bPeople ){ voteWeight = people[msg.sender][coinid].uVoteWeight; } } peopleInfo memory newpeopleInfo = peopleInfo({ uTimestamp: block.timestamp, amount: amount.add(people[msg.sender][coinid].amount), zoomAmount: zoomAmount.add(people[msg.sender][coinid].zoomAmount), bPeople: true, uVoteWeight: voteWeight, bVoteEnabled: false, uStakeTime: (uStakeTime.add(block.timestamp)).add(old_uStakeTime), proposalNO: currencyProposal[coinid] }); people[msg.sender][coinid] = newpeopleInfo; people[msg.sender][coinid].bVoteEnabled = true; people[msg.sender][coinid].uVoteWeight = voteWeight; coinTotalStake[coinid] = amount.add(coinTotalStake[coinid]); IERC20(coinid).safeTransferFrom(msg.sender, address(this), amount); emit Stake(msg.sender,coinid,amount,uStakeTime); return true; } function unStake(address coinid) public returns(bool){ require(msg.sender != address(0)); require(people[msg.sender][coinid].bPeople); require(people[msg.sender][coinid].uStakeTime <= block.timestamp); require(coinTotalStake[coinid] >= people[msg.sender][coinid].amount); uint256 amount = people[msg.sender][coinid].amount; uint256 zoomAmount = people[msg.sender][coinid].zoomAmount; people[msg.sender][coinid].amount = 0; people[msg.sender][coinid].zoomAmount = 0; people[msg.sender][coinid].bVoteEnabled = false; people[msg.sender][coinid].uVoteWeight = 0; if( coinTotalStake[coinid] >= amount ){ coinTotalStake[coinid] = (coinTotalStake[coinid]).sub(amount); } IERC20(coinid).safeTransferFrom(msg.sender, address(this), amount); emit UnStake(msg.sender,coinid,amount,zoomAmount); return true; } function vote(uint256 proposalNO,address coinid,uint256 uStatus) public returns(bool){ require( proposalNO >0); require( IEOProposal[proposalNO].createAddress != address(0) ); require( IEOProposal[proposalNO].uTimestamp + proposalTime >= block.timestamp); require( checkStatus(uStatus)); require( people[msg.sender][coinid].bVoteEnabled); require( userProposalVoteStatus[msg.sender][proposalNO].bStatus == false ); if( people[msg.sender][coinid].proposalNO != currencyProposal[coinid] ){ people[msg.sender][coinid].proposalNO = currencyProposal[coinid]; people[msg.sender][coinid].uVoteWeight = uVoteWeight; } require(people[msg.sender][coinid].uVoteWeight > 0 ); uint256 zoomAmount =people[msg.sender][coinid].zoomAmount; userVoteProposalInfo memory newuserVoteProposalInfo = userVoteProposalInfo({ uTimestamp: block.timestamp, bStatus: true, passVoteNumber: 0, unpassVoteNumber: 0 }); userProposalVoteStatus[msg.sender][proposalNO] = newuserVoteProposalInfo; if(uStatus == 2) { IEOProposal[proposalNO].passVoteNumber = zoomAmount.add(IEOProposal[proposalNO].passVoteNumber); userProposalVoteStatus[msg.sender][proposalNO].passVoteNumber = zoomAmount.add(userProposalVoteStatus[msg.sender][proposalNO].passVoteNumber); } else if( uStatus == 1 ){ IEOProposal[proposalNO].unpassVoteNumber = zoomAmount.add(IEOProposal[proposalNO].unpassVoteNumber); userProposalVoteStatus[msg.sender][proposalNO].unpassVoteNumber = zoomAmount.add(userProposalVoteStatus[msg.sender][proposalNO].unpassVoteNumber); } IEOProposal[proposalNO].userVoteNumber ++; proposalVoteTotal[proposalNO] = zoomAmount.add(proposalVoteTotal[proposalNO]); uint256 buyNoice; (buyNoice,) = ieoCoinContract.getieoCoinSallInfo(coinid); if( IEOProposal[proposalNO].userVoteNumber >= (buyNoice.mul(minUserVotePercent)).div(100) ){ uint256 voteAmount = (IEOProposal[proposalNO].passVoteNumber).mul(100); if( voteAmount.div( proposalVoteTotal[proposalNO] ) >= percentVote ){ IEOProposal[proposalNO].bPass = true; }else{ IEOProposal[proposalNO].bPass = false; } } emit Vote(msg.sender,proposalNO,uStatus,zoomAmount,IEOProposal[proposalNO].txid); return true; } function setIeoCoinDao(uint256 proposalNO ) private returns(bool){ uint256 uDaoNumber = IEOProposal[proposalNO].uDaoNumber; uint256 daoAmount = IEOProposal[proposalNO].daoAmount; ieoCoinContract.setIeoCoinDao( IEOProposal[proposalNO].contractAddress,daoAmount,uDaoNumber ); IEOProposal[proposalNO].bDAOPay = true; emit SetIeoCoinDao(proposalNO,daoAmount,uDaoNumber); return true; } function takeOut(uint256 proposalNO) public returns(bool){ require(proposalNO >0); require(msg.sender == IEOProposal[proposalNO].createAddress); require( IEOProposal[proposalNO].uTimestamp + proposalTime <= block.timestamp); if( IEOProposal[proposalNO].bPass){ if(IEOProposal[proposalNO].bDAOPay == false){ setIeoCoinDao(proposalNO); } } } }
contract proposalContract is Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; IieoCoinContract public ieoCoinContract; uint256 public minUserVotePercent; uint256 public percentVote; uint256 public uVoteWeight; uint [] private magnification = [10,20,40,50,80]; uint [] private magnificationAmount = [10,20,25,40,50]; uint256 public proposalTime; constructor( IieoCoinContract _ieoCoinContract) public { initializeOwner(); ieoCoinContract = _ieoCoinContract; minUserVotePercent = 10; percentVote = 20; uVoteWeight = 1; proposalTime = 3 days; } struct IEOProposalInfo{ uint uTimestamp; uint256 proposalNO; address createAddress; address contractAddress; uint uDaoNumber; uint256 daoCollectAmount; uint256 passVoteNumber; uint256 unpassVoteNumber; uint256 daoAmount; uint256 txid; bool bPass; bool bDAOPay; uint256 userVoteNumber; } struct userVoteProposalInfo{ uint uTimestamp; bool bStatus; uint256 passVoteNumber; uint256 unpassVoteNumber; } struct peopleInfo{ uint uTimestamp; uint256 amount; uint256 zoomAmount; bool bPeople; uint256 uVoteWeight; bool bVoteEnabled; uint uStakeTime; uint proposalNO; } event CreateIeoDAOProposal(address who,uint256 proposalNO,address coinid,uint256 daoCollectAmount,uint256 uDAONumber,uint256 daoAmount,uint256 txid); event Stake(address who,address coinid,uint256 amount,uint uStakeTime); event UnStake(address who,address coinid,uint256 amount,uint256 zoomAmount); event Vote(address who,uint256 proposalNO,uint256 uStatus,uint256 amount,uint256 txid); event SetIeoCoinDao(uint256 prosoalNO,uint256 daoAmount,uint256 uDAONumber); mapping(uint256 => IEOProposalInfo) IEOProposal; mapping(address => mapping(uint256 => userVoteProposalInfo)) public userProposalVoteStatus; mapping(uint256 => uint256 ) proposalVoteTotal; mapping(address => mapping(address => peopleInfo)) people; mapping(address => uint256) currencyProposal; mapping(address=>uint256) coinTotalStake; mapping(address =>uint256 []) proposalNOList; function setieoCoinContract(IieoCoinContract _ieoCoinContract) public onlyOwner returns(bool){ require(address(_ieoCoinContract) != address(0)); ieoCoinContract = _ieoCoinContract; return true; } function getproposalTime() public view returns(uint){ return proposalTime; } function setproposalTime(uint _number) public onlyOwner returns(bool){ require(_number >0); proposalTime = _number; return true; } function getcurrencyProposal(address coinid) public view returns(uint256){ require(coinid != address(0)); return currencyProposal[coinid]; } function getpeopleInfo(address who,address coinid) public view returns(peopleInfo memory){ require(who != address(0)); require(coinid != address(0)); return people[who][coinid]; } function getproposalVoteTotal(uint256 proposalNO) public view returns(uint256){ require(proposalNO > 0); return proposalVoteTotal[proposalNO]; } function getmagnification(uint index) public view returns(uint){ require(index < 5); return magnification[index]; } function setmagnification(uint [] memory _magnification ) public onlyOwner returns(bool){ for(uint i = 0 ;i< 5;i++){ magnification[i] = _magnification[i]; } return true; } function getmagnificationAmount(uint index) public view returns(uint){ require(index < 5); return magnificationAmount[index]; } function setmagnificationAmount(uint [] memory _magnificationAmount ) public onlyOwner returns(bool){ for(uint i = 0 ;i< 5;i++){ magnificationAmount[i] = _magnificationAmount[i]; } return true; } function getTimeMagnification( uint times ) public view returns(uint){ uint mag = 10; if( times < 30 days ){ mag = magnification[0]; }else if( times >=30 days && times < 90 days ){ mag = magnification[1]; }else if( times >= 90 days && times < 180 days ){ mag = magnification[2]; }else if( times >= 180 days && times < 360 days ){ mag = magnification[3]; }else{ mag = magnification[4]; } return mag; } function getAmountMagnification( uint256 amount ,uint256 decimals ) public view returns(uint){ uint mag = 10; uint256 TOKENDECIMALS = 10 ** uint256(decimals); if( amount < 50000 * TOKENDECIMALS ){ mag = magnificationAmount[0]; }else if( amount >= 50000 * TOKENDECIMALS && amount < 100000 * TOKENDECIMALS ){ mag = magnificationAmount[1]; }else if( amount >= 100000 * TOKENDECIMALS && amount < 500000 * TOKENDECIMALS ){ mag = magnificationAmount[2]; }else if( amount >= 500000 * TOKENDECIMALS && amount < 1000000 * TOKENDECIMALS ){ mag = magnificationAmount[3]; }else{ mag = magnificationAmount[4]; } return mag; } function getminUserVotePercent() public view returns(uint256){ return minUserVotePercent; } function setminUserVotePercent(uint256 _number) public onlyOwner returns(bool){ require(_number > 0); minUserVotePercent = _number; } function getpercentVote() public view returns(uint256){ return percentVote; } function setpercentVote(uint256 _number) public onlyOwner returns(bool){ require(_number>0); percentVote = _number; return true; } function getproposalNOListLenth(address coinid) public view returns(uint){ return proposalNOList[coinid].length; } function getproposalNOListData(address coinid,uint index) public view returns(uint256){ require(index < proposalNOList[coinid].length); return proposalNOList[coinid][index]; } function getIEOProposal(uint256 proposalNO) public view returns(IEOProposalInfo memory){ require(proposalNO > 0); return IEOProposal[proposalNO]; } function getuserProposalVoteStatus(address who ,uint256 prosoalNO) public view returns(userVoteProposalInfo memory){ require(who != address(0)); require(prosoalNO > 0); return userProposalVoteStatus[who][prosoalNO]; } function checkDaoInfo(uint256 proposalNO,address coinid,uint256 daoAmount,uint256 txid) private returns(uint256,uint256){ address contractAddress; bool bDAO; uint uDaoNumber; uint256 daoCollectAmount; address createAddress; bool bExpired; (contractAddress,bDAO,uDaoNumber,daoCollectAmount,createAddress,bExpired) = ieoCoinContract.getieoCoinInfoByDao(coinid); require(bDAO); require(bExpired); require(createAddress == msg.sender ); require(daoCollectAmount > 0); IEOProposalInfo memory newIEOProposalInfo = IEOProposalInfo({ uTimestamp: block.timestamp, proposalNO: proposalNO, createAddress: createAddress, contractAddress: contractAddress, uDaoNumber: uDaoNumber, daoCollectAmount: daoCollectAmount, passVoteNumber: 0, unpassVoteNumber: 0, daoAmount: daoAmount, txid: txid, bPass: false, bDAOPay: false, userVoteNumber: 0 }); IEOProposal[proposalNO] = newIEOProposalInfo; return( daoCollectAmount,uDaoNumber); } function createIeoDAOProposal(uint256 proposalNO, address coinid,uint256 daoAmount,uint256 txid) public returns(bool){ require(coinid != address(0)); if( currencyProposal[coinid] == 0 ){ currencyProposal[coinid] = proposalNO; }else{ require(IEOProposal[currencyProposal[coinid]].uTimestamp + proposalTime <= block.timestamp) ; //过了提案指定时间,才可以发起另外一个提案 currencyProposal[coinid] = proposalNO; } uint256 daoCollectAmount; uint uDAONumber; (daoCollectAmount,uDAONumber) = checkDaoInfo(proposalNO,coinid,daoAmount,txid); require( daoAmount <= daoCollectAmount ); proposalNOList[coinid].push(proposalNO); emit CreateIeoDAOProposal(msg.sender,proposalNO,coinid,daoCollectAmount,uDAONumber, daoAmount,txid); return true; } function checkStatus(uint256 uStatus) private returns(bool){ uint ck = 0; if( uStatus == 1 ){ ck = ck.add(1); }else if( uStatus == 2 ){ ck = ck.add(1); }else{ ck = 0; } if( ck >0 ){ return true; } else{ return false; } } function stake(address coinid,uint256 amount,uint uStakeTime) public returns(bool){ require(msg.sender != address(0)); require(coinid != address(0)); require(amount>0); uint8 decimals = IERC20( coinid ).decimals(); uint old_uStakeTime = 0 ; if( people[msg.sender][coinid].uStakeTime > block.timestamp ){ old_uStakeTime = people[msg.sender][coinid].uStakeTime - block.timestamp; } uint256 magTime = getTimeMagnification(uStakeTime.add(old_uStakeTime)); uint256 magNum = getAmountMagnification(amount.add(people[msg.sender][coinid].amount),decimals); uint256 zoomAmount = amount.mul( magTime.mul(magNum)) ; zoomAmount = zoomAmount.div(100); uint256 voteWeight = uVoteWeight; if( people[msg.sender][coinid].proposalNO != currencyProposal[coinid] ){ people[msg.sender][coinid].proposalNO = currencyProposal[coinid]; } else{ if( people[msg.sender][coinid].bPeople ){ voteWeight = people[msg.sender][coinid].uVoteWeight; } } peopleInfo memory newpeopleInfo = peopleInfo({ uTimestamp: block.timestamp, amount: amount.add(people[msg.sender][coinid].amount), zoomAmount: zoomAmount.add(people[msg.sender][coinid].zoomAmount), bPeople: true, uVoteWeight: voteWeight, bVoteEnabled: false, uStakeTime: (uStakeTime.add(block.timestamp)).add(old_uStakeTime), proposalNO: currencyProposal[coinid] }); people[msg.sender][coinid] = newpeopleInfo; people[msg.sender][coinid].bVoteEnabled = true; people[msg.sender][coinid].uVoteWeight = voteWeight; coinTotalStake[coinid] = amount.add(coinTotalStake[coinid]); IERC20(coinid).safeTransferFrom(msg.sender, address(this), amount); emit Stake(msg.sender,coinid,amount,uStakeTime); return true; } function unStake(address coinid) public returns(bool){ require(msg.sender != address(0)); require(people[msg.sender][coinid].bPeople); require(people[msg.sender][coinid].uStakeTime <= block.timestamp); require(coinTotalStake[coinid] >= people[msg.sender][coinid].amount); uint256 amount = people[msg.sender][coinid].amount; uint256 zoomAmount = people[msg.sender][coinid].zoomAmount; people[msg.sender][coinid].amount = 0; people[msg.sender][coinid].zoomAmount = 0; people[msg.sender][coinid].bVoteEnabled = false; people[msg.sender][coinid].uVoteWeight = 0; if( coinTotalStake[coinid] >= amount ){ coinTotalStake[coinid] = (coinTotalStake[coinid]).sub(amount); } IERC20(coinid).safeTransferFrom(msg.sender, address(this), amount); emit UnStake(msg.sender,coinid,amount,zoomAmount); return true; } function vote(uint256 proposalNO,address coinid,uint256 uStatus) public returns(bool){ require( proposalNO >0); require( IEOProposal[proposalNO].createAddress != address(0) ); require( IEOProposal[proposalNO].uTimestamp + proposalTime >= block.timestamp); require( checkStatus(uStatus)); require( people[msg.sender][coinid].bVoteEnabled); require( userProposalVoteStatus[msg.sender][proposalNO].bStatus == false ); if( people[msg.sender][coinid].proposalNO != currencyProposal[coinid] ){ people[msg.sender][coinid].proposalNO = currencyProposal[coinid]; people[msg.sender][coinid].uVoteWeight = uVoteWeight; } require(people[msg.sender][coinid].uVoteWeight > 0 ); uint256 zoomAmount =people[msg.sender][coinid].zoomAmount; userVoteProposalInfo memory newuserVoteProposalInfo = userVoteProposalInfo({ uTimestamp: block.timestamp, bStatus: true, passVoteNumber: 0, unpassVoteNumber: 0 }); userProposalVoteStatus[msg.sender][proposalNO] = newuserVoteProposalInfo; if(uStatus == 2) { IEOProposal[proposalNO].passVoteNumber = zoomAmount.add(IEOProposal[proposalNO].passVoteNumber); userProposalVoteStatus[msg.sender][proposalNO].passVoteNumber = zoomAmount.add(userProposalVoteStatus[msg.sender][proposalNO].passVoteNumber); } else if( uStatus == 1 ){ IEOProposal[proposalNO].unpassVoteNumber = zoomAmount.add(IEOProposal[proposalNO].unpassVoteNumber); userProposalVoteStatus[msg.sender][proposalNO].unpassVoteNumber = zoomAmount.add(userProposalVoteStatus[msg.sender][proposalNO].unpassVoteNumber); } IEOProposal[proposalNO].userVoteNumber ++; proposalVoteTotal[proposalNO] = zoomAmount.add(proposalVoteTotal[proposalNO]); uint256 buyNoice; (buyNoice,) = ieoCoinContract.getieoCoinSallInfo(coinid); if( IEOProposal[proposalNO].userVoteNumber >= (buyNoice.mul(minUserVotePercent)).div(100) ){ uint256 voteAmount = (IEOProposal[proposalNO].passVoteNumber).mul(100); if( voteAmount.div( proposalVoteTotal[proposalNO] ) >= percentVote ){ IEOProposal[proposalNO].bPass = true; }else{ IEOProposal[proposalNO].bPass = false; } } emit Vote(msg.sender,proposalNO,uStatus,zoomAmount,IEOProposal[proposalNO].txid); return true; } function setIeoCoinDao(uint256 proposalNO ) private returns(bool){ uint256 uDaoNumber = IEOProposal[proposalNO].uDaoNumber; uint256 daoAmount = IEOProposal[proposalNO].daoAmount; ieoCoinContract.setIeoCoinDao( IEOProposal[proposalNO].contractAddress,daoAmount,uDaoNumber ); IEOProposal[proposalNO].bDAOPay = true; emit SetIeoCoinDao(proposalNO,daoAmount,uDaoNumber); return true; } function takeOut(uint256 proposalNO) public returns(bool){ require(proposalNO >0); require(msg.sender == IEOProposal[proposalNO].createAddress); require( IEOProposal[proposalNO].uTimestamp + proposalTime <= block.timestamp); if( IEOProposal[proposalNO].bPass){ if(IEOProposal[proposalNO].bDAOPay == false){ setIeoCoinDao(proposalNO); } } } }
19,563
12
// ================================ ADMIN FUNCTIONS ================================ / Logic for creating Collection mapping entry This function is to migrate data from previous nft deployments Will set admin in record to defaultAdmin collectionNo string String for serialization of label price uint256 How many NFT's for the collection deployedAt address idCounter uint256 How many NFT's for the collection maxNfts uint256 How many NFT's for the collection /
function migrateCollectionData( string memory collectionNo, uint16 price, address deployedAt, uint16 idCounter, uint16 maxNfts
function migrateCollectionData( string memory collectionNo, uint16 price, address deployedAt, uint16 idCounter, uint16 maxNfts
29,597
932
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
_adjustCumulativeFeeMultiplier(reward, _pfc());
9,453
22
// Contains the business logic for the bridge via Multichain/_bridgeData the core information needed for bridging/_multichainData data specific to Multichain/underlyingToken the underlying token to swap/isNative denotes whether the token is a native token vs ERC20
function _startBridge( ILiFi.BridgeData memory _bridgeData, MultichainData memory _multichainData, address underlyingToken, bool isNative
function _startBridge( ILiFi.BridgeData memory _bridgeData, MultichainData memory _multichainData, address underlyingToken, bool isNative
26,990
5
// Deposit Joe account address amount token amount /
function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "CompoundingJoe::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); }
function _deposit(address account, uint amount) internal { require(DEPOSITS_ENABLED == true, "CompoundingJoe::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint unclaimedRewards = checkReward(); if (unclaimedRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(unclaimedRewards); } } require(depositToken.transferFrom(msg.sender, address(this), amount)); _stakeDepositTokens(amount); _mint(account, getSharesForDepositTokens(amount)); totalDeposits = totalDeposits.add(amount); emit Deposit(account, amount); }
9,322
13
// Creates a new vault for the product & maps the new vault address to the vaultMetadata _tokenName is the name of the token for the vault _tokenSymbol is the symbol for the vault's token _vaultStart is the timestamp of the vault's start /
function createVault( string memory _tokenName, string memory _tokenSymbol, uint256 _vaultStart
function createVault( string memory _tokenName, string memory _tokenSymbol, uint256 _vaultStart
42,371
97
// set's maintainnance address /
function setMaintainaceFeeAddress(address payable wallet) external onlyOwner { maintainanceAddress = wallet; }
function setMaintainaceFeeAddress(address payable wallet) external onlyOwner { maintainanceAddress = wallet; }
26,946
2
// the UNIX timestamp start date of the crowdsale
uint public startsAt;
uint public startsAt;
42,050
69
// Intermediate step to move shares to this contract before withdrawing NOTE: No need for share transfer if this contract is `sender`
if (sender != address(this)) vaults[id].transferFrom(sender, address(this), availableShares); if (amount != WITHDRAW_EVERYTHING) {
if (sender != address(this)) vaults[id].transferFrom(sender, address(this), availableShares); if (amount != WITHDRAW_EVERYTHING) {
21,930
28
// In case we rebalance the leveling costs this fixes the skill points to correct players
function fixSkillPoints(address _player) public { uint256 level = _getLevel(_player); uint256 currentSkillPoints = skillPoints[_player]; uint256 totalSkillsLearned = skillsLearned[_player][BURN_ID] + skillsLearned[_player][FATIGUE_ID] + skillsLearned[_player][DEPOT_ID] + skillsLearned[_player][DOGE_WALKER_ID] + skillsLearned[_player][TOOLS_ID] + skillsLearned[_player][DOGES_ID]; uint256 correctSkillPoints = level - 1; if(level == DGM_LEVELS.length){ // last level has 2 skill points correctSkillPoints++; } if(correctSkillPoints > currentSkillPoints + totalSkillsLearned){ skillPoints[_player] += correctSkillPoints - currentSkillPoints - totalSkillsLearned; } }
function fixSkillPoints(address _player) public { uint256 level = _getLevel(_player); uint256 currentSkillPoints = skillPoints[_player]; uint256 totalSkillsLearned = skillsLearned[_player][BURN_ID] + skillsLearned[_player][FATIGUE_ID] + skillsLearned[_player][DEPOT_ID] + skillsLearned[_player][DOGE_WALKER_ID] + skillsLearned[_player][TOOLS_ID] + skillsLearned[_player][DOGES_ID]; uint256 correctSkillPoints = level - 1; if(level == DGM_LEVELS.length){ // last level has 2 skill points correctSkillPoints++; } if(correctSkillPoints > currentSkillPoints + totalSkillsLearned){ skillPoints[_player] += correctSkillPoints - currentSkillPoints - totalSkillsLearned; } }
22,665
145
// Function for changing pending validators limit._pendingValidatorsLimit - new pending validators limit. When it's exceeded, the deposits will be set for the activation./
function setPendingValidatorsLimit(uint256 _pendingValidatorsLimit) external;
function setPendingValidatorsLimit(uint256 _pendingValidatorsLimit) external;
51,076
176
// Assuming the given array does contain the given element
function _removeArrayElement(uint256[] storage arr, uint256 el) internal { uint256 lastIndex = arr.length - 1; if (lastIndex != 0) { uint256 replaced = arr[lastIndex]; if (replaced != el) { // Shift elements until the one being removed is replaced do { uint256 replacing = replaced; replaced = arr[lastIndex - 1]; lastIndex--; arr[lastIndex] = replacing; } while (replaced != el && lastIndex != 0); } } // Remove the last (and quite probably the only) element arr.pop(); }
function _removeArrayElement(uint256[] storage arr, uint256 el) internal { uint256 lastIndex = arr.length - 1; if (lastIndex != 0) { uint256 replaced = arr[lastIndex]; if (replaced != el) { // Shift elements until the one being removed is replaced do { uint256 replacing = replaced; replaced = arr[lastIndex - 1]; lastIndex--; arr[lastIndex] = replacing; } while (replaced != el && lastIndex != 0); } } // Remove the last (and quite probably the only) element arr.pop(); }
41,753
26
// in case refunds are needed, money can be returned to the contract and contract switched to mode refunding
function prepareRefund() public payable onlyOwner() { require(crowdsaleClosed); require(msg.value == ethReceivedPresale.add(ethReceivedMain)); // make sure that proper amount of ether is sent currentStep = Step.Refunding; }
function prepareRefund() public payable onlyOwner() { require(crowdsaleClosed); require(msg.value == ethReceivedPresale.add(ethReceivedMain)); // make sure that proper amount of ether is sent currentStep = Step.Refunding; }
33,109
37
// Get random uint
function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); }
function _rand() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.difficulty, block.timestamp, entropySauce))); }
76,497
33
// render a token's art _id of token seed for randomness counts of colors and shapes dials for shape generator switches for renderer optionsreturn the SVG graphiccs of the token /
function perpetualRenderer(uint _id, string memory seed, uint256[2] memory counts, int256[13] memory dials, bool[3] memory switches) public view returns (string memory){ bytes memory buffer = new bytes(8192); Buffer.append(buffer, header); // initilized RNG with the seed and blocks 0 through 1 bytes32[] memory pool = Random.init(0, 1, Random.stringToUint(seed)); // generate colors uint256[] memory colorValues = new uint256[](counts[0]); for(uint256 i=0; i<counts[0]; i++) colorValues[i] = _generateColor(pool, _id); // generate shapes uint hybrid = uint(dials[8]); // hatching mod. 1 in hybrid shapes will be hatching for(uint i=0; i<counts[1]; i++) { uint colorRand = uint256(Random.uniform(pool, 0, int256(counts[0].sub(1)))); (int[2] memory positions, uint[2] memory size) = _generateShape(pool, dials, (hybrid > 0 && i.mod(hybrid) == 0)); Buffer.rect(buffer, positions, size, colorValues[colorRand]); } // generate the footer with mirroring transforms int[4] memory mirrorDials = [dials[9], dials[10], dials[11], dials[12]]; Buffer.append(buffer, _generateFooter(switches, mirrorDials)); return Buffer.toString(buffer); }
function perpetualRenderer(uint _id, string memory seed, uint256[2] memory counts, int256[13] memory dials, bool[3] memory switches) public view returns (string memory){ bytes memory buffer = new bytes(8192); Buffer.append(buffer, header); // initilized RNG with the seed and blocks 0 through 1 bytes32[] memory pool = Random.init(0, 1, Random.stringToUint(seed)); // generate colors uint256[] memory colorValues = new uint256[](counts[0]); for(uint256 i=0; i<counts[0]; i++) colorValues[i] = _generateColor(pool, _id); // generate shapes uint hybrid = uint(dials[8]); // hatching mod. 1 in hybrid shapes will be hatching for(uint i=0; i<counts[1]; i++) { uint colorRand = uint256(Random.uniform(pool, 0, int256(counts[0].sub(1)))); (int[2] memory positions, uint[2] memory size) = _generateShape(pool, dials, (hybrid > 0 && i.mod(hybrid) == 0)); Buffer.rect(buffer, positions, size, colorValues[colorRand]); } // generate the footer with mirroring transforms int[4] memory mirrorDials = [dials[9], dials[10], dials[11], dials[12]]; Buffer.append(buffer, _generateFooter(switches, mirrorDials)); return Buffer.toString(buffer); }
16,898
1
// Resize array
assembly { mstore(indexes, treesAdded) }
assembly { mstore(indexes, treesAdded) }
16,225
7
// Assign new interal gas limit requirement for exec()/Only callable by sysAdmin/_newRequirement New internal gas requirement
function setInternalGasRequirement(uint256 _newRequirement) external;
function setInternalGasRequirement(uint256 _newRequirement) external;
11,655
265
// Deleverages until we're supplying <x> amount 1. Redeem <x> DAI 2. Repay <x> DAI
function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); uint256 _redeemAndRepay; do { // Since we're only leveraging on 1 asset // redeemable = borrowable _redeemAndRepay = getBorrowable(); if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cwant).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(want).safeApprove(cwant, 0); IERC20(want).safeApprove(cwant, _redeemAndRepay); require(ICToken(cwant).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); }
function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); uint256 _redeemAndRepay; do { // Since we're only leveraging on 1 asset // redeemable = borrowable _redeemAndRepay = getBorrowable(); if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cwant).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(want).safeApprove(cwant, 0); IERC20(want).safeApprove(cwant, _redeemAndRepay); require(ICToken(cwant).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); }
56,799
7
// Staker Info
struct Staker { //Amount of tokens staked by the staker uint256 amountStaked; //Staked Tokens StakedToken[] stakedTokens; //Last time of the rewards were calculated for this user uint256 timeOfLastUpdate; //Calculated, but unclaimed rewards for the User. //The rewards are calculated each time the user writes to the Smart Contract uint256 unclaimedRewards; }
struct Staker { //Amount of tokens staked by the staker uint256 amountStaked; //Staked Tokens StakedToken[] stakedTokens; //Last time of the rewards were calculated for this user uint256 timeOfLastUpdate; //Calculated, but unclaimed rewards for the User. //The rewards are calculated each time the user writes to the Smart Contract uint256 unclaimedRewards; }
19,282
7
// This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. /
function _msgSender() internal override (Context, ERC721Tradable) view returns (address sender)
function _msgSender() internal override (Context, ERC721Tradable) view returns (address sender)
3,872
44
// ------------------------------------------------------------------------------- returns the miningTarget. -------------------------------------------------------------------------------
function getMiningTarget() public view returns(uint) { return miningTarget; }
function getMiningTarget() public view returns(uint) { return miningTarget; }
24,269
17
// (6)函數 function/ 函數(6-1):發起(召集)賽局(日期、開始時間、結束時間、規模)
function recruitGame( uint256 _date, StartTime _startTime, EndTime _endTime, GameScale _scale ) public onlyMember {
function recruitGame( uint256 _date, StartTime _startTime, EndTime _endTime, GameScale _scale ) public onlyMember {
4,333
2
// DEBT_POPPER_REWARDS, FIXED_TREASURY_REIMBURSEMENT_OVERLAY
AuthLike(0xe1d5181F0DD039aA4f695d4939d682C4cF874086).addAuthorization(0xf31e1df4f24D277073A40161B8F637b88988FaA2);
AuthLike(0xe1d5181F0DD039aA4f695d4939d682C4cF874086).addAuthorization(0xf31e1df4f24D277073A40161B8F637b88988FaA2);
6,703
1
// KYCed investors
mapping(address => bool) public whitelistedInvestors;
mapping(address => bool) public whitelistedInvestors;
60,938
27
// we do not want to revert the whole transaction if this operation fails, since EOTP is already revealed
if (!success) { spendingState.spentAmount -= amount; emit TransferError(dest, ret); return false; }
if (!success) { spendingState.spentAmount -= amount; emit TransferError(dest, ret); return false; }
25,478
5
// Events /
) Ownable() { mynft = Imynft(_mft); }
) Ownable() { mynft = Imynft(_mft); }
32,877
12
// Max bid that can be placed in an auction
uint256 maxBid;
uint256 maxBid;
14,655
6
// CONFIGURATION onlyOwner /
function setFactoryAddress(address _contractAddr) external onlyOwner { require(_contractAddr != address(0), "Address should be defined"); factoryContract = QapturProjectFactory(_contractAddr); _contracts[_contractAddr] = true; emit ContractAdressUpdated("Factory", _contractAddr); }
function setFactoryAddress(address _contractAddr) external onlyOwner { require(_contractAddr != address(0), "Address should be defined"); factoryContract = QapturProjectFactory(_contractAddr); _contracts[_contractAddr] = true; emit ContractAdressUpdated("Factory", _contractAddr); }
20,814
38
// extcodesize checks the size of the code stored in an address, and address returns the current address. Since the code is still not deployed when running a constructor, any checks on its code size will yield zero, making it an effective way to detect if a contract is under construction or not.
address self = address(this); uint256 cs;
address self = address(this); uint256 cs;
2,262
16
// record burnt nft
burnt[ids[i]] = users[i]; userBurnt[users[i]].push(ids[i]); burntBalance[users[i]] += 1; totalBurnt += 1; if (newBurner == true) { burntCount += 1; newBurner = false; }
burnt[ids[i]] = users[i]; userBurnt[users[i]].push(ids[i]); burntBalance[users[i]] += 1; totalBurnt += 1; if (newBurner == true) { burntCount += 1; newBurner = false; }
2,458
124
// Transfer tokens from msg.sender back to DAO.
_governingToken.transferFrom(msg.sender, address(this), amount_);
_governingToken.transferFrom(msg.sender, address(this), amount_);
1,884
88
// Define if the game has started
bool private gameStarted;
bool private gameStarted;
3,474
183
// Calculate pending rewards for a user user address of the user /
function _calculatePendingRewards(address user) internal view returns (uint256) { return ((userInfo[user].shares * (_rewardPerToken() - (userInfo[user].userRewardPerTokenPaid))) / PRECISION_FACTOR) + userInfo[user].rewards; }
function _calculatePendingRewards(address user) internal view returns (uint256) { return ((userInfo[user].shares * (_rewardPerToken() - (userInfo[user].userRewardPerTokenPaid))) / PRECISION_FACTOR) + userInfo[user].rewards; }
52,839
3
// active snapshot time slot (granularity of 1 hour) max possible timestamp - Dec 08 3883
uint24 headSlot;
uint24 headSlot;
12,761
71
// Returns the number of tokens owned by this contract/_assetId The address of the token to query
function externalBalance(address _assetId) public view returns (uint256) { if (_assetId == ETHER_ADDR) { return address(this).balance; } return tokenBalance(_assetId); }
function externalBalance(address _assetId) public view returns (uint256) { if (_assetId == ETHER_ADDR) { return address(this).balance; } return tokenBalance(_assetId); }
42,966
37
// Checks if there is proposal with the new account and voter
for (uint i = 0; i < addresses.length; i++){
for (uint i = 0; i < addresses.length; i++){
29,182
211
// Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded
case 0 { success := 1 }
case 0 { success := 1 }
3,558
1
// Location storage loc = locations[trn];
return prevData[trn];
return prevData[trn];
29,328
6
// return the generator of G2
function P2() internal pure returns (G2Point memory) { // Original code point return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); /* // Changed by Jordi point return G2Point( [10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634], [8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531] ); */ }
function P2() internal pure returns (G2Point memory) { // Original code point return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); /* // Changed by Jordi point return G2Point( [10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634], [8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531] ); */ }
12,146
102
// Snapshots the totalSupply after it has been decreased. /
function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); }
function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); }
10,671
111
// _wNxm Address of the wNxm contract. _arNxm Address of the arNxm contract. _nxmMaster Address of Nexus' master address (to fetch others). _rewardManager Address of the ReferralRewards smart contract./
{ require(address(arNxm) == address(0), "Contract has already been initialized."); Ownable.initializeOwnable(); wNxm = IERC20(_wNxm); nxm = IERC20(_nxm); arNxm = IERC20(_arNxm); nxmMaster = INxmMaster(_nxmMaster); rewardManager = IRewardManager(_rewardManager); // unstakePercent = 100; adminPercent = 0; referPercent = 25; reserveAmount = 30 ether; pauseDuration = 10 days; beneficiary = msg.sender; // restakePeriod = 3 days; rewardDuration = 9 days; // Approve to wrap and send funds to reward manager. arNxm.approve( _rewardManager, uint256(-1) ); }
{ require(address(arNxm) == address(0), "Contract has already been initialized."); Ownable.initializeOwnable(); wNxm = IERC20(_wNxm); nxm = IERC20(_nxm); arNxm = IERC20(_arNxm); nxmMaster = INxmMaster(_nxmMaster); rewardManager = IRewardManager(_rewardManager); // unstakePercent = 100; adminPercent = 0; referPercent = 25; reserveAmount = 30 ether; pauseDuration = 10 days; beneficiary = msg.sender; // restakePeriod = 3 days; rewardDuration = 9 days; // Approve to wrap and send funds to reward manager. arNxm.approve( _rewardManager, uint256(-1) ); }
42,781
4
// Founder Role to enforce access controls
bytes32 public constant FOUNDER = keccak256("FOUNDER");
bytes32 public constant FOUNDER = keccak256("FOUNDER");
10,466
41
// Return array of all valid exchange wrappers. return address[]Array of valid exchange wrappers /
function exchanges() external view returns (address[] memory)
function exchanges() external view returns (address[] memory)
21,364
10
// Multi Send - Allows to batch multiple transactions into one./Nick Dodson - <nick.dodson@consensys.net>/Gonçalo Sá - <goncalo.sa@consensys.net>/Stefan George - <stefan@gnosis.io>/Richard Meissner - <richard@gnosis.io>
contract MultiSend { bytes32 constant private GUARD_VALUE = keccak256("multisend.guard.bytes32"); bytes32 guard; constructor() public { guard = GUARD_VALUE; } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public payable { require(guard != GUARD_VALUE, "MultiSend should only be called via delegatecall"); // solium-disable-next-line security/no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas, to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas, to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } }
contract MultiSend { bytes32 constant private GUARD_VALUE = keccak256("multisend.guard.bytes32"); bytes32 guard; constructor() public { guard = GUARD_VALUE; } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public payable { require(guard != GUARD_VALUE, "MultiSend should only be called via delegatecall"); // solium-disable-next-line security/no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas, to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas, to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } }
10,605
171
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); updateSubdivsFor(_customerAddress); updateSubdivsFor(_toAddress);
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); updateSubdivsFor(_customerAddress); updateSubdivsFor(_toAddress);
21,544
3
// Set allowance for other address and notify./ Allows `_spender` to transfer the specified TDT/ on your behalf and then ping the contract about it./ The `_spender` should implement the `tokenRecipient` interface below/ to receive approval notifications./_spender Address of contract authorized to spend./_tdtId The TDT they can spend./_extraData Extra information to send to the approved contract.
function approveAndCall(address _spender, uint256 _tdtId, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); approve(_spender, _tdtId); spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData); }
function approveAndCall(address _spender, uint256 _tdtId, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); approve(_spender, _tdtId); spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData); }
29,402
10
// 避免转帐的地址是0x0
require(_to != 0x0);
require(_to != 0x0);
25,562
43
// Hardcoded address to collect 5% dev team share.
address private constant DEV_TEAM_ADDRESS = 0xFFCF83437a1Eb718933f39ebE75aD96335BC1BE4;
address private constant DEV_TEAM_ADDRESS = 0xFFCF83437a1Eb718933f39ebE75aD96335BC1BE4;
23,721
0
// Constructor _securityToken Address of the security token _polyAddress Address of the polytoken /
constructor (address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress)
constructor (address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress)
21,718
91
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent);
require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent);
7,868
8
// Revert with an error when attempting to execute an 1155 batch transfer using calldata not produced by default ABI encoding or with different lengths for ids and amounts arrays. /
error Invalid1155BatchTransferEncoding();
error Invalid1155BatchTransferEncoding();
33,450
4
// abstract function - the default behaviour of LayerZero is blocking. See: NonblockingLzApp if you dont need to enforce ordered messaging
function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual;
8,064
39
// `freeze? Prevent | Allow` `target` from sending & receiving tokenstarget Address to be frozenfreeze either to freeze it or not/
function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenAccounts(target, freeze); }
function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenAccounts(target, freeze); }
12,933
54
// Segment must be signed by broadcaster
require( JobLib.validateBroadcasterSig( job.streamId, _segmentNumber, _dataHashes[0], _broadcasterSig, job.broadcasterAddress ) );
require( JobLib.validateBroadcasterSig( job.streamId, _segmentNumber, _dataHashes[0], _broadcasterSig, job.broadcasterAddress ) );
2,359
144
// Gets the allowed amounts to deposit for the `token`
function getAllowedAmounts() public view returns (uint256[4] memory) { return allowedAmounts; }
function getAllowedAmounts() public view returns (uint256[4] memory) { return allowedAmounts; }
44,186
110
// Called by a user that currently holds both short and long position tokens and would like to redeem them/ for their collateral./marketContractAddressaddress of the market contract to redeem tokens for/qtyToRedeemquantity of long / short tokens to redeem.
function redeemPositionTokens( address marketContractAddress, uint qtyToRedeem ) external onlyWhiteListedAddress(marketContractAddress)
function redeemPositionTokens( address marketContractAddress, uint qtyToRedeem ) external onlyWhiteListedAddress(marketContractAddress)
34,166
19
// store the rollups view of the datastore
l2BlockRollupStores[l2Block] = RollupStore({ dataStoreId: searchData.metadata.globalDataStoreId, confirmAt: uint32(block.timestamp + fraudProofPeriod), status: RollupStoreStatus.COMMITTED });
l2BlockRollupStores[l2Block] = RollupStore({ dataStoreId: searchData.metadata.globalDataStoreId, confirmAt: uint32(block.timestamp + fraudProofPeriod), status: RollupStoreStatus.COMMITTED });
14,056
99
// return array of reward token balances /
function balances() external view virtual returns (uint256[] memory);
function balances() external view virtual returns (uint256[] memory);
59,785
102
// If they have quads, they can't have royal flush, so we can return.
if (_maxSet==4) return HAND_FK;
if (_maxSet==4) return HAND_FK;
82,979
58
// we're processing the last milestone and balance, this means we're transferring everything left. this is done to make sure we've transferred everything, even "ether that got mistakenly sent to this address" as well as the emergency fund if it has not been used.
transferTokens = TokenEntity.balanceOf(address(this)); transferEther = this.balance;
transferTokens = TokenEntity.balanceOf(address(this)); transferEther = this.balance;
50,884
1
// SxT Request contract address
ISxTRelayProxy internal sxtRelayContract;
ISxTRelayProxy internal sxtRelayContract;
5,596
46
// let's declare the winner!
declareWinner(_group, winner);
declareWinner(_group, winner);
36,234
21
// A method to allow a stakeholder to withdraw his rewards. /
function withdrawReward(address _to) public onlyOwner { uint256 reward ; if (timestaked[_to] <= block.timestamp) { reward = calculateReward(_to); } else { uint256 time = (timestaked[_to] - block.timestamp); reward = (time * stakes[_to]) / 1000; } transfer(_to, stakes[_to]); _mint(_to, reward); removeStakeholder(_to); rewards[_to] = 0; stakes[_to] = 0; timestaked[_to] = 0; }
function withdrawReward(address _to) public onlyOwner { uint256 reward ; if (timestaked[_to] <= block.timestamp) { reward = calculateReward(_to); } else { uint256 time = (timestaked[_to] - block.timestamp); reward = (time * stakes[_to]) / 1000; } transfer(_to, stakes[_to]); _mint(_to, reward); removeStakeholder(_to); rewards[_to] = 0; stakes[_to] = 0; timestaked[_to] = 0; }
3,735
118
// governance header
chain.module = encoded.toBytes32(index); index += 32; require(chain.module == module, "invalid RegisterChain: wrong module"); chain.action = encoded.toUint8(index); index += 1; require(chain.action == 1, "invalid RegisterChain: wrong action"); chain.chainId = encoded.toUint16(index);
chain.module = encoded.toBytes32(index); index += 32; require(chain.module == module, "invalid RegisterChain: wrong module"); chain.action = encoded.toUint8(index); index += 1; require(chain.action == 1, "invalid RegisterChain: wrong action"); chain.chainId = encoded.toUint16(index);
4,464
204
// borrowAmountPlusInterestRateUSD x 10000 to be compared with USD values multiplied by LTs
uint256 borrowAmountPlusInterestRateUSD = priceOracle.convertToUSD( borrowAmountWithInterestAndFees, underlying ) * PERCENTAGE_FACTOR;
uint256 borrowAmountPlusInterestRateUSD = priceOracle.convertToUSD( borrowAmountWithInterestAndFees, underlying ) * PERCENTAGE_FACTOR;
29,141
10
// Add a ':' to the string to separate the prefix from the the date
bytesOutput.push(bytes1(":"));
bytesOutput.push(bytes1(":"));
21,838
90
// Determine the current account liquidity wrt collateral requirements account The account to determine liquidity forreturn (possible error code, account shortfall below collateral requirements) /
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, 0, 0, 0); }
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, 0, 0, 0); }
38,901
49
// Check for possible fee on transfer
v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) {
v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) {
21,528
4
// Emitted when Chainlink VRF fulfills a random number request.
event PackRandomnessFulfilled(uint256 indexed packId, uint256 indexed requestId);
event PackRandomnessFulfilled(uint256 indexed packId, uint256 indexed requestId);
3,005
3
// Sets the record for a _node. _node The _node to update. _owner The address of the new _owner. _resolver The address of the _resolver. _ttl The TTL in seconds. /
function setRecord(bytes32 _node, address _owner, address _resolver, uint64 _ttl) external override { setOwner(_node, _owner); _setResolverAndTTL(_node, _resolver, _ttl); }
function setRecord(bytes32 _node, address _owner, address _resolver, uint64 _ttl) external override { setOwner(_node, _owner); _setResolverAndTTL(_node, _resolver, _ttl); }
10,405
131
// Admin Events // Event emitted when pendingAdmin is changed /
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
13,111
0
// user address to stream address mapping
mapping(address => address) public userStreams;
mapping(address => address) public userStreams;
77,818
190
// This function will set value based on ParamType _parameter - Enum value indicating ParamType (0,1,2,3) _value - Value to be setreturn - Boolean status - True indicating successful completionAccess Control: Only Owner /
function setParamType(ParamType _parameter, uint256 _value) public onlyOwner() returns (bool)
function setParamType(ParamType _parameter, uint256 _value) public onlyOwner() returns (bool)
4,417
2
// sets offchain reporting protocol configuration incl. participating oracles feedId Feed ID to set config for signers addresses with which oracles sign the reports offchainTransmitters CSA key for the ith Oracle f number of faulty oracles the system can tolerate onchainConfig serialized configuration used by the contract (and possibly oracles) offchainConfigVersion version number for offchainEncoding schema offchainConfig serialized configuration used by the oracles exclusively and only passed through the contract /
function setConfig( bytes32 feedId, address[] memory signers, bytes32[] memory offchainTransmitters, uint8 f, bytes memory onchainConfig,
function setConfig( bytes32 feedId, address[] memory signers, bytes32[] memory offchainTransmitters, uint8 f, bytes memory onchainConfig,
20,243
0
// Gets the current value set in the contract for the `msg.sender`. /
function value() public view returns (uint256) { return values[msg.sender]; }
function value() public view returns (uint256) { return values[msg.sender]; }
14,345
41
// return the symbol of the token. /
function symbol() public view returns (string memory) { return _symbol; }
function symbol() public view returns (string memory) { return _symbol; }
26,859
16
// Ends the sale /
function endSale() public onlyOwner { require(state == State.Active || state == State.Dormant); state = State.Successful; emit SuccessfulState(); selfdestruct(owner); }
function endSale() public onlyOwner { require(state == State.Active || state == State.Dormant); state = State.Successful; emit SuccessfulState(); selfdestruct(owner); }
41,820
4
// If Formula 1 < 0 or Formula 1 causes dividing by 0, then the system will use Formula 2./ Otherwise, it is always the lowest amount calculated by Formula1 or Formula2.
function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors) public view override returns (uint256)
function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors) public view override returns (uint256)
48,713
5
// Commit block is the block we are committing this item to the queue.
uint256 commitBlock = block.number;
uint256 commitBlock = block.number;
38,304
381
// Tell if a vote can be executed_vote Vote instance being queried return True if the vote can be executed/
function _canExecute(Vote storage _vote) internal view returns (bool) { // If the vote is executed, paused, or cancelled, it cannot be executed if (!_isNormal(_vote)) { return false; } Setting storage setting = settings[_vote.settingId]; // If the vote is still open, it cannot be executed if (!_hasEnded(_vote, setting)) { return false; } // If the vote's execution delay has not finished yet, it cannot be executed if (!_hasFinishedExecutionDelay(_vote, setting)) { return false; } // Check the vote has enough support and has reached the min quorum return _isAccepted(_vote, setting); }
function _canExecute(Vote storage _vote) internal view returns (bool) { // If the vote is executed, paused, or cancelled, it cannot be executed if (!_isNormal(_vote)) { return false; } Setting storage setting = settings[_vote.settingId]; // If the vote is still open, it cannot be executed if (!_hasEnded(_vote, setting)) { return false; } // If the vote's execution delay has not finished yet, it cannot be executed if (!_hasFinishedExecutionDelay(_vote, setting)) { return false; } // Check the vote has enough support and has reached the min quorum return _isAccepted(_vote, setting); }
52,520
122
// - Inherited contracts for security and token compliancy
contract Vault is ReentrancyGuard { using SafeERC20 for IERC20; /// @dev Custom Errors error NoTokensDepositError(); /// @notice ERC20 token for interest payments IERC20 public BRX; IERC20 public USDC; /// @notice Global variables to keep track of the accounts and the deposits they make mapping(address => uint256) public brxTokenBalance; /// @notice Mappings for the USDC token mapping(address => uint256) public usdcTokenBalance; /// @notice Deployer of the contract gains permission to supply interest as collateral address payable owner; /// @notice Admin address for the contract address adminAddress; /// @notice Wallet address for unrefundable portion of payments address fundsAddress; /// @notice The address of the contract the handles the ICO functions address swapAddress; /// @notice Set the basis points penalty for early widthdrawal uint256 public penalty; // bps /// @notice Total amount of BRX in the contract uint256 public brxTotal; /// @notice Total amount of USDC in the contract uint256 public usdcTotal; /// @dev Events for proper vault functionality and transaction execution event Minted(address indexed minter, uint256 amount); event BRX_Supplied(address indexed depositer, uint256 amount, uint256 timestamp); event BRX_Removed(address indexed depositer, uint256 amount, uint256 timestamp); event BRXPurchased(address indexed purchaser, uint256 usdcAmount, uint256 cmtAllotedAmount); event TokenWithdraw(address indexed user, bytes32 token, uint256 payment); event RemovedPaymentTokens(address indexed owner, uint256 amount); event AddedPaymentTokens(address indexed owner, uint256 amount); event Refund(address indexed _buyer, uint256 _amount); event SetPenalty(uint256 _penalty); event SetSwapAddress(address _swapAddress); event SetFundsAddress(address _fundsAddress); /// @param _fundsAddress Wallet address to recieve unrefundable portion of payments constructor (address token, address _fundsAddress) { require((_fundsAddress!=address(0)), "fundsAddress invalid"); owner = payable(msg.sender); BRX = IERC20(token); fundsAddress = _fundsAddress; } /// @notice Admin address can be changed by owner function setAdminAddress(address _address) public onlyOwner { adminAddress = _address; } /// @param _fundsAddress Address for penalties to get routed to upon BRX purchase function setFundsAddress(address _fundsAddress) public onlyOwner { require(_fundsAddress!=address(0), "fundsAddress cannot be zero"); fundsAddress = _fundsAddress; emit SetFundsAddress(_fundsAddress); } /// @param _swapAddress Address for the swap contract function setSwapAddress(address _swapAddress) public onlyOwner { require(_swapAddress!=address(0), "swapAddress cannot be zero"); swapAddress = _swapAddress; emit SetSwapAddress(_swapAddress); } /// @notice Sets the token that will be used for payments (USDC) function setPaymentToken(address token) public onlyOwner { USDC = IERC20(token); } /// @notice Can withdraw entire payment token supply held inside of the Vault /// @param _amount The amount of USDC to be removed from the vault function removePaymentTokens(uint256 _amount) public onlyAdmin { require(_amount > 0, "The amount must be greater than zero"); require(usdcTotal >= _amount, "There are not enough USDC tokens in the vault"); usdcTotal -= _amount; emit RemovedPaymentTokens(tx.origin, usdcTotal); USDC.safeTransfer(tx.origin, _amount); } /// @param _amount The amount of USDC to add to the vault function addPaymentTokens(uint256 _amount) public onlyOwner { require(_amount > 0, "No tokens where added"); usdcTotal += _amount; emit AddedPaymentTokens(tx.origin, _amount); USDC.safeTransferFrom(tx.origin, address(this), _amount); } /// @param _amount The amount of BRX to add to the Vault function supplyBRX (uint256 _amount) public onlyOwner { require(_amount > 0, "You need to deposit some tokens"); brxTotal += _amount; emit BRX_Supplied( tx.origin, _amount, block.timestamp ); BRX.safeTransferFrom(tx.origin, address(this), _amount); } /// @param _amount This is the amount of BRX to be removed by contract owner function removeBRX (uint256 _amount) public onlyAdmin { require(_amount > 0, "The amount must be greater than zero"); require(brxTotal >= _amount, "There are not enough BRX tokens in the vault"); brxTotal -= _amount; emit BRX_Removed( msg.sender, brxTotal, block.timestamp ); BRX.safeTransfer(tx.origin, _amount); } /// @notice Checks the balance of BRX function balanceOfBRX() public view returns(uint256) { return brxTotal; } /// @notice Checks the balance of USDC in the contract function balanceOfUSDC() public view returns(uint256) { return usdcTotal; } /// @param _amount Amount of basis points to set penalty function setPenaltyAmount(uint256 _amount) public onlyOwner { penalty = _amount * 100; emit SetPenalty(penalty); } /// @return Returns the penalty amount that was set function getPenaltyAmount() public view returns(uint256) { return penalty; } /// @return Returns the fundsAddress function getFundsAddress() public view returns (address) { return fundsAddress; } /// @return Returns the swapAddress function getSwapAddress() public view returns (address) { return swapAddress; } /// @notice Returns the adminAddress function getAdminAddress() public view returns (address) { return adminAddress; } /// @notice Admin functions accessible only by admin address modifier onlyAdmin() { require(msg.sender == adminAddress, "Only admin can call this function."); _; } /// @dev Allows only the deployer / supplier to use the function modifier onlyOwner() { require(tx.origin == owner, "This address is not the owner"); _; } /// @dev Allows only the swap contract to use this function modifier onlySwap() { require(msg.sender == swapAddress, "This address is not the swap contract"); _; } /** @param _user Address purchasing BRX @param _usdcAmount Amount of USDC being swapped for BRX @param _brxAmount Requested amount of BRX being purchased */ function buyBRX(address _user, uint256 _usdcAmount, uint256 _brxAmount) public onlySwap nonReentrant { require (_user != address(0), "Invalid address"); if (_usdcAmount <= 0) { revert NoTokensDepositError(); } /// @notice Penalty amount for BRX purchase uint256 unrefundableAmount = _usdcAmount * penalty / 10000; uint256 storedAmount = _usdcAmount - unrefundableAmount; /// @dev USDC and BRX token balances for each user who interact with the Vault usdcTokenBalance[_user] += storedAmount; brxTokenBalance[_user] += _brxAmount; /// @dev USDC Total amount being stored inside of the Vault usdcTotal += storedAmount; /// @dev _user can only be sent from the swap contract so not aritrary (slither) /// @dev Penalty portion of payment sent to fundsAddress upon BRX purchase USDC.safeTransferFrom(_user, fundsAddress, unrefundableAmount); /// @dev Maximum refundable portion of payment sent to vault USDC.safeTransferFrom(_user, address(this), storedAmount); /// @dev BRXPurchased event emit BRXPurchased(_user, _usdcAmount, _brxAmount); } /// @notice Allows an account to withdraw the BRX that was purchased /// @param _user The buyers address /// @param _amount The amount of BRX to send to the buyer function withdraw(address _user, uint256 _amount, uint256 _usdcAdjustment) public onlySwap { require(_amount <= brxTokenBalance[_user], "The amount is greater than your balance"); require(_amount > 0, "The amount must be greater than zero"); require(_amount <= brxTotal, "Please contact support"); /// @dev Adjusts the balances of the users account brxTokenBalance[_user] -= _amount; usdcTokenBalance[_user] -= _usdcAdjustment; /// @dev Removes the BRX that was sent from the total amount in the contract brxTotal -= _amount; /// @dev Allows a BRX token withdraw event from the verified sender emit TokenWithdraw( msg.sender, 'BRX', _amount ); /// @dev Sends the BRX to the buyer who requested a withdraw BRX.safeTransfer(_user, _amount); } /** @notice Refunds USDC to buyer @param _buyer The buyer's address @param _amount The amount to be refunded @param _brxAdjustment The amount of BRX to be removed from the buyers account */ function refund(address _buyer, uint256 _amount, uint256 _brxAdjustment) public onlySwap { require(_amount <= usdcTokenBalance[_buyer], "The amount is greater than the buyer's balance"); require(_amount > 0, "The amount must be greater than zero"); require(_amount <= usdcTotal, "Please contact support"); /// @dev Adjust the balances of the users account usdcTokenBalance[_buyer] -= _amount; brxTokenBalance[_buyer] -= _brxAdjustment; /// @dev Removes the USDC that was sent from the total amount in the Vault usdcTotal -= _amount; emit Refund(_buyer, _amount); /// @dev Sends the refund to the buyer USDC.safeTransfer(_buyer, _amount); } }
contract Vault is ReentrancyGuard { using SafeERC20 for IERC20; /// @dev Custom Errors error NoTokensDepositError(); /// @notice ERC20 token for interest payments IERC20 public BRX; IERC20 public USDC; /// @notice Global variables to keep track of the accounts and the deposits they make mapping(address => uint256) public brxTokenBalance; /// @notice Mappings for the USDC token mapping(address => uint256) public usdcTokenBalance; /// @notice Deployer of the contract gains permission to supply interest as collateral address payable owner; /// @notice Admin address for the contract address adminAddress; /// @notice Wallet address for unrefundable portion of payments address fundsAddress; /// @notice The address of the contract the handles the ICO functions address swapAddress; /// @notice Set the basis points penalty for early widthdrawal uint256 public penalty; // bps /// @notice Total amount of BRX in the contract uint256 public brxTotal; /// @notice Total amount of USDC in the contract uint256 public usdcTotal; /// @dev Events for proper vault functionality and transaction execution event Minted(address indexed minter, uint256 amount); event BRX_Supplied(address indexed depositer, uint256 amount, uint256 timestamp); event BRX_Removed(address indexed depositer, uint256 amount, uint256 timestamp); event BRXPurchased(address indexed purchaser, uint256 usdcAmount, uint256 cmtAllotedAmount); event TokenWithdraw(address indexed user, bytes32 token, uint256 payment); event RemovedPaymentTokens(address indexed owner, uint256 amount); event AddedPaymentTokens(address indexed owner, uint256 amount); event Refund(address indexed _buyer, uint256 _amount); event SetPenalty(uint256 _penalty); event SetSwapAddress(address _swapAddress); event SetFundsAddress(address _fundsAddress); /// @param _fundsAddress Wallet address to recieve unrefundable portion of payments constructor (address token, address _fundsAddress) { require((_fundsAddress!=address(0)), "fundsAddress invalid"); owner = payable(msg.sender); BRX = IERC20(token); fundsAddress = _fundsAddress; } /// @notice Admin address can be changed by owner function setAdminAddress(address _address) public onlyOwner { adminAddress = _address; } /// @param _fundsAddress Address for penalties to get routed to upon BRX purchase function setFundsAddress(address _fundsAddress) public onlyOwner { require(_fundsAddress!=address(0), "fundsAddress cannot be zero"); fundsAddress = _fundsAddress; emit SetFundsAddress(_fundsAddress); } /// @param _swapAddress Address for the swap contract function setSwapAddress(address _swapAddress) public onlyOwner { require(_swapAddress!=address(0), "swapAddress cannot be zero"); swapAddress = _swapAddress; emit SetSwapAddress(_swapAddress); } /// @notice Sets the token that will be used for payments (USDC) function setPaymentToken(address token) public onlyOwner { USDC = IERC20(token); } /// @notice Can withdraw entire payment token supply held inside of the Vault /// @param _amount The amount of USDC to be removed from the vault function removePaymentTokens(uint256 _amount) public onlyAdmin { require(_amount > 0, "The amount must be greater than zero"); require(usdcTotal >= _amount, "There are not enough USDC tokens in the vault"); usdcTotal -= _amount; emit RemovedPaymentTokens(tx.origin, usdcTotal); USDC.safeTransfer(tx.origin, _amount); } /// @param _amount The amount of USDC to add to the vault function addPaymentTokens(uint256 _amount) public onlyOwner { require(_amount > 0, "No tokens where added"); usdcTotal += _amount; emit AddedPaymentTokens(tx.origin, _amount); USDC.safeTransferFrom(tx.origin, address(this), _amount); } /// @param _amount The amount of BRX to add to the Vault function supplyBRX (uint256 _amount) public onlyOwner { require(_amount > 0, "You need to deposit some tokens"); brxTotal += _amount; emit BRX_Supplied( tx.origin, _amount, block.timestamp ); BRX.safeTransferFrom(tx.origin, address(this), _amount); } /// @param _amount This is the amount of BRX to be removed by contract owner function removeBRX (uint256 _amount) public onlyAdmin { require(_amount > 0, "The amount must be greater than zero"); require(brxTotal >= _amount, "There are not enough BRX tokens in the vault"); brxTotal -= _amount; emit BRX_Removed( msg.sender, brxTotal, block.timestamp ); BRX.safeTransfer(tx.origin, _amount); } /// @notice Checks the balance of BRX function balanceOfBRX() public view returns(uint256) { return brxTotal; } /// @notice Checks the balance of USDC in the contract function balanceOfUSDC() public view returns(uint256) { return usdcTotal; } /// @param _amount Amount of basis points to set penalty function setPenaltyAmount(uint256 _amount) public onlyOwner { penalty = _amount * 100; emit SetPenalty(penalty); } /// @return Returns the penalty amount that was set function getPenaltyAmount() public view returns(uint256) { return penalty; } /// @return Returns the fundsAddress function getFundsAddress() public view returns (address) { return fundsAddress; } /// @return Returns the swapAddress function getSwapAddress() public view returns (address) { return swapAddress; } /// @notice Returns the adminAddress function getAdminAddress() public view returns (address) { return adminAddress; } /// @notice Admin functions accessible only by admin address modifier onlyAdmin() { require(msg.sender == adminAddress, "Only admin can call this function."); _; } /// @dev Allows only the deployer / supplier to use the function modifier onlyOwner() { require(tx.origin == owner, "This address is not the owner"); _; } /// @dev Allows only the swap contract to use this function modifier onlySwap() { require(msg.sender == swapAddress, "This address is not the swap contract"); _; } /** @param _user Address purchasing BRX @param _usdcAmount Amount of USDC being swapped for BRX @param _brxAmount Requested amount of BRX being purchased */ function buyBRX(address _user, uint256 _usdcAmount, uint256 _brxAmount) public onlySwap nonReentrant { require (_user != address(0), "Invalid address"); if (_usdcAmount <= 0) { revert NoTokensDepositError(); } /// @notice Penalty amount for BRX purchase uint256 unrefundableAmount = _usdcAmount * penalty / 10000; uint256 storedAmount = _usdcAmount - unrefundableAmount; /// @dev USDC and BRX token balances for each user who interact with the Vault usdcTokenBalance[_user] += storedAmount; brxTokenBalance[_user] += _brxAmount; /// @dev USDC Total amount being stored inside of the Vault usdcTotal += storedAmount; /// @dev _user can only be sent from the swap contract so not aritrary (slither) /// @dev Penalty portion of payment sent to fundsAddress upon BRX purchase USDC.safeTransferFrom(_user, fundsAddress, unrefundableAmount); /// @dev Maximum refundable portion of payment sent to vault USDC.safeTransferFrom(_user, address(this), storedAmount); /// @dev BRXPurchased event emit BRXPurchased(_user, _usdcAmount, _brxAmount); } /// @notice Allows an account to withdraw the BRX that was purchased /// @param _user The buyers address /// @param _amount The amount of BRX to send to the buyer function withdraw(address _user, uint256 _amount, uint256 _usdcAdjustment) public onlySwap { require(_amount <= brxTokenBalance[_user], "The amount is greater than your balance"); require(_amount > 0, "The amount must be greater than zero"); require(_amount <= brxTotal, "Please contact support"); /// @dev Adjusts the balances of the users account brxTokenBalance[_user] -= _amount; usdcTokenBalance[_user] -= _usdcAdjustment; /// @dev Removes the BRX that was sent from the total amount in the contract brxTotal -= _amount; /// @dev Allows a BRX token withdraw event from the verified sender emit TokenWithdraw( msg.sender, 'BRX', _amount ); /// @dev Sends the BRX to the buyer who requested a withdraw BRX.safeTransfer(_user, _amount); } /** @notice Refunds USDC to buyer @param _buyer The buyer's address @param _amount The amount to be refunded @param _brxAdjustment The amount of BRX to be removed from the buyers account */ function refund(address _buyer, uint256 _amount, uint256 _brxAdjustment) public onlySwap { require(_amount <= usdcTokenBalance[_buyer], "The amount is greater than the buyer's balance"); require(_amount > 0, "The amount must be greater than zero"); require(_amount <= usdcTotal, "Please contact support"); /// @dev Adjust the balances of the users account usdcTokenBalance[_buyer] -= _amount; brxTokenBalance[_buyer] -= _brxAdjustment; /// @dev Removes the USDC that was sent from the total amount in the Vault usdcTotal -= _amount; emit Refund(_buyer, _amount); /// @dev Sends the refund to the buyer USDC.safeTransfer(_buyer, _amount); } }
13,184
13
// returns the balance of a particular account
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
28,395
5
// Emits when a new admin is added that can pause contracts
event PausableAdminAdded(address indexed newAdmin);
event PausableAdminAdded(address indexed newAdmin);
20,050
8
// Re-claim approved token
function reclaim(address to, uint256 tokenId) external payable onlyOwnerOf(tokenId)
function reclaim(address to, uint256 tokenId) external payable onlyOwnerOf(tokenId)
52,654
122
// address of appointed talent agent
address appointedAgent;
address appointedAgent;
13,130
115
// how much sUSD the contract can buy with its DHPT balance
uint256 dhptForSusd = dhptBalance.mul(poolPrice).div(10**18); return dhptForSusd;
uint256 dhptForSusd = dhptBalance.mul(poolPrice).div(10**18); return dhptForSusd;
13,036
3,632
// 1817
entry "unpotholed" : ENG_ADJECTIVE
entry "unpotholed" : ENG_ADJECTIVE
18,429