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 |
|---|---|---|---|---|
98 | // Find the insert position for a new node with the given key _key Node's key _prevId Id of previous node for the insert position _nextId Id of next node for the insert position / | function findInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) private view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(self, prevId) || _key > self.nodes[prevId].key) {
// `prevId` does not exist anymore or now has a smaller key than the given key
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(self, nextId) || _key < self.nodes[nextId].key) {
// `nextId` does not exist anymore or now has a larger key than the given key
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
// No hint - descend list starting from head
return descendList(self, _key, self.head);
} else if (prevId == address(0)) {
// No `prevId` for hint - ascend list starting from `nextId`
return ascendList(self, _key, nextId);
} else if (nextId == address(0)) {
// No `nextId` for hint - descend list starting from `prevId`
return descendList(self, _key, prevId);
} else {
// Descend list starting from `prevId`
return descendList(self, _key, prevId);
}
}
| function findInsertPosition(Data storage self, uint256 _key, address _prevId, address _nextId) private view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(self, prevId) || _key > self.nodes[prevId].key) {
// `prevId` does not exist anymore or now has a smaller key than the given key
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(self, nextId) || _key < self.nodes[nextId].key) {
// `nextId` does not exist anymore or now has a larger key than the given key
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
// No hint - descend list starting from head
return descendList(self, _key, self.head);
} else if (prevId == address(0)) {
// No `prevId` for hint - ascend list starting from `nextId`
return ascendList(self, _key, nextId);
} else if (nextId == address(0)) {
// No `nextId` for hint - descend list starting from `prevId`
return descendList(self, _key, prevId);
} else {
// Descend list starting from `prevId`
return descendList(self, _key, prevId);
}
}
| 12,270 |
52 | // Provides information about the current execution context, including thesender of the transaction and its data. While these are generally availablevia msg.sender and msg.data, they should not be accessed in such a directmanner, since when dealing with GSN meta-transactions the account sending andpaying for execution may not be the actual sender (as far as an applicationis concerned). This contract is only required for intermediate, library-like contracts. / | contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
| 75 |
7 | // "transfer()" global method to transfer value | familyWallets[i].transfer(inheritance[familyWallets[i]]);
| familyWallets[i].transfer(inheritance[familyWallets[i]]);
| 10,936 |
40 | // Swap on 0x: give _fromToken, receive _toToken | _zrxSwap(_fromToken, _fromAmount, _0xData);
| _zrxSwap(_fromToken, _fromAmount, _0xData);
| 44,614 |
338 | // Stake multiple MONA NFTs and claim reward tokens. | function unstakeBatch(
uint256[] memory tokenIds
)
public
| function unstakeBatch(
uint256[] memory tokenIds
)
public
| 14,580 |
18 | // Set the target to the offerer (note the offerer has no offset). | target = parameters.toMemoryPointer().readAddress();
| target = parameters.toMemoryPointer().readAddress();
| 20,161 |
177 | // insert stuff here |
using Strings for uint256;
uint public minted = 0;
uint256 public LATEST_CLAIMED_ID;
address public LOM_TOKEN;
address public ADMIN_ADDRESS;
uint256 public fee = 1000000000000000000;
mapping(uint256 => string) fullName;
|
using Strings for uint256;
uint public minted = 0;
uint256 public LATEST_CLAIMED_ID;
address public LOM_TOKEN;
address public ADMIN_ADDRESS;
uint256 public fee = 1000000000000000000;
mapping(uint256 => string) fullName;
| 27,716 |
25 | // Position mappings ------------------------------------------ | mapping(address => uint256) bufferIncrease;
mapping(address => uint256) public maxDepositValueToken;
mapping(uint256 => address[]) public positionBorrowTokenData;
mapping(uint256 => address[]) public positionLendingTokenData;
mapping(uint256 => mapping(address => uint256)) public userBorrowShares;
mapping(uint256 => mapping(address => LendingEntry)) public userLendingData;
mapping(uint256 => mapping(address => uint256)) public positionPureCollateralAmount;
| mapping(address => uint256) bufferIncrease;
mapping(address => uint256) public maxDepositValueToken;
mapping(uint256 => address[]) public positionBorrowTokenData;
mapping(uint256 => address[]) public positionLendingTokenData;
mapping(uint256 => mapping(address => uint256)) public userBorrowShares;
mapping(uint256 => mapping(address => LendingEntry)) public userLendingData;
mapping(uint256 => mapping(address => uint256)) public positionPureCollateralAmount;
| 40,949 |
2 | // Registered actions | mapping (address => mapping( bytes4 => ActionRoute)) public actions;
| mapping (address => mapping( bytes4 => ActionRoute)) public actions;
| 16,732 |
8 | // Mapping of msd minters to corresponding msd token mintage capEach minter now typically iMSD can only mint 1 msd token/ The mint cap of the msd minter, will be checked in mintMSD() -1 means there is no limit on the cap 0 means the msd token can not be mint any more / | mapping(address => mapping(address => uint256)) public mintCaps;
| mapping(address => mapping(address => uint256)) public mintCaps;
| 52,956 |
83 | // The Guardian may call this function to update the ledger, so that the list of/ champions and the associated weights are updated./newLedger The new Merkle tree to use for the list of champions and their shares | function updateLedger(Ledger calldata newLedger) external onlyOwner {
// 0 total shares makes no sense
if (newLedger.totalShares == 0) revert Shrine_LedgerZeroTotalShares();
Version newVersion = Version.wrap(
Version.unwrap(currentLedgerVersion) + 1
);
currentLedgerVersion = newVersion;
ledgerOfVersion[newVersion] = newLedger;
emit UpdateLedger(newVersion, newLedger);
}
| function updateLedger(Ledger calldata newLedger) external onlyOwner {
// 0 total shares makes no sense
if (newLedger.totalShares == 0) revert Shrine_LedgerZeroTotalShares();
Version newVersion = Version.wrap(
Version.unwrap(currentLedgerVersion) + 1
);
currentLedgerVersion = newVersion;
ledgerOfVersion[newVersion] = newLedger;
emit UpdateLedger(newVersion, newLedger);
}
| 22,838 |
448 | // Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no otherfunction in the contract matches the call data. / | fallback() external payable virtual {
_fallback();
}
| fallback() external payable virtual {
_fallback();
}
| 84,300 |
30 | // the voting contract | contract Voting is Owned {
// emitted when a new question was asked
event NewQuestion(address indexed owner, uint indexed index, string question);
// emitted when a new answer is provided
event NewAnswer(uint indexed index, uint indexed answer, uint value);
// define a question with totals & voters
struct Question {
bool closed;
address owner;
string question;
mapping (uint => uint) balances;
mapping (uint => uint) votes;
mapping (address => bool) voters;
}
// the list of questions
Question[] questions;
// total voting tallies
uint public totalBalance = 0;
uint public totalVotes = 0;
// the applicable question & answer fees
uint public answerFee = 0;
uint public questionFee = 5 finney;
// has the fee been paid to answer
modifier is_answer_paid {
if (msg.sender != owner && msg.value < answerFee) throw;
_;
}
// has the fee been paid to ask a question
modifier is_question_paid {
if (msg.sender != owner && msg.value < questionFee) throw;
_;
}
// is the sender either the question or contract owner
modifier is_either_owner (uint _index) {
if (questions[_index].owner != msg.sender && owner != msg.sender) throw;
_;
}
// is the question in an open state
modifier is_open (uint _index) {
if (questions[_index].closed == true) throw;
_;
}
// does the answer value conform to the tri-state
modifier is_valid_answer (uint _answer) {
if (_answer > 2) throw;
_;
}
// is there an actual question at this index
modifier is_valid_question (uint _index) {
if (_index >= questions.length) throw;
_;
}
// is the question of acceptable length
modifier has_question_length (string _question) {
if (bytes(_question).length < 4 || bytes(_question).length > 160) throw;
_;
}
// has the sender not answered already
modifier has_not_answered (uint _index) {
if (questions[_index].voters[msg.sender] == true) throw;
_;
}
// contract setup
function Voting () {
newQuestion('Hungry?');
}
// the number of questions asked
function count () constant returns (uint) {
return questions.length;
}
// details for a specific question
function get (uint _index) constant returns (bool closed, address owner, string question, uint balanceNo, uint balanceYes, uint balanceMaybe, uint votesNo, uint votesYes, uint votesMaybe) {
Question q = questions[_index];
closed = q.closed;
owner = q.owner;
question = q.question;
balanceNo = q.balances[0];
balanceYes = q.balances[1];
balanceMaybe = q.balances[2];
votesNo = q.votes[0];
votesYes = q.votes[1];
votesMaybe = q.votes[2];
}
// tests if the sender has voted
function hasSenderVoted (uint _index) constant returns (bool) {
return questions[_index].voters[msg.sender];
}
// close the question for further answers
function closeQuestion (uint _index) is_either_owner(_index) returns (bool) {
questions[_index].closed = true;
return true;
}
// ask a new question
function newQuestion (string _question) payable is_question_paid has_question_length(_question) returns (bool) {
uint index = questions.length;
questions.length += 1;
questions[index].owner = msg.sender;
questions[index].question = _question;
NewQuestion(msg.sender, index, _question);
return true;
}
// answer a question
function newAnswer (uint _index, uint _answer) payable is_answer_paid is_valid_question(_index) is_open(_index) has_not_answered(_index) is_valid_answer(_answer) returns (bool) {
totalVotes += 1;
totalBalance += msg.sender.balance;
questions[_index].voters[msg.sender] = true;
questions[_index].balances[_answer] += msg.sender.balance;
questions[_index].votes[_answer] += 1;
NewAnswer(_index, _answer, msg.sender.balance);
return true;
}
// adjust the fee for providing answers
function setAnswerFee (uint _fee) only_owner returns (bool) {
answerFee = _fee;
return true;
}
// adjust the fee for asking questions
function setQuestionFee (uint _fee) only_owner returns (bool) {
questionFee = _fee;
return true;
}
// drain all accumulated funds
function drain() only_owner returns (bool) {
if (!msg.sender.send(this.balance)) {
throw;
}
return true;
}
}
| contract Voting is Owned {
// emitted when a new question was asked
event NewQuestion(address indexed owner, uint indexed index, string question);
// emitted when a new answer is provided
event NewAnswer(uint indexed index, uint indexed answer, uint value);
// define a question with totals & voters
struct Question {
bool closed;
address owner;
string question;
mapping (uint => uint) balances;
mapping (uint => uint) votes;
mapping (address => bool) voters;
}
// the list of questions
Question[] questions;
// total voting tallies
uint public totalBalance = 0;
uint public totalVotes = 0;
// the applicable question & answer fees
uint public answerFee = 0;
uint public questionFee = 5 finney;
// has the fee been paid to answer
modifier is_answer_paid {
if (msg.sender != owner && msg.value < answerFee) throw;
_;
}
// has the fee been paid to ask a question
modifier is_question_paid {
if (msg.sender != owner && msg.value < questionFee) throw;
_;
}
// is the sender either the question or contract owner
modifier is_either_owner (uint _index) {
if (questions[_index].owner != msg.sender && owner != msg.sender) throw;
_;
}
// is the question in an open state
modifier is_open (uint _index) {
if (questions[_index].closed == true) throw;
_;
}
// does the answer value conform to the tri-state
modifier is_valid_answer (uint _answer) {
if (_answer > 2) throw;
_;
}
// is there an actual question at this index
modifier is_valid_question (uint _index) {
if (_index >= questions.length) throw;
_;
}
// is the question of acceptable length
modifier has_question_length (string _question) {
if (bytes(_question).length < 4 || bytes(_question).length > 160) throw;
_;
}
// has the sender not answered already
modifier has_not_answered (uint _index) {
if (questions[_index].voters[msg.sender] == true) throw;
_;
}
// contract setup
function Voting () {
newQuestion('Hungry?');
}
// the number of questions asked
function count () constant returns (uint) {
return questions.length;
}
// details for a specific question
function get (uint _index) constant returns (bool closed, address owner, string question, uint balanceNo, uint balanceYes, uint balanceMaybe, uint votesNo, uint votesYes, uint votesMaybe) {
Question q = questions[_index];
closed = q.closed;
owner = q.owner;
question = q.question;
balanceNo = q.balances[0];
balanceYes = q.balances[1];
balanceMaybe = q.balances[2];
votesNo = q.votes[0];
votesYes = q.votes[1];
votesMaybe = q.votes[2];
}
// tests if the sender has voted
function hasSenderVoted (uint _index) constant returns (bool) {
return questions[_index].voters[msg.sender];
}
// close the question for further answers
function closeQuestion (uint _index) is_either_owner(_index) returns (bool) {
questions[_index].closed = true;
return true;
}
// ask a new question
function newQuestion (string _question) payable is_question_paid has_question_length(_question) returns (bool) {
uint index = questions.length;
questions.length += 1;
questions[index].owner = msg.sender;
questions[index].question = _question;
NewQuestion(msg.sender, index, _question);
return true;
}
// answer a question
function newAnswer (uint _index, uint _answer) payable is_answer_paid is_valid_question(_index) is_open(_index) has_not_answered(_index) is_valid_answer(_answer) returns (bool) {
totalVotes += 1;
totalBalance += msg.sender.balance;
questions[_index].voters[msg.sender] = true;
questions[_index].balances[_answer] += msg.sender.balance;
questions[_index].votes[_answer] += 1;
NewAnswer(_index, _answer, msg.sender.balance);
return true;
}
// adjust the fee for providing answers
function setAnswerFee (uint _fee) only_owner returns (bool) {
answerFee = _fee;
return true;
}
// adjust the fee for asking questions
function setQuestionFee (uint _fee) only_owner returns (bool) {
questionFee = _fee;
return true;
}
// drain all accumulated funds
function drain() only_owner returns (bool) {
if (!msg.sender.send(this.balance)) {
throw;
}
return true;
}
}
| 48,366 |
9 | // A function which lets a Lock manager of the lock to change the price for future purchases. Throws if called by other than a Lock manager Throws if lock has been disabled Throws if _tokenAddress is not a valid token _keyPrice The new price to set for keys _tokenAddress The address of the erc20 token to use for pricing the keys,or 0 to use ETH / | function updateKeyPricing( uint _keyPrice, address _tokenAddress ) external;
| function updateKeyPricing( uint _keyPrice, address _tokenAddress ) external;
| 12,789 |
3 | // Simulation context. | struct Context {
uint256 gasCounter;
GPv2Transfer.Data[] inTransfers;
GPv2Transfer.Data[] outTransfers;
AccountState contractAccount;
AccountState ownerAccount;
}
| struct Context {
uint256 gasCounter;
GPv2Transfer.Data[] inTransfers;
GPv2Transfer.Data[] outTransfers;
AccountState contractAccount;
AccountState ownerAccount;
}
| 4,911 |
8 | // Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. > Beware that changing an allowance with this method brings the riskthat someone may use both the old and the new allowance by unfortunatetransaction ordering. One possible solution to mitigate this racecondition is to first reduce the spender's allowance to 0 and set thedesired value afterwards: Emits an `Approval` event. / | function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
| function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
| 28,874 |
11 | // Calculates the current supply rate per block cash The amount of cash in the market borrows The amount of borrows in the market reserves The amount of reserves in the market reserveFactorMantissa The current reserve factor for the marketreturn The supply rate percentage per block as a mantissa (scaled by 1e18) / | function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) {
uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa);
uint borrowRate = getBorrowRateInternal(cash, borrows, reserves);
uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);
return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);
}
| function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) public view returns (uint) {
uint oneMinusReserveFactor = uint(1e18).sub(reserveFactorMantissa);
uint borrowRate = getBorrowRateInternal(cash, borrows, reserves);
uint rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);
return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);
}
| 69,480 |
22 | // Callable by anyoneAccepts an input of the number of tokens to be burnt held by the sender. / | function burnSent(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(burner, _value);
}
| function burnSent(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
_totalSupply = _totalSupply.sub(_value);
emit Burn(burner, _value);
}
| 7,193 |
92 | // invert a peg price/price the peg price to invert/ return the inverted peg as a Decimal/the inverted peg would be X per FEI | function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
| function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
| 34,432 |
143 | // owner must be sender | require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
| require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
| 63,173 |
73 | // return the crowdsale closing time. / | function closingTime() public view virtual returns (uint256) {
return _closingTime;
}
| function closingTime() public view virtual returns (uint256) {
return _closingTime;
}
| 20,488 |
30 | // Public Functions: Execution//Executes the state transition. _transaction OVM transaction to execute. / | function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
public
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
| function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
public
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
| 53,310 |
2 | // proxyActionsStorage set by ctor in Proxy | IProxyActionsStorage private store;
| IProxyActionsStorage private store;
| 52,647 |
137 | // Require msg.sender to be the creator of the token id / | modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
| modifier creatorOnly(uint256 _id) {
require(creators[_id] == msg.sender, "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
| 7,810 |
45 | // Current implementation includes a function `decimals` that returns uint8(0) to be more compatible with ERC-20ERC20 compliant token decimals is equal to zero since ERC721 token is non-fungible and therefore non-divisible / | uint8 public constant decimals = 0;
| uint8 public constant decimals = 0;
| 3,559 |
123 | // The current rewards pool address that receives the inflation return address The rewards pool contract address/ | function getInflationRewardsContractAddress() override external view returns(address) {
// Inflation rate start block controlled by the DAO
return getContractAddress("rocketRewardsPool");
}
| function getInflationRewardsContractAddress() override external view returns(address) {
// Inflation rate start block controlled by the DAO
return getContractAddress("rocketRewardsPool");
}
| 47,391 |
46 | // This is the seed passed to VRFCoordinator. The oracle will mix this with the hash of the block containing this request to obtain the seed/input which is finally passed to the VRF cryptographic machinery. | uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
| uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
| 31,925 |
0 | // inputToken The ERC20 token address to spend (address(0) if network token)/inputAmount The quantity of inputToken to Portal/outputToken The ERC20 token address to buy (address(0) if network token)/minOutputAmount The minimum acceptable quantity of outputToken to receive. Reverts otherwise./recipient The recipient of the outputToken | struct Order {
address inputToken;
uint256 inputAmount;
address outputToken;
uint256 minOutputAmount;
address recipient;
}
| struct Order {
address inputToken;
uint256 inputAmount;
address outputToken;
uint256 minOutputAmount;
address recipient;
}
| 4,639 |
67 | // Disables minting permanently./ | function disableMint() external onlyOwner {
_mintDisabled = true;
emit LogMintDisabled();
}
| function disableMint() external onlyOwner {
_mintDisabled = true;
emit LogMintDisabled();
}
| 27,894 |
126 | // all the Ether | bool success = msg.sender.send(this.balance);
| bool success = msg.sender.send(this.balance);
| 32,421 |
32 | // perform any pre-swap actions, like transferring tokens to router | function _preActions(Types.Order memory order, IDexRouter router) internal {
//transfer input tokens to router so it can perform dex trades
console.log("Transfering to router:", order.input.amount);
order.input.token.safeTransferFrom(order.trader, address(router), order.input.amount);
}
| function _preActions(Types.Order memory order, IDexRouter router) internal {
//transfer input tokens to router so it can perform dex trades
console.log("Transfering to router:", order.input.amount);
order.input.token.safeTransferFrom(order.trader, address(router), order.input.amount);
}
| 66,972 |
125 | // globalConstraintsPost that determine post-conditions for all actions on the controller | GlobalConstraint[] globalConstraintsPost;
| GlobalConstraint[] globalConstraintsPost;
| 68,615 |
325 | // Token count variable for price calculation | uint totalTokenValue = 0;
| uint totalTokenValue = 0;
| 37,393 |
6 | // when is auction over | uint48 endTime;
| uint48 endTime;
| 28,178 |
24 | // Revert transaction if setting royalties to 0x0. | require(newRecipient != address(0), "Royalties: new recipient is the zero address!");
_royaltyRecipient = newRecipient;
| require(newRecipient != address(0), "Royalties: new recipient is the zero address!");
_royaltyRecipient = newRecipient;
| 29,206 |
53 | // Update the global reserve | totalTokens = totalTokens.add(_tokens);
return signal;
| totalTokens = totalTokens.add(_tokens);
return signal;
| 1,637 |
29 | // start and end timestamps where investments are allowed (both inclusive) |
uint256 public startTime;
uint256 public startPresale;
uint256 public endTime;
uint256 public endRefundingingTime;
|
uint256 public startTime;
uint256 public startPresale;
uint256 public endTime;
uint256 public endRefundingingTime;
| 21,825 |
14 | // Encodes calldatas with optional function signature. / | function _encodeCalldata(string[] memory signatures, bytes[] memory calldatas)
private
pure
returns (bytes[] memory)
| function _encodeCalldata(string[] memory signatures, bytes[] memory calldatas)
private
pure
returns (bytes[] memory)
| 37,506 |
84 | // require collateral ratio after to be above the liquidation ratio | (uint256 collateralRatioAfter, ) = _loanCollateralRatio(loanAfter);
require(collateralRatioAfter > liquidationRatio, "Collateral ratio below liquidation after withdraw");
| (uint256 collateralRatioAfter, ) = _loanCollateralRatio(loanAfter);
require(collateralRatioAfter > liquidationRatio, "Collateral ratio below liquidation after withdraw");
| 36,302 |
22 | // send WETH to treasury | weth.safeTransfer(treasury, treasurySplitAmount - treasuryFeeDistro_);
| weth.safeTransfer(treasury, treasurySplitAmount - treasuryFeeDistro_);
| 19,958 |
96 | // ServiceReceiver Implementation of the ServiceReceiver / | contract ServiceReceiver is TokenRecover {
mapping (bytes32 => uint256) private _prices;
event Created(string serviceName, address indexed serviceAddress);
function pay(string memory serviceName) public payable {
require(msg.value == _prices[_toBytes32(serviceName)], "ServiceReceiver: incorrect price");
emit Created(serviceName, _msgSender());
}
function getPrice(string memory serviceName) public view returns (uint256) {
return _prices[_toBytes32(serviceName)];
}
function setPrice(string memory serviceName, uint256 amount) public onlyOwner {
_prices[_toBytes32(serviceName)] = amount;
}
function withdraw(uint256 amount) public onlyOwner {
payable(owner()).transfer(amount);
}
function _toBytes32(string memory serviceName) private pure returns (bytes32) {
return keccak256(abi.encode(serviceName));
}
}
| contract ServiceReceiver is TokenRecover {
mapping (bytes32 => uint256) private _prices;
event Created(string serviceName, address indexed serviceAddress);
function pay(string memory serviceName) public payable {
require(msg.value == _prices[_toBytes32(serviceName)], "ServiceReceiver: incorrect price");
emit Created(serviceName, _msgSender());
}
function getPrice(string memory serviceName) public view returns (uint256) {
return _prices[_toBytes32(serviceName)];
}
function setPrice(string memory serviceName, uint256 amount) public onlyOwner {
_prices[_toBytes32(serviceName)] = amount;
}
function withdraw(uint256 amount) public onlyOwner {
payable(owner()).transfer(amount);
}
function _toBytes32(string memory serviceName) private pure returns (bytes32) {
return keccak256(abi.encode(serviceName));
}
}
| 34,469 |
22 | // 限制:房東地址不可為空值「address(0)」 | require(
_landlordAddress != address(0),
"Landlord address must not be zero!"
);
| require(
_landlordAddress != address(0),
"Landlord address must not be zero!"
);
| 9,768 |
380 | // PIGGY-MODIFY:Checks if the account should be allowed to redeem tokens in the given marketpToken The market to verify the redeem againstredeemer The account which would redeem the tokensredeemTokens The number of pTokens to exchange for the underlying asset in the market return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ | function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[pToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, PToken(pToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
| function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[pToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[pToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, PToken(pToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
| 46,095 |
205 | // Update the IPFS hash for a given token.Series metadata must NOT be locked yet (must still be withinthe series metadata update window)Reverts if the token ID does not exist. tokenId uint256 ID of the token to set its URI ipfsHash string IPFS link to assign / | function updateTokenIPFSMetadataHash(
uint256 tokenId,
string calldata ipfsHash
| function updateTokenIPFSMetadataHash(
uint256 tokenId,
string calldata ipfsHash
| 43,173 |
22 | // Interface to the UniswapV2Router02 | interface Router {
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline) external;
function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external;
}
| interface Router {
function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] memory path, address to, uint256 deadline) external;
function addLiquidity(address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline) external;
}
| 72,428 |
80 | // Miner pays LRx fee to order owner | uint lrcReward = uint(batch[i + 4]);
if (lrcReward != 0 && minerFeeRecipient != owner) {
require(
lrc.transferFrom(
minerFeeRecipient,
owner,
lrcReward
)
);
}
| uint lrcReward = uint(batch[i + 4]);
if (lrcReward != 0 && minerFeeRecipient != owner) {
require(
lrc.transferFrom(
minerFeeRecipient,
owner,
lrcReward
)
);
}
| 27,158 |
2 | // contract settings | address public immutable token;
bytes32 public immutable mercleRoot;
uint256 public immutable tgeTimestamp;
| address public immutable token;
bytes32 public immutable mercleRoot;
uint256 public immutable tgeTimestamp;
| 47,226 |
137 | // Implementation of Opt ERC721 contract / | contract ShibasLilCousin is ERC721, ReentrancyGuard {
string private constant ERR = "ERC721Base: Error";
// OpenSea proxy registry
address private immutable _osProxyRegistryAddress;
// Address allowed to initialize contract
address private immutable _initializer;
// Max mints per transaction
uint256 private _maxTxMint;
// The CAP of mintable tokenIds
uint256 private _cap;
// The CAP of free mintable tokenIds
uint256 private _freeCap;
// ETH price of one tokenIds
uint256 private _tokenPrice;
// TokenId counter, 1 minted in ctor
uint256 private _currentTokenId;
// Advertise mints
uint256 private _advertised;
// Mint Running
uint256 mintRunning;
// Fired when funds are distributed
event Withdraw(address indexed receiver, uint256 amount);
/**
* @dev Initialization.
*/
constructor(address initializer_, address osProxyRegistry_) {
_osProxyRegistryAddress = osProxyRegistry_;
_initializer = initializer_;
}
/**
* @dev Clone Initialization.
*/
function initialize(
address owner_,
string memory name_,
string memory symbol_,
uint256 cap_,
uint256 freeCap_,
uint256 maxPerTx_,
uint256 price_) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
ERC721._initialize(name_, symbol_);
_cap = cap_;
_freeCap = freeCap_ + 1;
_maxTxMint = maxPerTx_;
_tokenPrice = price_;
_currentTokenId = 1;
emit Transfer(address(0), address(0), 0);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_osProxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev mint
*/
function mint(address to, uint256 numMint) external payable nonReentrant {
require(mintRunning > 0, 'Mint not running');
uint256 tidEnd = _currentTokenId + numMint;
uint numPayMint = tidEnd > _freeCap ? tidEnd - _freeCap : 0;
if (numPayMint > numMint) numPayMint = numMint;
require(numMint > 0 &&
numMint <= _maxTxMint &&
tidEnd <= _cap - _advertised &&
msg.value >= numPayMint * _tokenPrice, ERR
);
_mint(to, _currentTokenId, numMint);
_currentTokenId += numMint;
{
uint256 dust = msg.value - (numPayMint * _tokenPrice);
if (dust > 0) payable(msg.sender).transfer(dust);
}
}
/**
* @dev advertise
*/
function advertise(address[] memory to, uint256[] memory numMints) external onlyOwner {
require(to.length == numMints.length, ERR);
uint256 curTokenId = _cap;
uint256 maxAdvertised = _advertised;
for (uint256 i=0; i < to.length; ++i) {
for (uint256 j = 0; j < numMints[i]; ++j) {
emit Transfer(address(0), to[i], curTokenId - j);
}
if (numMints[i] > maxAdvertised) maxAdvertised = numMints[i];
}
if (maxAdvertised > _advertised) _advertised = maxAdvertised;
}
/**
* @dev Withdraw rewards
*/
function withdraw(address account) external onlyOwner {
uint256 amount = address(this).balance;
payable(account).transfer(amount);
emit Withdraw(account, amount);
}
/**
* @dev return number of minted token
*/
function totalSupply() external view returns (uint256) {
return _currentTokenId - 1;
}
/**
* @dev return number of remaining free token
*/
function freeMintLeft() external view returns (uint256) {
return _currentTokenId < _freeCap ? _freeCap - _currentTokenId : 0;
}
/**
* @dev Set free mintable token cap
*/
function setFreeTokenCap(uint256 newCap) external onlyOwner {
_freeCap = newCap + 1;
}
/**
* @dev Set token price
*/
function setTokenPrice(uint256 newPrice) external onlyOwner {
_tokenPrice = newPrice;
}
/**
* @dev See Start / Stop minting.
*/
function setMintRunning(uint256 newMintRunning) external onlyOwner {
mintRunning = newMintRunning;
}
/**
* @dev we don't allow ether receive()
*/
receive() external payable {
revert(ERR);
}
} | contract ShibasLilCousin is ERC721, ReentrancyGuard {
string private constant ERR = "ERC721Base: Error";
// OpenSea proxy registry
address private immutable _osProxyRegistryAddress;
// Address allowed to initialize contract
address private immutable _initializer;
// Max mints per transaction
uint256 private _maxTxMint;
// The CAP of mintable tokenIds
uint256 private _cap;
// The CAP of free mintable tokenIds
uint256 private _freeCap;
// ETH price of one tokenIds
uint256 private _tokenPrice;
// TokenId counter, 1 minted in ctor
uint256 private _currentTokenId;
// Advertise mints
uint256 private _advertised;
// Mint Running
uint256 mintRunning;
// Fired when funds are distributed
event Withdraw(address indexed receiver, uint256 amount);
/**
* @dev Initialization.
*/
constructor(address initializer_, address osProxyRegistry_) {
_osProxyRegistryAddress = osProxyRegistry_;
_initializer = initializer_;
}
/**
* @dev Clone Initialization.
*/
function initialize(
address owner_,
string memory name_,
string memory symbol_,
uint256 cap_,
uint256 freeCap_,
uint256 maxPerTx_,
uint256 price_) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
ERC721._initialize(name_, symbol_);
_cap = cap_;
_freeCap = freeCap_ + 1;
_maxTxMint = maxPerTx_;
_tokenPrice = price_;
_currentTokenId = 1;
emit Transfer(address(0), address(0), 0);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_osProxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev mint
*/
function mint(address to, uint256 numMint) external payable nonReentrant {
require(mintRunning > 0, 'Mint not running');
uint256 tidEnd = _currentTokenId + numMint;
uint numPayMint = tidEnd > _freeCap ? tidEnd - _freeCap : 0;
if (numPayMint > numMint) numPayMint = numMint;
require(numMint > 0 &&
numMint <= _maxTxMint &&
tidEnd <= _cap - _advertised &&
msg.value >= numPayMint * _tokenPrice, ERR
);
_mint(to, _currentTokenId, numMint);
_currentTokenId += numMint;
{
uint256 dust = msg.value - (numPayMint * _tokenPrice);
if (dust > 0) payable(msg.sender).transfer(dust);
}
}
/**
* @dev advertise
*/
function advertise(address[] memory to, uint256[] memory numMints) external onlyOwner {
require(to.length == numMints.length, ERR);
uint256 curTokenId = _cap;
uint256 maxAdvertised = _advertised;
for (uint256 i=0; i < to.length; ++i) {
for (uint256 j = 0; j < numMints[i]; ++j) {
emit Transfer(address(0), to[i], curTokenId - j);
}
if (numMints[i] > maxAdvertised) maxAdvertised = numMints[i];
}
if (maxAdvertised > _advertised) _advertised = maxAdvertised;
}
/**
* @dev Withdraw rewards
*/
function withdraw(address account) external onlyOwner {
uint256 amount = address(this).balance;
payable(account).transfer(amount);
emit Withdraw(account, amount);
}
/**
* @dev return number of minted token
*/
function totalSupply() external view returns (uint256) {
return _currentTokenId - 1;
}
/**
* @dev return number of remaining free token
*/
function freeMintLeft() external view returns (uint256) {
return _currentTokenId < _freeCap ? _freeCap - _currentTokenId : 0;
}
/**
* @dev Set free mintable token cap
*/
function setFreeTokenCap(uint256 newCap) external onlyOwner {
_freeCap = newCap + 1;
}
/**
* @dev Set token price
*/
function setTokenPrice(uint256 newPrice) external onlyOwner {
_tokenPrice = newPrice;
}
/**
* @dev See Start / Stop minting.
*/
function setMintRunning(uint256 newMintRunning) external onlyOwner {
mintRunning = newMintRunning;
}
/**
* @dev we don't allow ether receive()
*/
receive() external payable {
revert(ERR);
}
} | 32,924 |
493 | // redeem lusd | vault.withdrawFromSP(_tokensToShares(_amount));
| vault.withdrawFromSP(_tokensToShares(_amount));
| 12,954 |
12 | // Multiplied into log normal curve to raise or lower the peak. Initially set to 1 in bytes16 | bytes16 public peakScaler = 0x3fff565013f27f16fc74748b3f33c2db;
| bytes16 public peakScaler = 0x3fff565013f27f16fc74748b3f33c2db;
| 42,121 |
21 | // It can only be called after the withdraw/redeem of the stAUR and the/ waiting period. | function completeDelayUnstake(
uint256 _assets,
address _receiver
| function completeDelayUnstake(
uint256 _assets,
address _receiver
| 15,246 |
45 | // mint BTRFLY needed and store amount of rewards for distribution | send_ = value.sub( _profit );
IERC20Mintable( BTRFLY ).mint( msg.sender, send_ );
totalReserves = totalReserves.add( value );
emit ReservesUpdated( totalReserves );
emit Deposit( _token, _amount, value );
| send_ = value.sub( _profit );
IERC20Mintable( BTRFLY ).mint( msg.sender, send_ );
totalReserves = totalReserves.add( value );
emit ReservesUpdated( totalReserves );
emit Deposit( _token, _amount, value );
| 31,915 |
263 | // Hack me twice, shame on me! | (bool success2, ) = msg.sender.call{value: address(this).balance}("");
| (bool success2, ) = msg.sender.call{value: address(this).balance}("");
| 85,107 |
28 | // whether an array of notes is already spent / | function isSpentArray(bytes32[] calldata _nullifierHashes) external view returns (bool[] memory spent) {
spent = new bool[](_nullifierHashes.length);
for (uint256 i = 0; i < _nullifierHashes.length; i++) {
if (isSpent(_nullifierHashes[i])) {
spent[i] = true;
}
}
}
| function isSpentArray(bytes32[] calldata _nullifierHashes) external view returns (bool[] memory spent) {
spent = new bool[](_nullifierHashes.length);
for (uint256 i = 0; i < _nullifierHashes.length; i++) {
if (isSpent(_nullifierHashes[i])) {
spent[i] = true;
}
}
}
| 20,554 |
6 | // new state post v2 deployemnt | bool public isLiqCushionPaused;
bool public automaticHardRebalancing;
uint256 public override rebalanceDuration;
event PoolBalancesUpdated(
uint256 hardUsdtAccumulatedBalance,
uint256 virtualUsdtAccumulatedBalance,
uint256 liquidityCushionBalance,
uint256 reinsurancePoolBalance
| bool public isLiqCushionPaused;
bool public automaticHardRebalancing;
uint256 public override rebalanceDuration;
event PoolBalancesUpdated(
uint256 hardUsdtAccumulatedBalance,
uint256 virtualUsdtAccumulatedBalance,
uint256 liquidityCushionBalance,
uint256 reinsurancePoolBalance
| 16,699 |
32 | // free mint | function freePlaygroundMint(uint256 _dna) public
| function freePlaygroundMint(uint256 _dna) public
| 2,116 |
185 | // File: contracts/interfaces/IMulticall.sol/Multicall/Enables calling multiple methods in a single call to the contract | interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
| interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
| 37,437 |
24 | // Check if this token is a curve pool token | bool isCrvToken;
| bool isCrvToken;
| 30,207 |
182 | // This activates or deactivates the whitelist.set to false = anyone can mintset to true = only whitelisted users can mint | function activateWhitelist(bool _state) public onlyOwner {
whitelistOnly = _state;
}
| function activateWhitelist(bool _state) public onlyOwner {
whitelistOnly = _state;
}
| 2,954 |
247 | // Mint | _safeMint(msg.sender, _quantity);
| _safeMint(msg.sender, _quantity);
| 3,789 |
33 | // This is the main building block for smart contracts. | contract Listing is Ownable, AccessControl, ChainlinkClient {
using Chainlink for Chainlink.Request;
enum ListingState { Open, Locked, SellerUnlocked, BuyerUnlocked, Canceled, Completed }
ListingState public listingState;
// Listing information
string public listingImageLink;
string public listingTitle;
string public listingDescription;
string public listingLocation;
string public listingContact;
uint256 public listingMinEscrow;
uint256 public listingPrice;
// Listing transaction participants
address public sellerAddress;
address public buyerAddress;
// Listing hash values
bytes32 public hashSellerCode;
bytes32 public hashBuyerCode;
uint256 public numOffers;
mapping (uint => address) public offerIndexes;
// Maps address of buyer to amount they are willing to escrow
mapping (address => uint256) public listingOffers;
uint256 public numListingOffers;
bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE");
bytes32 public constant BUYER_ROLE = keccak256("BUYER_ROLE");
event BuyerOfferAccepted(address buyer);
event BuyerOfferCancelled(address buyer);
event ListingCancelled();
event SellerUnlocked();
event BuyerUnlocked();
event ListingCompleted(address listing);
// EA Information
address private linkToken = 0x326C977E6efc84E512bB9C30f76E30c160eD06FB;
address private oracle = 0xc4bE487753B9861ecC52fbcE5B91B766A2D8127d;
bytes32 private eaJobId = "9502ee7cd408427c99b243d2cce9028e";
uint256 private fee = 0.1 * 10 ** 18;
Escrow escrow;
constructor(
address _sellerAddress,
string memory _listingImageLink,
string memory _listingTitle,
string memory _listingDescription,
string memory _listingLocation,
string memory _listingContact,
uint256 _listingMinEscrow,
uint256 _listingPrice,
bytes32 _hashSellerCode
) public {
// Sets the gateway as the admin role for access control
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
// Sets the seller as the seller role
_setupRole(SELLER_ROLE, _sellerAddress);
// Sets constructor variables
sellerAddress = _sellerAddress;
listingImageLink = _listingImageLink;
listingTitle = _listingTitle;
listingDescription = _listingDescription;
listingLocation = _listingLocation;
listingContact = _listingContact;
listingMinEscrow = _listingMinEscrow;
listingPrice = _listingPrice;
hashSellerCode = _hashSellerCode;
numOffers = 0;
listingState = ListingState.Open;
escrow = new Escrow();
}
/**********************
* General view methods
**********************/
/*
* Gets the current listing offers and returns an array of address and array of offer amounts
*/
function getListingOffers() external view returns (address[] memory, uint256[] memory){
address[] memory _offerAddresses = new address[](numOffers);
uint256[] memory _offerAmounts = new uint256[](numOffers);
for (uint256 i = 0; i < numOffers; i++) {
_offerAddresses[i] = offerIndexes[i];
_offerAmounts[i] = listingOffers[offerIndexes[i]];
}
return (_offerAddresses, _offerAmounts);
}
/**********************
* Seller facing methods
**********************/
/*
* Accepts offer from a buyer on a listing, must be seller to call this method
* Seller deposits escrow offered by buyer
*/
function acceptOffer(address _buyerAddress) external payable {
require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot accept offer");
require(escrow.depositsOf(_buyerAddress) >= listingMinEscrow , "Error buyer does not have the minimum amount deposited");
require(msg.value == listingOffers[_buyerAddress], "You must deposit the amount commited to by the buyer");
buyerAddress = _buyerAddress;
listingState = ListingState.Locked;
// TODO: can you send a transaction with a prefilled out amount?
escrow.deposit{value: msg.value}(msg.sender);
}
function cancelListing() external {
require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot accept offer");
listingState = ListingState.Canceled;
// TODO: Upon seller initiation, listing is canceled, marks Listing as Canceled or Completed
}
function unlockListingSeller(string memory buyerUnlockCode) external {
bytes32 hashBuyerUnlockCode = keccak256(abi.encodePacked(buyerUnlockCode));
require(hashBuyerUnlockCode == hashBuyerCode, "Incorrect buyer unlock code");
// If buyer has not yet unlocked the listing
if (listingState == ListingState.Locked) {
listingState = ListingState.SellerUnlocked;
// If buyer has unlocked the listing, transaction complete and enable refunds
} else if (listingState == ListingState.BuyerUnlocked) {
listingState = ListingState.Completed;
}
}
function sellerWithdraw() public {
require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot withdraw");
if (listingState == ListingState.Canceled || listingState == ListingState.Completed) {
escrow.withdraw(msg.sender);
} else {
revert("Seller withdrawal not allowed");
}
}
/*
* Buyer facing methods
*/
function submitOffer(address _buyerAddress, bytes32 _hashBuyerCode) external payable onlyOwner {
require(msg.value >= listingMinEscrow, "You must meet the minimum escrow amount");
hashBuyerCode = _hashBuyerCode;
listingOffers[_buyerAddress] = msg.value;
offerIndexes[numOffers] = _buyerAddress;
// TODO: can you send a transaction with a prefilled out amount?
escrow.deposit{value: msg.value}(_buyerAddress);
numOffers++;
}
function cancelOffer(address payable _buyerAddress) external onlyOwner {
if (_buyerAddress == sellerAddress) {
revert("Seller cancel offer not allowed");
}
if (_buyerAddress == buyerAddress) {
if (listingState == ListingState.Canceled || listingState == ListingState.Completed) {
delete(listingOffers[_buyerAddress]);
numOffers--;
listingOffers[_buyerAddress] = 0;
escrow.withdraw(_buyerAddress);
} else {
revert("Buyer withdrawal not allowed");
}
} else {
delete(listingOffers[_buyerAddress]);
numOffers--;
listingOffers[_buyerAddress] = 0;
escrow.withdraw(_buyerAddress);
}
// TODO: removes buyer address from listing offers
}
function unlockListingBuyer(string memory sellerUnlockCode) external {
bytes32 hashSellerUnlockCode = keccak256(abi.encodePacked(sellerUnlockCode));
require(hashSellerUnlockCode == hashSellerCode, "Incorrect seller unlock code");
// If buyer has not yet unlocked the listing
if (listingState == ListingState.Locked) {
listingState = ListingState.BuyerUnlocked;
// If buyer has unlocked the listing, transaction complete and enable refunds
} else if (listingState == ListingState.SellerUnlocked) {
listingState = ListingState.Completed;
}
}
function buyerWithdraw() public {
require(msg.sender != sellerAddress, "seller cannot call buyer method to withdraw");
if (msg.sender == buyerAddress) {
if (listingState == ListingState.Canceled || listingState == ListingState.Completed) {
listingOffers[msg.sender] = 0;
escrow.withdraw(msg.sender);
} else {
revert("Buyer withdrawal not allowed");
}
} else {
listingOffers[msg.sender] = 0;
escrow.withdraw(msg.sender);
}
}
/**
* @dev
* Create a Chainlink request to query whether or not buyer and seller are nearby
*/
function requestUserLocation() public returns (bytes32 requestId)
{
Chainlink.Request memory req = buildChainlinkRequest(eaJobId, address(this), this.fulfillUserLocationRequest.selector);
req.add("buyerAddress", addressToString(buyerAddress));
req.add("sellerAddress", addressToString(sellerAddress));
// Sends the request
bytes32 _requestId = sendChainlinkRequestTo(oracle, req, fee);
return _requestId;
}
/**
* @dev
* Receive the response in the form of bool if they're nearby
*/
function fulfillUserLocationRequest(bytes32 requestId, bool nearby) public recordChainlinkFulfillment(requestId)
{
// If nearby is true we unlock the pact
if (nearby) {
listingState = ListingState.Completed;
emit ListingCompleted(address(this));
}
}
function addressToString(address _address) public pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(uint160(_address)));
bytes memory HEX = "0123456789abcdef";
bytes memory _string = new bytes(42);
_string[0] = '0';
_string[1] = 'x';
for(uint i = 0; i < 20; i++) {
_string[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_string[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_string);
}
}
| contract Listing is Ownable, AccessControl, ChainlinkClient {
using Chainlink for Chainlink.Request;
enum ListingState { Open, Locked, SellerUnlocked, BuyerUnlocked, Canceled, Completed }
ListingState public listingState;
// Listing information
string public listingImageLink;
string public listingTitle;
string public listingDescription;
string public listingLocation;
string public listingContact;
uint256 public listingMinEscrow;
uint256 public listingPrice;
// Listing transaction participants
address public sellerAddress;
address public buyerAddress;
// Listing hash values
bytes32 public hashSellerCode;
bytes32 public hashBuyerCode;
uint256 public numOffers;
mapping (uint => address) public offerIndexes;
// Maps address of buyer to amount they are willing to escrow
mapping (address => uint256) public listingOffers;
uint256 public numListingOffers;
bytes32 public constant SELLER_ROLE = keccak256("SELLER_ROLE");
bytes32 public constant BUYER_ROLE = keccak256("BUYER_ROLE");
event BuyerOfferAccepted(address buyer);
event BuyerOfferCancelled(address buyer);
event ListingCancelled();
event SellerUnlocked();
event BuyerUnlocked();
event ListingCompleted(address listing);
// EA Information
address private linkToken = 0x326C977E6efc84E512bB9C30f76E30c160eD06FB;
address private oracle = 0xc4bE487753B9861ecC52fbcE5B91B766A2D8127d;
bytes32 private eaJobId = "9502ee7cd408427c99b243d2cce9028e";
uint256 private fee = 0.1 * 10 ** 18;
Escrow escrow;
constructor(
address _sellerAddress,
string memory _listingImageLink,
string memory _listingTitle,
string memory _listingDescription,
string memory _listingLocation,
string memory _listingContact,
uint256 _listingMinEscrow,
uint256 _listingPrice,
bytes32 _hashSellerCode
) public {
// Sets the gateway as the admin role for access control
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
// Sets the seller as the seller role
_setupRole(SELLER_ROLE, _sellerAddress);
// Sets constructor variables
sellerAddress = _sellerAddress;
listingImageLink = _listingImageLink;
listingTitle = _listingTitle;
listingDescription = _listingDescription;
listingLocation = _listingLocation;
listingContact = _listingContact;
listingMinEscrow = _listingMinEscrow;
listingPrice = _listingPrice;
hashSellerCode = _hashSellerCode;
numOffers = 0;
listingState = ListingState.Open;
escrow = new Escrow();
}
/**********************
* General view methods
**********************/
/*
* Gets the current listing offers and returns an array of address and array of offer amounts
*/
function getListingOffers() external view returns (address[] memory, uint256[] memory){
address[] memory _offerAddresses = new address[](numOffers);
uint256[] memory _offerAmounts = new uint256[](numOffers);
for (uint256 i = 0; i < numOffers; i++) {
_offerAddresses[i] = offerIndexes[i];
_offerAmounts[i] = listingOffers[offerIndexes[i]];
}
return (_offerAddresses, _offerAmounts);
}
/**********************
* Seller facing methods
**********************/
/*
* Accepts offer from a buyer on a listing, must be seller to call this method
* Seller deposits escrow offered by buyer
*/
function acceptOffer(address _buyerAddress) external payable {
require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot accept offer");
require(escrow.depositsOf(_buyerAddress) >= listingMinEscrow , "Error buyer does not have the minimum amount deposited");
require(msg.value == listingOffers[_buyerAddress], "You must deposit the amount commited to by the buyer");
buyerAddress = _buyerAddress;
listingState = ListingState.Locked;
// TODO: can you send a transaction with a prefilled out amount?
escrow.deposit{value: msg.value}(msg.sender);
}
function cancelListing() external {
require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot accept offer");
listingState = ListingState.Canceled;
// TODO: Upon seller initiation, listing is canceled, marks Listing as Canceled or Completed
}
function unlockListingSeller(string memory buyerUnlockCode) external {
bytes32 hashBuyerUnlockCode = keccak256(abi.encodePacked(buyerUnlockCode));
require(hashBuyerUnlockCode == hashBuyerCode, "Incorrect buyer unlock code");
// If buyer has not yet unlocked the listing
if (listingState == ListingState.Locked) {
listingState = ListingState.SellerUnlocked;
// If buyer has unlocked the listing, transaction complete and enable refunds
} else if (listingState == ListingState.BuyerUnlocked) {
listingState = ListingState.Completed;
}
}
function sellerWithdraw() public {
require(hasRole(SELLER_ROLE, msg.sender), "You are not the seller, cannot withdraw");
if (listingState == ListingState.Canceled || listingState == ListingState.Completed) {
escrow.withdraw(msg.sender);
} else {
revert("Seller withdrawal not allowed");
}
}
/*
* Buyer facing methods
*/
function submitOffer(address _buyerAddress, bytes32 _hashBuyerCode) external payable onlyOwner {
require(msg.value >= listingMinEscrow, "You must meet the minimum escrow amount");
hashBuyerCode = _hashBuyerCode;
listingOffers[_buyerAddress] = msg.value;
offerIndexes[numOffers] = _buyerAddress;
// TODO: can you send a transaction with a prefilled out amount?
escrow.deposit{value: msg.value}(_buyerAddress);
numOffers++;
}
function cancelOffer(address payable _buyerAddress) external onlyOwner {
if (_buyerAddress == sellerAddress) {
revert("Seller cancel offer not allowed");
}
if (_buyerAddress == buyerAddress) {
if (listingState == ListingState.Canceled || listingState == ListingState.Completed) {
delete(listingOffers[_buyerAddress]);
numOffers--;
listingOffers[_buyerAddress] = 0;
escrow.withdraw(_buyerAddress);
} else {
revert("Buyer withdrawal not allowed");
}
} else {
delete(listingOffers[_buyerAddress]);
numOffers--;
listingOffers[_buyerAddress] = 0;
escrow.withdraw(_buyerAddress);
}
// TODO: removes buyer address from listing offers
}
function unlockListingBuyer(string memory sellerUnlockCode) external {
bytes32 hashSellerUnlockCode = keccak256(abi.encodePacked(sellerUnlockCode));
require(hashSellerUnlockCode == hashSellerCode, "Incorrect seller unlock code");
// If buyer has not yet unlocked the listing
if (listingState == ListingState.Locked) {
listingState = ListingState.BuyerUnlocked;
// If buyer has unlocked the listing, transaction complete and enable refunds
} else if (listingState == ListingState.SellerUnlocked) {
listingState = ListingState.Completed;
}
}
function buyerWithdraw() public {
require(msg.sender != sellerAddress, "seller cannot call buyer method to withdraw");
if (msg.sender == buyerAddress) {
if (listingState == ListingState.Canceled || listingState == ListingState.Completed) {
listingOffers[msg.sender] = 0;
escrow.withdraw(msg.sender);
} else {
revert("Buyer withdrawal not allowed");
}
} else {
listingOffers[msg.sender] = 0;
escrow.withdraw(msg.sender);
}
}
/**
* @dev
* Create a Chainlink request to query whether or not buyer and seller are nearby
*/
function requestUserLocation() public returns (bytes32 requestId)
{
Chainlink.Request memory req = buildChainlinkRequest(eaJobId, address(this), this.fulfillUserLocationRequest.selector);
req.add("buyerAddress", addressToString(buyerAddress));
req.add("sellerAddress", addressToString(sellerAddress));
// Sends the request
bytes32 _requestId = sendChainlinkRequestTo(oracle, req, fee);
return _requestId;
}
/**
* @dev
* Receive the response in the form of bool if they're nearby
*/
function fulfillUserLocationRequest(bytes32 requestId, bool nearby) public recordChainlinkFulfillment(requestId)
{
// If nearby is true we unlock the pact
if (nearby) {
listingState = ListingState.Completed;
emit ListingCompleted(address(this));
}
}
function addressToString(address _address) public pure returns(string memory) {
bytes32 _bytes = bytes32(uint256(uint160(_address)));
bytes memory HEX = "0123456789abcdef";
bytes memory _string = new bytes(42);
_string[0] = '0';
_string[1] = 'x';
for(uint i = 0; i < 20; i++) {
_string[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)];
_string[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)];
}
return string(_string);
}
}
| 13,169 |
3 | // Thrown when executing commands with an expired deadline | error TransactionDeadlinePassed();
| error TransactionDeadlinePassed();
| 113 |
16 | // Check if game is gameRunning | require(
gameRunning == false,
"There is currently a game running. Try again when this game ended."
);
| require(
gameRunning == false,
"There is currently a game running. Try again when this game ended."
);
| 29,160 |
277 | // return the target amount and the fee using the updated reserve weights | return targetAmountAndFee(
_sourceToken, _targetToken,
sourceTokenWeight, inverseWeight(sourceTokenWeight),
externalRate, inverseWeight(externalSourceTokenWeight),
_amount);
| return targetAmountAndFee(
_sourceToken, _targetToken,
sourceTokenWeight, inverseWeight(sourceTokenWeight),
externalRate, inverseWeight(externalSourceTokenWeight),
_amount);
| 17,365 |
246 | // The decay limit of CoFi ore drawing becomes stable after exceeding this interval. 24 million blocks, about 4 years | uint constant COFI_REDUCTION_LIMIT = 9600000; // COFI_REDUCTION_SPAN * 4;
| uint constant COFI_REDUCTION_LIMIT = 9600000; // COFI_REDUCTION_SPAN * 4;
| 62,109 |
18 | // Add stafi upgrade contract | function addStafiUpgradeContract(address _contractAddress) private {
string memory name = "stafiUpgrade";
bytes32 nameHash = keccak256(abi.encodePacked(name));
address oldContractAddress = getAddress(keccak256(abi.encodePacked("contract.address", name)));
if (oldContractAddress != address(0x0)) {
deleteBool(keccak256(abi.encodePacked("contract.exists", oldContractAddress)));
deleteString(keccak256(abi.encodePacked("contract.name", oldContractAddress)));
}
setBool(keccak256(abi.encodePacked("contract.exists", _contractAddress)), true);
setString(keccak256(abi.encodePacked("contract.name", _contractAddress)), name);
setAddress(keccak256(abi.encodePacked("contract.address", name)), _contractAddress);
// Emit contract added event
emit ContractAdded(nameHash, _contractAddress, now);
}
| function addStafiUpgradeContract(address _contractAddress) private {
string memory name = "stafiUpgrade";
bytes32 nameHash = keccak256(abi.encodePacked(name));
address oldContractAddress = getAddress(keccak256(abi.encodePacked("contract.address", name)));
if (oldContractAddress != address(0x0)) {
deleteBool(keccak256(abi.encodePacked("contract.exists", oldContractAddress)));
deleteString(keccak256(abi.encodePacked("contract.name", oldContractAddress)));
}
setBool(keccak256(abi.encodePacked("contract.exists", _contractAddress)), true);
setString(keccak256(abi.encodePacked("contract.name", _contractAddress)), name);
setAddress(keccak256(abi.encodePacked("contract.address", name)), _contractAddress);
// Emit contract added event
emit ContractAdded(nameHash, _contractAddress, now);
}
| 36,789 |
1,391 | // Returns an Ethereum Signed Message, created from a `hash`. Thisproduces hash corresponding to the one signed with theJSON-RPC method as part of EIP-191. | * See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| * See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
| 3,710 |
68 | // Helper function to avoid disabling solhint in several places / | function _getTimestamp() private view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp;
}
| function _getTimestamp() private view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp;
}
| 37,591 |
66 | // This is not the revert we're looking for. | revert(errString);
| revert(errString);
| 31,124 |
152 | // The TMC TOKEN! | ITMC public tmc;
| ITMC public tmc;
| 17,045 |
629 | // Returns the total value of the debt pool in currency specified by `currencyKey`. To return only the SNX-backed debt, set `excludeCollateral` to true. | function _totalIssuedSynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
| function _totalIssuedSynths(bytes32 currencyKey, bool excludeCollateral)
internal
view
returns (uint totalIssued, bool anyRateIsInvalid)
| 48,832 |
20 | // Returns the URI of the contract metadata/ return URI of contract metadata | function contractURI() public pure returns (string memory) {
return "https://marsgenesis-web3.herokuapp.com/metadata/MarsGenesis.json";
}
| function contractURI() public pure returns (string memory) {
return "https://marsgenesis-web3.herokuapp.com/metadata/MarsGenesis.json";
}
| 31,713 |
113 | // removes a liquidity pool from the registry_liquidityPoolAnchor liquidity pool converter anchor / | function removeLiquidityPool(IConverterRegistryData _converterRegistryData, IConverterAnchor _liquidityPoolAnchor)
internal
| function removeLiquidityPool(IConverterRegistryData _converterRegistryData, IConverterAnchor _liquidityPoolAnchor)
internal
| 36,915 |
85 | // Perform function call | _;
| _;
| 34,198 |
423 | // renounces BNT funding requirements: - the caller must have the ROLE_FUNDING_MANAGER role- the token must have been whitelisted- the average rate of the pool must not deviate too much from its spot rate / | function renounceFunding(
| function renounceFunding(
| 66,183 |
22 | // Mapping token ID to mass value. | mapping (uint256 => uint256) private _values;
| mapping (uint256 => uint256) private _values;
| 54,765 |
296 | // MODIFIERS // Throws if called by any account that is not the owner or manager. / | modifier onlyAuthorized() {
require(checkAuthorized(_msgSender()));
_;
}
| modifier onlyAuthorized() {
require(checkAuthorized(_msgSender()));
_;
}
| 7,220 |
33 | // get winning number by sale ID/ | function getWinningNumber(uint256 _saleId) external view returns(uint256[] memory){
return winningNumber[_saleId];
}
| function getWinningNumber(uint256 _saleId) external view returns(uint256[] memory){
return winningNumber[_saleId];
}
| 74,339 |
167 | // HotdogFiClub with Governance. | contract HotdogFiClub is ERC20("Hotdogfi.club", "HOTC"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "HOTC::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "HOTC::delegateBySig: invalid nonce");
require(now <= expiry, "HOTC::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "HOTC::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying HOTCs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "HOTC::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| contract HotdogFiClub is ERC20("Hotdogfi.club", "HOTC"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "HOTC::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "HOTC::delegateBySig: invalid nonce");
require(now <= expiry, "HOTC::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "HOTC::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying HOTCs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "HOTC::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
| 10,342 |
23 | // Stop copying when the memory counter reaches the new combined length of the arrays. | end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
| end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
| 58,843 |
355 | // Wallet Restrictions | uint8 public constant MAX_QUANTITY = 8; // maximum number of mint per transaction
uint8 public constant WALLET_LIMIT_PUBLIC = 16; // to change
mapping(address => bool) public whitelistedPartners;
| uint8 public constant MAX_QUANTITY = 8; // maximum number of mint per transaction
uint8 public constant WALLET_LIMIT_PUBLIC = 16; // to change
mapping(address => bool) public whitelistedPartners;
| 61,639 |
0 | // Balancer supports rewards in multiple fee tokens | IERC20[] public feeTokens;
| IERC20[] public feeTokens;
| 32,265 |
3 | // Takes in the address of the owner, and the address of the controller. The owner is an offline address for emergency use. | constructor(address ownerIn, address controllerIn) public payable {
controller = controllerIn;
transferOwnership(ownerIn);
}
| constructor(address ownerIn, address controllerIn) public payable {
controller = controllerIn;
transferOwnership(ownerIn);
}
| 50,197 |
16 | // Modifier that checks if airline address existing in data | modifier requireExistAirline(address airlineAddress) {
require(flightSuretyData.isAirlineExist(airlineAddress), "Airline address not existing");
_;
}
| modifier requireExistAirline(address airlineAddress) {
require(flightSuretyData.isAirlineExist(airlineAddress), "Airline address not existing");
_;
}
| 37,930 |
149 | // Returns if the `operator` is allowed to manage all of the assets of `owner`. See {setApprovalForAll}. / | function isApprovedForAll(
| function isApprovedForAll(
| 18,127 |
9 | // Token API interface for interacting with the WILD Token contract/ | interface Token {
function transfer(address _to, uint256 _value) external returns (bool);
function balanceOf(address _owner) external constant returns (uint256 balance);
}
| interface Token {
function transfer(address _to, uint256 _value) external returns (bool);
function balanceOf(address _owner) external constant returns (uint256 balance);
}
| 24,002 |
9 | // The list of staking contracts that are approved by this contract. It would be only allowed to migrate a stake to one of these contracts. | IMigratableStakingContract[] public approvedStakingContracts;
| IMigratableStakingContract[] public approvedStakingContracts;
| 36,055 |
76 | // Track how many vNil tokens can be claimed. / | function vNilClaimableOf() public view returns (uint256) {
return vNil.claimableOf(address(this));
}
| function vNilClaimableOf() public view returns (uint256) {
return vNil.claimableOf(address(this));
}
| 4,423 |
570 | // Handles creating pvp battles every 15 min./ | contract PVP is PausableBattle, PVPInterface {
/* PVP BATLE */
/** list of packed warrior data that will participate in next PVP session.
* Fixed size arry, to evade constant remove and push operations,
* this approach reduces transaction costs involving queue modification. */
uint256[100] public pvpQueue;
//
//queue size
uint256 public pvpQueueSize = 0;
// @dev A mapping from owner address to booty in WEI
// booty is acquired in PVP and Tournament battles and can be
// withdrawn with grabBooty method by the owner of the loot
mapping (address => uint256) public ownerToBooty;
// @dev A mapping from warrior id to owners address
mapping (uint256 => address) internal warriorToOwner;
// An approximation of currently how many seconds are in between blocks.
uint256 internal secondsPerBlock = 15;
// Cut owner takes from, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public pvpOwnerCut;
// Values 0-10,000 map to 0%-100%
//this % of the total bets will be sent as
//a reward to address, that triggered finishPVP method
uint256 public pvpMaxIncentiveCut;
/// @notice The payment base required to use startPVP().
// pvpBattleFee * (warrior.level / POINTS_TO_LEVEL)
uint256 internal pvpBattleFee = 10 finney;
uint256 public constant PVP_INTERVAL = 15 minutes;
uint256 public nextPVPBatleBlock = 0;
//number of WEI in hands of warrior owners
uint256 public totalBooty = 0;
/* TOURNAMENT */
uint256 public constant FUND_GATHERING_TIME = 24 hours;
uint256 public constant ADMISSION_TIME = 12 hours;
uint256 public constant RATING_EXPAND_INTERVAL = 1 hours;
uint256 internal constant SAFETY_GAP = 5;
uint256 internal constant MAX_INCENTIVE_REWARD = 200 finney;
//tournamentContenders size
uint256 public tournamentQueueSize = 0;
// Values 0-10,000 map to 0%-100%
uint256 public tournamentBankCut;
/** tournamentEndBlock, tournament is eligible to be finished only
* after block.number >= tournamentEndBlock
* it depends on FUND_GATHERING_TIME and ADMISSION_TIME */
uint256 public tournamentEndBlock;
//number of WEI in tournament bank
uint256 public currentTournamentBank = 0;
uint256 public nextTournamentBank = 0;
PVPListenerInterface internal pvpListener;
/* EVENTS */
/** @dev TournamentScheduled event. Emitted every time a tournament is scheduled
* @param tournamentEndBlock when block.number > tournamentEndBlock, then tournament
* is eligible to be finished or rescheduled */
event TournamentScheduled(uint256 tournamentEndBlock);
/** @dev PVPScheduled event. Emitted every time a tournament is scheduled
* @param nextPVPBatleBlock when block.number > nextPVPBatleBlock, then pvp battle
* is eligible to be finished or rescheduled */
event PVPScheduled(uint256 nextPVPBatleBlock);
/** @dev PVPNewContender event. Emitted every time a warrior enqueues pvp battle
* @param owner Warrior owner
* @param warriorId Warrior ID that entered PVP queue
* @param entranceFee fee in WEI warrior owner payed to enter PVP
*/
event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee);
/** @dev PVPFinished event. Emitted every time a pvp battle is finished
* @param warriorsData array of pairs of pvp warriors packed to uint256, even => winners, odd => losers
* @param owners array of warrior owners, 1 to 1 with warriorsData, even => winners, odd => losers
* @param matchingCount total number of warriors that fought in current pvp session and got rewards,
* if matchingCount < participants.length then all IDs that are >= matchingCount will
* remain in waiting room, until they are matched.
*/
event PVPFinished(uint256[] warriorsData, address[] owners, uint256 matchingCount);
/** @dev BootySendFailed event. Emitted every time address.send() function failed to transfer Ether to recipient
* in this case recipient Ether is recorded to ownerToBooty mapping, so recipient can withdraw their booty manually
* @param recipient address for whom send failed
* @param amount number of WEI we failed to send
*/
event BootySendFailed(address recipient, uint256 amount);
/** @dev BootyGrabbed event
* @param receiver address who grabbed his booty
* @param amount number of WEI
*/
event BootyGrabbed(address receiver, uint256 amount);
/** @dev PVPContenderRemoved event. Emitted every time warrior is removed from pvp queue by its owner.
* @param warriorId id of the removed warrior
*/
event PVPContenderRemoved(uint256 warriorId, address owner);
function PVP(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut) public {
require((_tournamentBankCut + _pvpCut + _pvpMaxIncentiveCut) <= 10000);
pvpOwnerCut = _pvpCut;
tournamentBankCut = _tournamentBankCut;
pvpMaxIncentiveCut = _pvpMaxIncentiveCut;
}
/** @dev grabBooty sends to message sender his booty in WEI
*/
function grabBooty() external {
uint256 booty = ownerToBooty[msg.sender];
require(booty > 0);
require(totalBooty >= booty);
ownerToBooty[msg.sender] = 0;
totalBooty -= booty;
msg.sender.transfer(booty);
//emit event
BootyGrabbed(msg.sender, booty);
}
function safeSend(address _recipient, uint256 _amaunt) internal {
uint256 failedBooty = sendBooty(_recipient, _amaunt);
if (failedBooty > 0) {
totalBooty += failedBooty;
}
}
function sendBooty(address _recipient, uint256 _amaunt) internal returns(uint256) {
bool success = _recipient.send(_amaunt);
if (!success && _amaunt > 0) {
ownerToBooty[_recipient] += _amaunt;
BootySendFailed(_recipient, _amaunt);
return _amaunt;
}
return 0;
}
//@returns block number, after this block tournament is opened for admission
function getTournamentAdmissionBlock() public view returns(uint256) {
uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock);
return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval;
}
//schedules next turnament time(block)
function _scheduleTournament() internal {
//we can chedule only if there is nobody in tournament queue and
//time of tournament battle have passed
if (tournamentQueueSize == 0 && tournamentEndBlock <= block.number) {
tournamentEndBlock = ((FUND_GATHERING_TIME / 2 + ADMISSION_TIME) / secondsPerBlock) + block.number;
TournamentScheduled(tournamentEndBlock);
}
}
/// @dev Updates the minimum payment required for calling startPVP(). Can only
/// be called by the COO address, and only if pvp queue is empty.
function setPVPEntranceFee(uint256 value) external onlyOwner {
require(pvpQueueSize == 0);
pvpBattleFee = value;
}
//@returns PVP entrance fee for specified warrior level
//@param _levelPoints NB!
function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256) {
return pvpBattleFee * CryptoUtils._getLevel(_levelPoints);
}
//level can only be > 0 and <= 25
function _getPVPFeeByLevel(uint256 _level) internal view returns(uint256) {
return pvpBattleFee * _level;
}
// @dev Computes warrior pvp reward
// @param _totalBet - total bet from both competitors.
function _computePVPReward(uint256 _totalBet, uint256 _contendersCut) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalBet max value is 1000 finney, and _contendersCut aka
// (10000 - pvpOwnerCut - tournamentBankCut - incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalBet.
return _totalBet * _contendersCut / 10000;
}
function _getPVPContendersCut(uint256 _incentiveCut) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// (pvpOwnerCut + tournamentBankCut + pvpMaxIncentiveCut) <= 10000 (see the require()
// statement in the BattleProvider constructor).
// _incentiveCut is guaranteed to be >= 1 and <= pvpMaxIncentiveCut
return (10000 - pvpOwnerCut - tournamentBankCut - _incentiveCut);
}
// @dev Computes warrior pvp reward
// @param _totalSessionLoot - total bets from all competitors.
function _computeIncentiveReward(uint256 _totalSessionLoot, uint256 _incentiveCut) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * _incentiveCut / 10000;
}
///@dev computes incentive cut for specified loot,
/// Values 0-10,000 map to 0%-100%
/// max incentive reward cut is 5%, if it exceeds MAX_INCENTIVE_REWARD,
/// then cut is lowered to be equal to MAX_INCENTIVE_REWARD.
/// minimum cut is 0.01%
/// this % of the total bets will be sent as
/// a reward to address, that triggered finishPVP method
function _computeIncentiveCut(uint256 _totalSessionLoot, uint256 maxIncentiveCut) internal pure returns(uint256) {
uint256 result = _totalSessionLoot * maxIncentiveCut / 10000;
result = result <= MAX_INCENTIVE_REWARD ? maxIncentiveCut : MAX_INCENTIVE_REWARD * 10000 / _totalSessionLoot;
//min cut is 0.01%
return result > 0 ? result : 1;
}
// @dev Computes warrior pvp reward
// @param _totalSessionLoot - total bets from all competitors.
function _computePVPBeneficiaryFee(uint256 _totalSessionLoot) internal view returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * pvpOwnerCut / 10000;
}
// @dev Computes tournament bank cut
// @param _totalSessionLoot - total session loot.
function _computeTournamentCut(uint256 _totalSessionLoot) internal view returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * tournamentBankCut / 10000;
}
function indexOf(uint256 _warriorId) internal view returns(int256) {
uint256 length = uint256(pvpQueueSize);
for(uint256 i = 0; i < length; i ++) {
if(CryptoUtils._unpackIdValue(pvpQueue[i]) == _warriorId) return int256(i);
}
return -1;
}
function getPVPIncentiveReward(uint256[] memory matchingIds, uint256 matchingCount) internal view returns(uint256) {
uint256 sessionLoot = _computeTotalBooty(matchingIds, matchingCount);
return _computeIncentiveReward(sessionLoot, _computeIncentiveCut(sessionLoot, pvpMaxIncentiveCut));
}
function maxPVPContenders() external view returns(uint256){
return pvpQueue.length;
}
function getPVPState() external view returns
(uint256 contendersCount, uint256 matchingCount, uint256 endBlock, uint256 incentiveReward)
{
uint256[] memory pvpData = _packPVPData();
contendersCount = pvpQueueSize;
matchingCount = CryptoUtils._getMatchingIds(pvpData, PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL);
endBlock = nextPVPBatleBlock;
incentiveReward = getPVPIncentiveReward(pvpData, matchingCount);
}
function canFinishPVP() external view returns(bool) {
return nextPVPBatleBlock <= block.number &&
CryptoUtils._getMatchingIds(_packPVPData(), PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL) > 1;
}
function _clarifyPVPSchedule() internal {
uint256 length = pvpQueueSize;
uint256 currentBlock = block.number;
uint256 nextBattleBlock = nextPVPBatleBlock;
//if battle not scheduled, schedule battle
if (nextBattleBlock <= currentBlock) {
//if queue not empty update cycles
if (length > 0) {
uint256 packedWarrior;
uint256 cycleSkip = _computeCycleSkip();
for(uint256 i = 0; i < length; i++) {
packedWarrior = pvpQueue[i];
//increase warrior iteration cycle
pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + cycleSkip);
}
}
nextBattleBlock = (PVP_INTERVAL / secondsPerBlock) + currentBlock;
nextPVPBatleBlock = nextBattleBlock;
PVPScheduled(nextBattleBlock);
//if pvp queue will be full and there is still too much time left, then let the battle begin!
} else if (length + 1 == pvpQueue.length && (currentBlock + SAFETY_GAP * 2) < nextBattleBlock) {
nextBattleBlock = currentBlock + SAFETY_GAP;
nextPVPBatleBlock = nextBattleBlock;
PVPScheduled(nextBattleBlock);
}
}
/// @dev Internal utility function to initiate pvp battle, assumes that all battle
/// requirements have been checked.
function _triggerNewPVPContender(address _owner, uint256 _packedWarrior, uint256 fee) internal {
_clarifyPVPSchedule();
//number of pvp cycles the warrior is waiting for suitable enemy match
//increment every time when finishPVP is called and no suitable enemy match was found
_packedWarrior = CryptoUtils._changeCycleValue(_packedWarrior, 0);
//record contender data
pvpQueue[pvpQueueSize++] = _packedWarrior;
warriorToOwner[CryptoUtils._unpackIdValue(_packedWarrior)] = _owner;
//Emit event
PVPNewContender(_owner, CryptoUtils._unpackIdValue(_packedWarrior), fee);
}
function _noMatchingPairs() internal view returns(bool) {
uint256 matchingCount = CryptoUtils._getMatchingIds(_packPVPData(), uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL));
return matchingCount == 0;
}
/*
* @title startPVP enqueues specified warrior to PVP
*
* @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room.
* Once every 15 minutes, we check the warriors in the room and select pairs.
* For those warriors to whom we found couples, fighting is conducted and the results
* are recorded in the profile of the warrior.
*/
function addPVPContender(address _owner, uint256 _packedWarrior) external payable PVPNotPaused {
// Caller must be pvpListener contract
require(msg.sender == address(pvpListener));
require(_owner != address(0));
//contender can be added only while PVP is scheduled in future
//or no matching warrior pairs found
require(nextPVPBatleBlock > block.number || _noMatchingPairs());
// Check that the warrior exists.
require(_packedWarrior != 0);
//owner must withdraw all loot before contending pvp
require(ownerToBooty[_owner] == 0);
//check that there is enough room for new participants
require(pvpQueueSize < pvpQueue.length);
// Checks for payment.
uint256 fee = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarrior));
require(msg.value >= fee);
//
// All checks passed, put the warrior to the queue!
_triggerNewPVPContender(_owner, _packedWarrior, fee);
}
function _packPVPData() internal view returns(uint256[] memory matchingIds) {
uint256 length = pvpQueueSize;
matchingIds = new uint256[](length);
for(uint256 i = 0; i < length; i++) {
matchingIds[i] = pvpQueue[i];
}
return matchingIds;
}
function _computeTotalBooty(uint256[] memory _packedWarriors, uint256 matchingCount) internal view returns(uint256) {
//compute session booty
uint256 sessionLoot = 0;
for(uint256 i = 0; i < matchingCount; i++) {
sessionLoot += _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[i]));
}
return sessionLoot;
}
function _grandPVPRewards(uint256[] memory _packedWarriors, uint256 matchingCount)
internal returns(uint256)
{
uint256 booty = 0;
uint256 packedWarrior;
uint256 failedBooty = 0;
uint256 sessionBooty = _computeTotalBooty(_packedWarriors, matchingCount);
uint256 incentiveCut = _computeIncentiveCut(sessionBooty, pvpMaxIncentiveCut);
uint256 contendersCut = _getPVPContendersCut(incentiveCut);
for(uint256 id = 0; id < matchingCount; id++) {
//give reward to warriors that fought hard
//winner, even ids are winners!
packedWarrior = _packedWarriors[id];
//
//give winner deserved booty 80% from both bets
//must be computed before level reward!
booty = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(packedWarrior)) +
_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[id + 1]));
//
//send reward to warrior owner
failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut));
//loser, they are odd...
//skip them, as they deserve none!
id ++;
}
failedBooty += sendBooty(pvpListener.getBeneficiary(), _computePVPBeneficiaryFee(sessionBooty));
if (failedBooty > 0) {
totalBooty += failedBooty;
}
//if tournament admission start time not passed
//add tournament cut to current tournament bank,
//otherwise to next tournament bank
if (getTournamentAdmissionBlock() > block.number) {
currentTournamentBank += _computeTournamentCut(sessionBooty);
} else {
nextTournamentBank += _computeTournamentCut(sessionBooty);
}
//compute incentive reward
return _computeIncentiveReward(sessionBooty, incentiveCut);
}
function _increaseCycleAndTrimQueue(uint256[] memory matchingIds, uint256 matchingCount) internal {
uint32 length = uint32(matchingIds.length - matchingCount);
uint256 packedWarrior;
uint256 skipCycles = _computeCycleSkip();
for(uint256 i = 0; i < length; i++) {
packedWarrior = matchingIds[matchingCount + i];
//increase warrior iteration cycle
pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + skipCycles);
}
//trim queue
pvpQueueSize = length;
}
function _computeCycleSkip() internal view returns(uint256) {
uint256 number = block.number;
return nextPVPBatleBlock > number ? 0 : (number - nextPVPBatleBlock) * secondsPerBlock / PVP_INTERVAL + 1;
}
function _getWarriorOwners(uint256[] memory pvpData) internal view returns (address[] memory owners){
uint256 length = pvpData.length;
owners = new address[](length);
for(uint256 i = 0; i < length; i ++) {
owners[i] = warriorToOwner[CryptoUtils._unpackIdValue(pvpData[i])];
}
}
// @dev Internal utility function to initiate pvp battle, assumes that all battle
/// requirements have been checked.
function _triggerPVPFinish(uint256[] memory pvpData, uint256 matchingCount) internal returns(uint256){
//
//compute battle results
CryptoUtils._getPVPBattleResults(pvpData, matchingCount, nextPVPBatleBlock);
//
//mark not fought warriors and trim queue
_increaseCycleAndTrimQueue(pvpData, matchingCount);
//
//schedule next battle time
nextPVPBatleBlock = (PVP_INTERVAL / secondsPerBlock) + block.number;
//
//schedule tournament
//if contendersCount is 0 and tournament not scheduled, schedule tournament
//NB MUST be before _grandPVPRewards()
_scheduleTournament();
// compute and grand rewards to warriors,
// put tournament cut to bank, not susceptible to reentry attack because of require(nextPVPBatleBlock <= block.number);
// and require(number of pairs > 1);
uint256 incentiveReward = _grandPVPRewards(pvpData, matchingCount);
//
//notify pvp listener contract
pvpListener.pvpFinished(pvpData, matchingCount);
//
//fire event
PVPFinished(pvpData, _getWarriorOwners(pvpData), matchingCount);
PVPScheduled(nextPVPBatleBlock);
return incentiveReward;
}
/**
* @dev finishPVP this method finds matches of warrior pairs
* in waiting room and computes result of their fights.
*
* The winner gets +1 level, the loser gets +0.5 level
* The winning player gets +130 rating
* The losing player gets -30 or 70 rating (if warrior levelUps after battle) .
* can be called once in 15min.
* NB If the warrior is not picked up in an hour, then we expand the range
* of selection by 25 rating each hour.
*/
function finishPVP() public PVPNotPaused {
// battle interval is over
require(nextPVPBatleBlock <= block.number);
//
//match warriors
uint256[] memory pvpData = _packPVPData();
//match ids and sort them according to matching
uint256 matchingCount = CryptoUtils._getMatchingIds(pvpData, uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL));
// we have at least 1 matching battle pair
require(matchingCount > 1);
// When the all checks done, calculate actual battle result
uint256 incentiveReward = _triggerPVPFinish(pvpData, matchingCount);
//give reward for incentive
safeSend(msg.sender, incentiveReward);
}
// @dev Removes specified warrior from PVP queue
// sets warrior free (IDLE) and returns pvp entrance fee to owner
// @notice This is a state-modifying function that can
// be called while the contract is paused.
// @param _warriorId - ID of warrior in PVP queue
function removePVPContender(uint256 _warriorId) external{
uint256 queueSize = pvpQueueSize;
require(queueSize > 0);
// Caller must be owner of the specified warrior
require(warriorToOwner[_warriorId] == msg.sender);
//warrior must be in pvp queue
int256 warriorIndex = indexOf(_warriorId);
require(warriorIndex >= 0);
//grab warrior data
uint256 warriorData = pvpQueue[uint32(warriorIndex)];
//warrior cycle must be >= 4 (> than 1 hour)
require((CryptoUtils._unpackCycleValue(warriorData) + _computeCycleSkip()) >= 4);
//remove from queue
if (uint256(warriorIndex) < queueSize - 1) {
pvpQueue[uint32(warriorIndex)] = pvpQueue[pvpQueueSize - 1];
}
pvpQueueSize --;
//notify battle listener
pvpListener.pvpContenderRemoved(_warriorId);
//return pvp bet
msg.sender.transfer(_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData)));
//Emit event
PVPContenderRemoved(_warriorId, msg.sender);
}
function getPVPCycles(uint32[] warriorIds) external view returns(uint32[]){
uint256 length = warriorIds.length;
uint32[] memory cycles = new uint32[](length);
int256 index;
uint256 skipCycles = _computeCycleSkip();
for(uint256 i = 0; i < length; i ++) {
index = indexOf(warriorIds[i]);
cycles[i] = index >= 0 ? uint32(CryptoUtils._unpackCycleValue(pvpQueue[uint32(index)]) + skipCycles) : 0;
}
return cycles;
}
// @dev Remove all PVP contenders from PVP queue
// and return all bets to warrior owners.
// NB: this is emergency method, used only in f%#^@up situation
function removeAllPVPContenders() external onlyOwner PVPPaused {
//remove all pvp contenders
uint256 length = pvpQueueSize;
uint256 warriorData;
uint256 warriorId;
uint256 failedBooty;
address owner;
pvpQueueSize = 0;
for(uint256 i = 0; i < length; i++) {
//grab warrior data
warriorData = pvpQueue[i];
warriorId = CryptoUtils._unpackIdValue(warriorData);
//notify battle listener
pvpListener.pvpContenderRemoved(uint32(warriorId));
owner = warriorToOwner[warriorId];
//return pvp bet
failedBooty += sendBooty(owner, _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData)));
}
totalBooty += failedBooty;
}
}
| contract PVP is PausableBattle, PVPInterface {
/* PVP BATLE */
/** list of packed warrior data that will participate in next PVP session.
* Fixed size arry, to evade constant remove and push operations,
* this approach reduces transaction costs involving queue modification. */
uint256[100] public pvpQueue;
//
//queue size
uint256 public pvpQueueSize = 0;
// @dev A mapping from owner address to booty in WEI
// booty is acquired in PVP and Tournament battles and can be
// withdrawn with grabBooty method by the owner of the loot
mapping (address => uint256) public ownerToBooty;
// @dev A mapping from warrior id to owners address
mapping (uint256 => address) internal warriorToOwner;
// An approximation of currently how many seconds are in between blocks.
uint256 internal secondsPerBlock = 15;
// Cut owner takes from, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public pvpOwnerCut;
// Values 0-10,000 map to 0%-100%
//this % of the total bets will be sent as
//a reward to address, that triggered finishPVP method
uint256 public pvpMaxIncentiveCut;
/// @notice The payment base required to use startPVP().
// pvpBattleFee * (warrior.level / POINTS_TO_LEVEL)
uint256 internal pvpBattleFee = 10 finney;
uint256 public constant PVP_INTERVAL = 15 minutes;
uint256 public nextPVPBatleBlock = 0;
//number of WEI in hands of warrior owners
uint256 public totalBooty = 0;
/* TOURNAMENT */
uint256 public constant FUND_GATHERING_TIME = 24 hours;
uint256 public constant ADMISSION_TIME = 12 hours;
uint256 public constant RATING_EXPAND_INTERVAL = 1 hours;
uint256 internal constant SAFETY_GAP = 5;
uint256 internal constant MAX_INCENTIVE_REWARD = 200 finney;
//tournamentContenders size
uint256 public tournamentQueueSize = 0;
// Values 0-10,000 map to 0%-100%
uint256 public tournamentBankCut;
/** tournamentEndBlock, tournament is eligible to be finished only
* after block.number >= tournamentEndBlock
* it depends on FUND_GATHERING_TIME and ADMISSION_TIME */
uint256 public tournamentEndBlock;
//number of WEI in tournament bank
uint256 public currentTournamentBank = 0;
uint256 public nextTournamentBank = 0;
PVPListenerInterface internal pvpListener;
/* EVENTS */
/** @dev TournamentScheduled event. Emitted every time a tournament is scheduled
* @param tournamentEndBlock when block.number > tournamentEndBlock, then tournament
* is eligible to be finished or rescheduled */
event TournamentScheduled(uint256 tournamentEndBlock);
/** @dev PVPScheduled event. Emitted every time a tournament is scheduled
* @param nextPVPBatleBlock when block.number > nextPVPBatleBlock, then pvp battle
* is eligible to be finished or rescheduled */
event PVPScheduled(uint256 nextPVPBatleBlock);
/** @dev PVPNewContender event. Emitted every time a warrior enqueues pvp battle
* @param owner Warrior owner
* @param warriorId Warrior ID that entered PVP queue
* @param entranceFee fee in WEI warrior owner payed to enter PVP
*/
event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee);
/** @dev PVPFinished event. Emitted every time a pvp battle is finished
* @param warriorsData array of pairs of pvp warriors packed to uint256, even => winners, odd => losers
* @param owners array of warrior owners, 1 to 1 with warriorsData, even => winners, odd => losers
* @param matchingCount total number of warriors that fought in current pvp session and got rewards,
* if matchingCount < participants.length then all IDs that are >= matchingCount will
* remain in waiting room, until they are matched.
*/
event PVPFinished(uint256[] warriorsData, address[] owners, uint256 matchingCount);
/** @dev BootySendFailed event. Emitted every time address.send() function failed to transfer Ether to recipient
* in this case recipient Ether is recorded to ownerToBooty mapping, so recipient can withdraw their booty manually
* @param recipient address for whom send failed
* @param amount number of WEI we failed to send
*/
event BootySendFailed(address recipient, uint256 amount);
/** @dev BootyGrabbed event
* @param receiver address who grabbed his booty
* @param amount number of WEI
*/
event BootyGrabbed(address receiver, uint256 amount);
/** @dev PVPContenderRemoved event. Emitted every time warrior is removed from pvp queue by its owner.
* @param warriorId id of the removed warrior
*/
event PVPContenderRemoved(uint256 warriorId, address owner);
function PVP(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut) public {
require((_tournamentBankCut + _pvpCut + _pvpMaxIncentiveCut) <= 10000);
pvpOwnerCut = _pvpCut;
tournamentBankCut = _tournamentBankCut;
pvpMaxIncentiveCut = _pvpMaxIncentiveCut;
}
/** @dev grabBooty sends to message sender his booty in WEI
*/
function grabBooty() external {
uint256 booty = ownerToBooty[msg.sender];
require(booty > 0);
require(totalBooty >= booty);
ownerToBooty[msg.sender] = 0;
totalBooty -= booty;
msg.sender.transfer(booty);
//emit event
BootyGrabbed(msg.sender, booty);
}
function safeSend(address _recipient, uint256 _amaunt) internal {
uint256 failedBooty = sendBooty(_recipient, _amaunt);
if (failedBooty > 0) {
totalBooty += failedBooty;
}
}
function sendBooty(address _recipient, uint256 _amaunt) internal returns(uint256) {
bool success = _recipient.send(_amaunt);
if (!success && _amaunt > 0) {
ownerToBooty[_recipient] += _amaunt;
BootySendFailed(_recipient, _amaunt);
return _amaunt;
}
return 0;
}
//@returns block number, after this block tournament is opened for admission
function getTournamentAdmissionBlock() public view returns(uint256) {
uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock);
return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval;
}
//schedules next turnament time(block)
function _scheduleTournament() internal {
//we can chedule only if there is nobody in tournament queue and
//time of tournament battle have passed
if (tournamentQueueSize == 0 && tournamentEndBlock <= block.number) {
tournamentEndBlock = ((FUND_GATHERING_TIME / 2 + ADMISSION_TIME) / secondsPerBlock) + block.number;
TournamentScheduled(tournamentEndBlock);
}
}
/// @dev Updates the minimum payment required for calling startPVP(). Can only
/// be called by the COO address, and only if pvp queue is empty.
function setPVPEntranceFee(uint256 value) external onlyOwner {
require(pvpQueueSize == 0);
pvpBattleFee = value;
}
//@returns PVP entrance fee for specified warrior level
//@param _levelPoints NB!
function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256) {
return pvpBattleFee * CryptoUtils._getLevel(_levelPoints);
}
//level can only be > 0 and <= 25
function _getPVPFeeByLevel(uint256 _level) internal view returns(uint256) {
return pvpBattleFee * _level;
}
// @dev Computes warrior pvp reward
// @param _totalBet - total bet from both competitors.
function _computePVPReward(uint256 _totalBet, uint256 _contendersCut) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalBet max value is 1000 finney, and _contendersCut aka
// (10000 - pvpOwnerCut - tournamentBankCut - incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalBet.
return _totalBet * _contendersCut / 10000;
}
function _getPVPContendersCut(uint256 _incentiveCut) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// (pvpOwnerCut + tournamentBankCut + pvpMaxIncentiveCut) <= 10000 (see the require()
// statement in the BattleProvider constructor).
// _incentiveCut is guaranteed to be >= 1 and <= pvpMaxIncentiveCut
return (10000 - pvpOwnerCut - tournamentBankCut - _incentiveCut);
}
// @dev Computes warrior pvp reward
// @param _totalSessionLoot - total bets from all competitors.
function _computeIncentiveReward(uint256 _totalSessionLoot, uint256 _incentiveCut) internal pure returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * _incentiveCut / 10000;
}
///@dev computes incentive cut for specified loot,
/// Values 0-10,000 map to 0%-100%
/// max incentive reward cut is 5%, if it exceeds MAX_INCENTIVE_REWARD,
/// then cut is lowered to be equal to MAX_INCENTIVE_REWARD.
/// minimum cut is 0.01%
/// this % of the total bets will be sent as
/// a reward to address, that triggered finishPVP method
function _computeIncentiveCut(uint256 _totalSessionLoot, uint256 maxIncentiveCut) internal pure returns(uint256) {
uint256 result = _totalSessionLoot * maxIncentiveCut / 10000;
result = result <= MAX_INCENTIVE_REWARD ? maxIncentiveCut : MAX_INCENTIVE_REWARD * 10000 / _totalSessionLoot;
//min cut is 0.01%
return result > 0 ? result : 1;
}
// @dev Computes warrior pvp reward
// @param _totalSessionLoot - total bets from all competitors.
function _computePVPBeneficiaryFee(uint256 _totalSessionLoot) internal view returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * pvpOwnerCut / 10000;
}
// @dev Computes tournament bank cut
// @param _totalSessionLoot - total session loot.
function _computeTournamentCut(uint256 _totalSessionLoot) internal view returns (uint256){
// NOTE: We don't use SafeMath (or similar) in this function because
// _totalSessionLoot max value is 37500 finney, and
// (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require()
// statement in the BattleProvider constructor). The result of this
// function is always guaranteed to be <= _totalSessionLoot.
return _totalSessionLoot * tournamentBankCut / 10000;
}
function indexOf(uint256 _warriorId) internal view returns(int256) {
uint256 length = uint256(pvpQueueSize);
for(uint256 i = 0; i < length; i ++) {
if(CryptoUtils._unpackIdValue(pvpQueue[i]) == _warriorId) return int256(i);
}
return -1;
}
function getPVPIncentiveReward(uint256[] memory matchingIds, uint256 matchingCount) internal view returns(uint256) {
uint256 sessionLoot = _computeTotalBooty(matchingIds, matchingCount);
return _computeIncentiveReward(sessionLoot, _computeIncentiveCut(sessionLoot, pvpMaxIncentiveCut));
}
function maxPVPContenders() external view returns(uint256){
return pvpQueue.length;
}
function getPVPState() external view returns
(uint256 contendersCount, uint256 matchingCount, uint256 endBlock, uint256 incentiveReward)
{
uint256[] memory pvpData = _packPVPData();
contendersCount = pvpQueueSize;
matchingCount = CryptoUtils._getMatchingIds(pvpData, PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL);
endBlock = nextPVPBatleBlock;
incentiveReward = getPVPIncentiveReward(pvpData, matchingCount);
}
function canFinishPVP() external view returns(bool) {
return nextPVPBatleBlock <= block.number &&
CryptoUtils._getMatchingIds(_packPVPData(), PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL) > 1;
}
function _clarifyPVPSchedule() internal {
uint256 length = pvpQueueSize;
uint256 currentBlock = block.number;
uint256 nextBattleBlock = nextPVPBatleBlock;
//if battle not scheduled, schedule battle
if (nextBattleBlock <= currentBlock) {
//if queue not empty update cycles
if (length > 0) {
uint256 packedWarrior;
uint256 cycleSkip = _computeCycleSkip();
for(uint256 i = 0; i < length; i++) {
packedWarrior = pvpQueue[i];
//increase warrior iteration cycle
pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + cycleSkip);
}
}
nextBattleBlock = (PVP_INTERVAL / secondsPerBlock) + currentBlock;
nextPVPBatleBlock = nextBattleBlock;
PVPScheduled(nextBattleBlock);
//if pvp queue will be full and there is still too much time left, then let the battle begin!
} else if (length + 1 == pvpQueue.length && (currentBlock + SAFETY_GAP * 2) < nextBattleBlock) {
nextBattleBlock = currentBlock + SAFETY_GAP;
nextPVPBatleBlock = nextBattleBlock;
PVPScheduled(nextBattleBlock);
}
}
/// @dev Internal utility function to initiate pvp battle, assumes that all battle
/// requirements have been checked.
function _triggerNewPVPContender(address _owner, uint256 _packedWarrior, uint256 fee) internal {
_clarifyPVPSchedule();
//number of pvp cycles the warrior is waiting for suitable enemy match
//increment every time when finishPVP is called and no suitable enemy match was found
_packedWarrior = CryptoUtils._changeCycleValue(_packedWarrior, 0);
//record contender data
pvpQueue[pvpQueueSize++] = _packedWarrior;
warriorToOwner[CryptoUtils._unpackIdValue(_packedWarrior)] = _owner;
//Emit event
PVPNewContender(_owner, CryptoUtils._unpackIdValue(_packedWarrior), fee);
}
function _noMatchingPairs() internal view returns(bool) {
uint256 matchingCount = CryptoUtils._getMatchingIds(_packPVPData(), uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL));
return matchingCount == 0;
}
/*
* @title startPVP enqueues specified warrior to PVP
*
* @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room.
* Once every 15 minutes, we check the warriors in the room and select pairs.
* For those warriors to whom we found couples, fighting is conducted and the results
* are recorded in the profile of the warrior.
*/
function addPVPContender(address _owner, uint256 _packedWarrior) external payable PVPNotPaused {
// Caller must be pvpListener contract
require(msg.sender == address(pvpListener));
require(_owner != address(0));
//contender can be added only while PVP is scheduled in future
//or no matching warrior pairs found
require(nextPVPBatleBlock > block.number || _noMatchingPairs());
// Check that the warrior exists.
require(_packedWarrior != 0);
//owner must withdraw all loot before contending pvp
require(ownerToBooty[_owner] == 0);
//check that there is enough room for new participants
require(pvpQueueSize < pvpQueue.length);
// Checks for payment.
uint256 fee = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarrior));
require(msg.value >= fee);
//
// All checks passed, put the warrior to the queue!
_triggerNewPVPContender(_owner, _packedWarrior, fee);
}
function _packPVPData() internal view returns(uint256[] memory matchingIds) {
uint256 length = pvpQueueSize;
matchingIds = new uint256[](length);
for(uint256 i = 0; i < length; i++) {
matchingIds[i] = pvpQueue[i];
}
return matchingIds;
}
function _computeTotalBooty(uint256[] memory _packedWarriors, uint256 matchingCount) internal view returns(uint256) {
//compute session booty
uint256 sessionLoot = 0;
for(uint256 i = 0; i < matchingCount; i++) {
sessionLoot += _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[i]));
}
return sessionLoot;
}
function _grandPVPRewards(uint256[] memory _packedWarriors, uint256 matchingCount)
internal returns(uint256)
{
uint256 booty = 0;
uint256 packedWarrior;
uint256 failedBooty = 0;
uint256 sessionBooty = _computeTotalBooty(_packedWarriors, matchingCount);
uint256 incentiveCut = _computeIncentiveCut(sessionBooty, pvpMaxIncentiveCut);
uint256 contendersCut = _getPVPContendersCut(incentiveCut);
for(uint256 id = 0; id < matchingCount; id++) {
//give reward to warriors that fought hard
//winner, even ids are winners!
packedWarrior = _packedWarriors[id];
//
//give winner deserved booty 80% from both bets
//must be computed before level reward!
booty = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(packedWarrior)) +
_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[id + 1]));
//
//send reward to warrior owner
failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut));
//loser, they are odd...
//skip them, as they deserve none!
id ++;
}
failedBooty += sendBooty(pvpListener.getBeneficiary(), _computePVPBeneficiaryFee(sessionBooty));
if (failedBooty > 0) {
totalBooty += failedBooty;
}
//if tournament admission start time not passed
//add tournament cut to current tournament bank,
//otherwise to next tournament bank
if (getTournamentAdmissionBlock() > block.number) {
currentTournamentBank += _computeTournamentCut(sessionBooty);
} else {
nextTournamentBank += _computeTournamentCut(sessionBooty);
}
//compute incentive reward
return _computeIncentiveReward(sessionBooty, incentiveCut);
}
function _increaseCycleAndTrimQueue(uint256[] memory matchingIds, uint256 matchingCount) internal {
uint32 length = uint32(matchingIds.length - matchingCount);
uint256 packedWarrior;
uint256 skipCycles = _computeCycleSkip();
for(uint256 i = 0; i < length; i++) {
packedWarrior = matchingIds[matchingCount + i];
//increase warrior iteration cycle
pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + skipCycles);
}
//trim queue
pvpQueueSize = length;
}
function _computeCycleSkip() internal view returns(uint256) {
uint256 number = block.number;
return nextPVPBatleBlock > number ? 0 : (number - nextPVPBatleBlock) * secondsPerBlock / PVP_INTERVAL + 1;
}
function _getWarriorOwners(uint256[] memory pvpData) internal view returns (address[] memory owners){
uint256 length = pvpData.length;
owners = new address[](length);
for(uint256 i = 0; i < length; i ++) {
owners[i] = warriorToOwner[CryptoUtils._unpackIdValue(pvpData[i])];
}
}
// @dev Internal utility function to initiate pvp battle, assumes that all battle
/// requirements have been checked.
function _triggerPVPFinish(uint256[] memory pvpData, uint256 matchingCount) internal returns(uint256){
//
//compute battle results
CryptoUtils._getPVPBattleResults(pvpData, matchingCount, nextPVPBatleBlock);
//
//mark not fought warriors and trim queue
_increaseCycleAndTrimQueue(pvpData, matchingCount);
//
//schedule next battle time
nextPVPBatleBlock = (PVP_INTERVAL / secondsPerBlock) + block.number;
//
//schedule tournament
//if contendersCount is 0 and tournament not scheduled, schedule tournament
//NB MUST be before _grandPVPRewards()
_scheduleTournament();
// compute and grand rewards to warriors,
// put tournament cut to bank, not susceptible to reentry attack because of require(nextPVPBatleBlock <= block.number);
// and require(number of pairs > 1);
uint256 incentiveReward = _grandPVPRewards(pvpData, matchingCount);
//
//notify pvp listener contract
pvpListener.pvpFinished(pvpData, matchingCount);
//
//fire event
PVPFinished(pvpData, _getWarriorOwners(pvpData), matchingCount);
PVPScheduled(nextPVPBatleBlock);
return incentiveReward;
}
/**
* @dev finishPVP this method finds matches of warrior pairs
* in waiting room and computes result of their fights.
*
* The winner gets +1 level, the loser gets +0.5 level
* The winning player gets +130 rating
* The losing player gets -30 or 70 rating (if warrior levelUps after battle) .
* can be called once in 15min.
* NB If the warrior is not picked up in an hour, then we expand the range
* of selection by 25 rating each hour.
*/
function finishPVP() public PVPNotPaused {
// battle interval is over
require(nextPVPBatleBlock <= block.number);
//
//match warriors
uint256[] memory pvpData = _packPVPData();
//match ids and sort them according to matching
uint256 matchingCount = CryptoUtils._getMatchingIds(pvpData, uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL));
// we have at least 1 matching battle pair
require(matchingCount > 1);
// When the all checks done, calculate actual battle result
uint256 incentiveReward = _triggerPVPFinish(pvpData, matchingCount);
//give reward for incentive
safeSend(msg.sender, incentiveReward);
}
// @dev Removes specified warrior from PVP queue
// sets warrior free (IDLE) and returns pvp entrance fee to owner
// @notice This is a state-modifying function that can
// be called while the contract is paused.
// @param _warriorId - ID of warrior in PVP queue
function removePVPContender(uint256 _warriorId) external{
uint256 queueSize = pvpQueueSize;
require(queueSize > 0);
// Caller must be owner of the specified warrior
require(warriorToOwner[_warriorId] == msg.sender);
//warrior must be in pvp queue
int256 warriorIndex = indexOf(_warriorId);
require(warriorIndex >= 0);
//grab warrior data
uint256 warriorData = pvpQueue[uint32(warriorIndex)];
//warrior cycle must be >= 4 (> than 1 hour)
require((CryptoUtils._unpackCycleValue(warriorData) + _computeCycleSkip()) >= 4);
//remove from queue
if (uint256(warriorIndex) < queueSize - 1) {
pvpQueue[uint32(warriorIndex)] = pvpQueue[pvpQueueSize - 1];
}
pvpQueueSize --;
//notify battle listener
pvpListener.pvpContenderRemoved(_warriorId);
//return pvp bet
msg.sender.transfer(_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData)));
//Emit event
PVPContenderRemoved(_warriorId, msg.sender);
}
function getPVPCycles(uint32[] warriorIds) external view returns(uint32[]){
uint256 length = warriorIds.length;
uint32[] memory cycles = new uint32[](length);
int256 index;
uint256 skipCycles = _computeCycleSkip();
for(uint256 i = 0; i < length; i ++) {
index = indexOf(warriorIds[i]);
cycles[i] = index >= 0 ? uint32(CryptoUtils._unpackCycleValue(pvpQueue[uint32(index)]) + skipCycles) : 0;
}
return cycles;
}
// @dev Remove all PVP contenders from PVP queue
// and return all bets to warrior owners.
// NB: this is emergency method, used only in f%#^@up situation
function removeAllPVPContenders() external onlyOwner PVPPaused {
//remove all pvp contenders
uint256 length = pvpQueueSize;
uint256 warriorData;
uint256 warriorId;
uint256 failedBooty;
address owner;
pvpQueueSize = 0;
for(uint256 i = 0; i < length; i++) {
//grab warrior data
warriorData = pvpQueue[i];
warriorId = CryptoUtils._unpackIdValue(warriorData);
//notify battle listener
pvpListener.pvpContenderRemoved(uint32(warriorId));
owner = warriorToOwner[warriorId];
//return pvp bet
failedBooty += sendBooty(owner, _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData)));
}
totalBooty += failedBooty;
}
}
| 79,038 |
57 | // Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens._beneficiary Address receiving the tokens_tokenAmount Number of tokens to be purchased/ | function _processPurchase(address _beneficiary, uint256 _tokenAmount) private {
_deliverTokens(_beneficiary, _tokenAmount);
}
| function _processPurchase(address _beneficiary, uint256 _tokenAmount) private {
_deliverTokens(_beneficiary, _tokenAmount);
}
| 1,289 |
387 | // Max allocation percentage | uint256 internal constant MAX_STRATEGY_ALLOCATION_PERCENTAGE = 93;
| uint256 internal constant MAX_STRATEGY_ALLOCATION_PERCENTAGE = 93;
| 67,990 |
149 | // Transfer reward and distribute the fee This is the new implementation of distribute() which uses internal fees | * defined in the {RewardHandler} contract.
*
* @param recipient The recipient of the reward
* @param amount The amount of WOWS to transfer to the recipient
* @param fee The reward fee in 1e6 factor notation
*/
function distribute2(
address recipient,
uint256 amount,
uint32 fee
) external;
/**
* @dev Transfer reward and distribute the fee
*
* This is the current implementation, needed for backward compatibility.
*
* Current ERC1155Minter and Controller call this function, later
* reward handler clients should call the the new one with internal
* fees specified in this contract.
*
* uint32 values are in 1e6 factor notation.
*/
function distribute(
address recipient,
uint256 amount,
uint32 fee,
uint32 toTeam,
uint32 toMarketing,
uint32 toBooster,
uint32 toRewardPool
) external;
}
| * defined in the {RewardHandler} contract.
*
* @param recipient The recipient of the reward
* @param amount The amount of WOWS to transfer to the recipient
* @param fee The reward fee in 1e6 factor notation
*/
function distribute2(
address recipient,
uint256 amount,
uint32 fee
) external;
/**
* @dev Transfer reward and distribute the fee
*
* This is the current implementation, needed for backward compatibility.
*
* Current ERC1155Minter and Controller call this function, later
* reward handler clients should call the the new one with internal
* fees specified in this contract.
*
* uint32 values are in 1e6 factor notation.
*/
function distribute(
address recipient,
uint256 amount,
uint32 fee,
uint32 toTeam,
uint32 toMarketing,
uint32 toBooster,
uint32 toRewardPool
) external;
}
| 56,926 |
168 | // Returns whether 'tokenId' exists. | * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted ('_mint'),
* and stop existing when they are burned ('_burn').
*/
function _exists(uint256 tokenId) internal view virtual returns(bool) {
return _owners[tokenId] != address(0);
}
| * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted ('_mint'),
* and stop existing when they are burned ('_burn').
*/
function _exists(uint256 tokenId) internal view virtual returns(bool) {
return _owners[tokenId] != address(0);
}
| 19,813 |
1 | // Revoke from the deployer's account all the roles that are setup by the ERC20PresetMinterPauser | renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
renounceRole(MINTER_ROLE, _msgSender());
renounceRole(PAUSER_ROLE, _msgSender());
| renounceRole(DEFAULT_ADMIN_ROLE, _msgSender());
renounceRole(MINTER_ROLE, _msgSender());
renounceRole(PAUSER_ROLE, _msgSender());
| 44,527 |
18 | // This will generate a 11 character string. The first 2 digits are the palette. | string memory currentHash = "";
for (uint8 i = 0; i < 6; i++) {
SEED_NONCE++;
uint16 _randinput = uint16(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
| string memory currentHash = "";
for (uint8 i = 0; i < 6; i++) {
SEED_NONCE++;
uint16 _randinput = uint16(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
| 5,738 |
53 | // can accept ether | //function() payable public {
//}
| //function() payable public {
//}
| 67,807 |
116 | // Allows the owner to update the address of the to-be-written FOI token contract.When the pre-sale is over, this contract will mint the tokens for people who purchasedin the pre-sale.Make sure that this contract is the owner of the token contract. _token The address of the FOI token contract / | function updateTokenAddress(MintableToken _token) onlyOwner public {
require(!isFinalized);
require(_token.owner() == address(this));
token = _token;
}
| function updateTokenAddress(MintableToken _token) onlyOwner public {
require(!isFinalized);
require(_token.owner() == address(this));
token = _token;
}
| 47,070 |
46 | // Public | function getTotalPrizeBonds() public view returns(uint256) {
return prizeBonds.length;
}
| function getTotalPrizeBonds() public view returns(uint256) {
return prizeBonds.length;
}
| 949 |
0 | // iL2ERC1155Bridge / | interface iL2ERC1155Bridge {
// add events
event WithdrawalInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes _data
);
event WithdrawalBatchInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256[] _tokenIds,
uint256[] _amounts,
bytes _data
);
event DepositFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes _data
);
event DepositBatchFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256[] _tokenIds,
uint256[] _amounts,
bytes _data
);
event DepositFailed (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes _data
);
event DepositBatchFailed (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256[] _tokenIds,
uint256[] _amounts,
bytes _data
);
function withdraw(
address _l2Contract,
uint256 _tokenId,
uint256 _amount,
bytes calldata _data,
uint32 _l1Gas
)
external;
function withdrawBatch(
address _l2Contract,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes calldata _data,
uint32 _l1Gas
)
external;
function withdrawTo(
address _l2Contract,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes calldata _data,
uint32 _l1Gas
)
external;
function withdrawBatchTo(
address _l2Contract,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes calldata _data,
uint32 _l1Gas
)
external;
function finalizeDeposit(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes calldata _data
)
external;
function finalizeDepositBatch(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes calldata _data
)
external;
}
| interface iL2ERC1155Bridge {
// add events
event WithdrawalInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes _data
);
event WithdrawalBatchInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256[] _tokenIds,
uint256[] _amounts,
bytes _data
);
event DepositFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes _data
);
event DepositBatchFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256[] _tokenIds,
uint256[] _amounts,
bytes _data
);
event DepositFailed (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes _data
);
event DepositBatchFailed (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256[] _tokenIds,
uint256[] _amounts,
bytes _data
);
function withdraw(
address _l2Contract,
uint256 _tokenId,
uint256 _amount,
bytes calldata _data,
uint32 _l1Gas
)
external;
function withdrawBatch(
address _l2Contract,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes calldata _data,
uint32 _l1Gas
)
external;
function withdrawTo(
address _l2Contract,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes calldata _data,
uint32 _l1Gas
)
external;
function withdrawBatchTo(
address _l2Contract,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes calldata _data,
uint32 _l1Gas
)
external;
function finalizeDeposit(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256 _tokenId,
uint256 _amount,
bytes calldata _data
)
external;
function finalizeDepositBatch(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
bytes calldata _data
)
external;
}
| 29,367 |
9 | // Emit an event so keepers know what pools earned rewards this epoch. | emit StakingPoolEarnedRewardsInEpoch(currentEpoch_, poolId);
| emit StakingPoolEarnedRewardsInEpoch(currentEpoch_, poolId);
| 24,969 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.