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
|
|---|---|---|---|---|
4
|
// Verify the merkle proof
|
bytes32 leaf = keccak256(abi.encodePacked(account, cumulativeAmount));
require(_verifyAsm(merkleProof, expectedMerkleRoot, leaf), 'Invalid proof');
|
bytes32 leaf = keccak256(abi.encodePacked(account, cumulativeAmount));
require(_verifyAsm(merkleProof, expectedMerkleRoot, leaf), 'Invalid proof');
| 6,435
|
23
|
// Check that the item has been moved to the rentedItems array
|
require(pool.rentedItems[pool.rentedItems.length - 1] == selectedItemId, "Item not added to rented items");
|
require(pool.rentedItems[pool.rentedItems.length - 1] == selectedItemId, "Item not added to rented items");
| 23,917
|
10
|
// Transfers ownership of a node to a new address. May only be called by the currentowner of the node. _node The node to transfer ownership of. _owner The address of the new owner. /
|
function setOwner(bytes32 _node, address _owner) public only_owner(_node) {
emit Transfer(_node, _owner);
records[_node].owner = _owner;
}
|
function setOwner(bytes32 _node, address _owner) public only_owner(_node) {
emit Transfer(_node, _owner);
records[_node].owner = _owner;
}
| 22,608
|
150
|
// Call from.tokensToSend() if the interface is registered operator address operator requesting the transfer from address token holder address to address recipient address amount uint256 amount of tokens to transfer userData bytes extra information provided by the token holder (if any) operatorData bytes extra information provided by the operator (if any) /
|
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
|
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
| 510
|
353
|
// Issue their new synths
|
synths[destinationCurrencyKey].issue(destinationAddress, amountReceived);
|
synths[destinationCurrencyKey].issue(destinationAddress, amountReceived);
| 35,725
|
0
|
// The arguments and returns from the swap contract. These may need to be updated in the future if the contract changes.
|
interface ethswap {
function initiate(uint refundTimestamp, bytes32 secretHash, address participant) payable external;
function refund(bytes32 secretHash) external;
}
|
interface ethswap {
function initiate(uint refundTimestamp, bytes32 secretHash, address participant) payable external;
function refund(bytes32 secretHash) external;
}
| 30,914
|
32
|
// Performs a Solidity function call using a low level `call`. Aplain`call` is an unsafe replacement for a function call: use thisfunction instead. If `target` reverts with a revert reason, it is bubbled up by thisfunction (like regular Solidity function calls). Returns the raw returned data. To convert to the expected return value, Requirements: - `target` must be a contract.- calling `target` with `data` must not revert. _Available since v3.1._ / function functionCall(address target, bytes memory data) internal returns (bytes memory)
|
// {
// return functionCall(target, data, "Address: low-level call failed");
// }
|
// {
// return functionCall(target, data, "Address: low-level call failed");
// }
| 13,729
|
52
|
// Track consent of an actor in a market to allow the specified seller or buyer delegate/ to provide or consume data under the respective API catalog in the given market.//marketId The ID of the XBR data market in which to provide or consume data. Any/ terms attached to the market or the API apply./delegate The address of the off-chain provider or consumer delegate, which is a piece/ of software acting on behalf and under consent of the actor in the market./delegateType The type of off-chain delegate, a data provider or data consumer./apiCatalog The ID of the API or API catalog
|
function setConsent (bytes16 marketId, address delegate, uint8 delegateType, bytes16 apiCatalog,
|
function setConsent (bytes16 marketId, address delegate, uint8 delegateType, bytes16 apiCatalog,
| 51,814
|
12
|
// === PUBLIC READ-ONLY ===
|
function getName()
public
view
returns (string memory)
|
function getName()
public
view
returns (string memory)
| 59,184
|
44
|
// Record the token Id to artist drop id mapping
|
tokenIdToArtistDropId[newTokenId] = _id;
|
tokenIdToArtistDropId[newTokenId] = _id;
| 23,967
|
34
|
// On 'closing' we shall increment cycle counter
|
function openCloseMint(bool _status) public onlyOwner{
isMintWindowOpen = _status;
if(_status != false)
{
cycleCounter +=1;
}
}
|
function openCloseMint(bool _status) public onlyOwner{
isMintWindowOpen = _status;
if(_status != false)
{
cycleCounter +=1;
}
}
| 18,276
|
236
|
// Mapping owner -> first owned token Note that we work 1 based here because of initialization e.g. firstId == 1 links to tokenId 0;
|
struct Owned {
uint256 count;
ListKey listKey; // First tokenId in linked list
}
|
struct Owned {
uint256 count;
ListKey listKey; // First tokenId in linked list
}
| 55,965
|
124
|
// daysPassed will be less than 15 so no worries about overflow here
|
calcPercent = (15 - uint8(daysPassed));
|
calcPercent = (15 - uint8(daysPassed));
| 14,446
|
59
|
// select miners
|
selectArbitersFromMiners (currentJob, arbitraionJobId);
currentJob.maxMinerTime = now.add(maxMinerTime);
payTriggerman(1, currentJob);
emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 1, now);
|
selectArbitersFromMiners (currentJob, arbitraionJobId);
currentJob.maxMinerTime = now.add(maxMinerTime);
payTriggerman(1, currentJob);
emit ArbitrationJobTriggered(arbitraionJobId, msg.sender, 1, now);
| 48,202
|
199
|
// Converts a function taking a calldata pointer and returning a memory pointer into a function taking that calldata pointer and returning a dynamic array of CriteriaResolver types.inFn The input function, taking an arbitrary calldata pointer andreturning an arbitrary memory pointer. return outFn The output function, taking an arbitrary calldata pointerand returning a dynamic array of CriteriaResolver types. /
|
function _toCriteriaResolversReturnType(
function(CalldataPointer) internal pure returns (MemoryPointer) inFn
)
internal
pure
returns (
function(CalldataPointer)
internal
pure
returns (CriteriaResolver[] memory) outFn
|
function _toCriteriaResolversReturnType(
function(CalldataPointer) internal pure returns (MemoryPointer) inFn
)
internal
pure
returns (
function(CalldataPointer)
internal
pure
returns (CriteriaResolver[] memory) outFn
| 20,582
|
57
|
// Safely mints `quantity` tokens and transfers them to `to`. Requirements: - If `to` refers to a smart contract, it must implement
|
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (to.code.length != 0) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex < end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex < end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
|
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (to.code.length != 0) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex < end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex < end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
| 29,596
|
156
|
// (myBalance100) / poolBalance == (myBalance / poolBalance)100
|
return (getMyBalance(msg.sender).mul(100)).div(poolTokenBalance());
|
return (getMyBalance(msg.sender).mul(100)).div(poolTokenBalance());
| 28,340
|
24
|
// only tgeFactory or pool
|
require(
msg.sender == address(service.tgeFactory()) ||
msg.sender == address(this),
ExceptionsLibrary.NOT_TGE_FACTORY
);
if (msg.sender == address(service.tgeFactory())) {
if (address(getGovernanceToken()) != address(0)) {
require(!isDAO(), ExceptionsLibrary.IS_DAO);
require(
ITGE(getGovernanceToken().lastTGE()).state() !=
|
require(
msg.sender == address(service.tgeFactory()) ||
msg.sender == address(this),
ExceptionsLibrary.NOT_TGE_FACTORY
);
if (msg.sender == address(service.tgeFactory())) {
if (address(getGovernanceToken()) != address(0)) {
require(!isDAO(), ExceptionsLibrary.IS_DAO);
require(
ITGE(getGovernanceToken().lastTGE()).state() !=
| 34,055
|
65
|
// next we need to allow the uniswapv2 router to spend the token we just sent to this contractby calling IERC20 approve you allow the uniswap contract to spend the tokens in this contract
|
IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn);
|
IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn);
| 29,345
|
8
|
// its opponent first differ.
|
uint256 jrhNnodes; // The number of nodes in the tree the JRH is the root of.
uint256 lowerBound; // During the binary search, the lowest index in the justification tree that might still be the
|
uint256 jrhNnodes; // The number of nodes in the tree the JRH is the root of.
uint256 lowerBound; // During the binary search, the lowest index in the justification tree that might still be the
| 15,344
|
2
|
// This project returns the SVG data as the art string.
|
return _getSvgDataURI(tokenType);
|
return _getSvgDataURI(tokenType);
| 32,091
|
40
|
// Don't allow people to vote with flash loans
|
if (_stake.lastClaim(stakers[i]) == block.timestamp) {
continue;
}
|
if (_stake.lastClaim(stakers[i]) == block.timestamp) {
continue;
}
| 27,042
|
30
|
// Allows the smart contract, the contract owner, or the contract admin of any NFT collection to specify their own bounded price at the collection level. Throws when the specified tokenAddress is address(0).Throws when the caller is not the contract, the owner or the administrator of the specified tokenAddress.Throws when the previously set pricing bounds were set to be immutable.Throws when the specified floor price is greater than the ceiling price.<h4>Postconditions:</h4>1. The collection-level pricing bounds for the specified tokenAddress has been set.2. An `UpdatedCollectionLevelPricingBoundaries` event has been emitted. tokenAddress The smart contract address of the NFT collection.pricingBounds Including the floor price,
|
function setCollectionPricingBounds(address tokenAddress, PricingBounds calldata pricingBounds) external override {
_requireCallerIsNFTOrContractOwnerOrAdmin(tokenAddress);
if(collectionPricingBounds[tokenAddress].isImmutable) {
revert PaymentProcessor__PricingBoundsAreImmutable();
}
if(pricingBounds.floorPrice > pricingBounds.ceilingPrice) {
revert PaymentProcessor__CeilingPriceMustBeGreaterThanFloorPrice();
}
collectionPricingBounds[tokenAddress] = pricingBounds;
emit UpdatedCollectionLevelPricingBoundaries(
tokenAddress,
pricingBounds.floorPrice,
pricingBounds.ceilingPrice);
}
|
function setCollectionPricingBounds(address tokenAddress, PricingBounds calldata pricingBounds) external override {
_requireCallerIsNFTOrContractOwnerOrAdmin(tokenAddress);
if(collectionPricingBounds[tokenAddress].isImmutable) {
revert PaymentProcessor__PricingBoundsAreImmutable();
}
if(pricingBounds.floorPrice > pricingBounds.ceilingPrice) {
revert PaymentProcessor__CeilingPriceMustBeGreaterThanFloorPrice();
}
collectionPricingBounds[tokenAddress] = pricingBounds;
emit UpdatedCollectionLevelPricingBoundaries(
tokenAddress,
pricingBounds.floorPrice,
pricingBounds.ceilingPrice);
}
| 39,654
|
28
|
// Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.account Address of the contract to check.interfaceId ERC165 interface to check. return True if `account` implements `interfaceId`, false otherwise. /
|
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
|
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
| 6,043
|
35
|
// Making sure sent amount is greater than or equal to the sellingPrice
|
require(msg.value >= sellingPrice);
|
require(msg.value >= sellingPrice);
| 38,299
|
14
|
// Grant the contract deployer all other roles by default
|
_grantAllRoles(owner_);
if (owner_!=_msgSender()) {
_transferOwnership(owner_);
}
|
_grantAllRoles(owner_);
if (owner_!=_msgSender()) {
_transferOwnership(owner_);
}
| 28,705
|
24
|
// if auction has not yet ended, cannot start another
|
require(block.timestamp > auctionEndTimestamp,"Auction has not yet ended");
require(address(this).balance >= reward,"Not enough funds to cover reward");
require(auctionDuration >= 3600,"Auction duration has to be at least an hour (3600 seonds)");
require(auctionRewardClaimed == true || auctionEndTimestamp == 0,"The reward of any previous auctions must be paid out before starting a new auction");
|
require(block.timestamp > auctionEndTimestamp,"Auction has not yet ended");
require(address(this).balance >= reward,"Not enough funds to cover reward");
require(auctionDuration >= 3600,"Auction duration has to be at least an hour (3600 seonds)");
require(auctionRewardClaimed == true || auctionEndTimestamp == 0,"The reward of any previous auctions must be paid out before starting a new auction");
| 8,317
|
413
|
// get amount in Uniswap
|
(uint256 now0, uint256 now1) = pos._getTotalAmounts(performanceFee);
if(now0 > 0 || now1 > 0){ //
|
(uint256 now0, uint256 now1) = pos._getTotalAmounts(performanceFee);
if(now0 > 0 || now1 > 0){ //
| 28,735
|
20
|
// Transfer votes to anybody
|
function transferVotes (address to, uint candidate) public inVotingPeriod {
require(userVotesDistribution[msg.sender][candidate] > 0);
uint votesToTransfer = userVotesDistribution[msg.sender][candidate];
userVotesDistribution[msg.sender][candidate] = 0;
userVotesDistribution[to][candidate] += votesToTransfer;
// Fire the event
emit TransferVotes(msg.sender, to, candidate, votesToTransfer);
}
|
function transferVotes (address to, uint candidate) public inVotingPeriod {
require(userVotesDistribution[msg.sender][candidate] > 0);
uint votesToTransfer = userVotesDistribution[msg.sender][candidate];
userVotesDistribution[msg.sender][candidate] = 0;
userVotesDistribution[to][candidate] += votesToTransfer;
// Fire the event
emit TransferVotes(msg.sender, to, candidate, votesToTransfer);
}
| 39,026
|
15
|
// Returns whether an operation is done or not. /
|
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
|
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
| 3,418
|
35
|
// this library provides a set of complex math operations /
|
library MathEx {
error Overflow();
/**
* @dev returns `2 ^ f` by calculating `e ^ (f * ln(2))`, where `e` is Euler's number:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp2(Fraction memory f) internal pure returns (Fraction memory) {
uint256 x = MathEx.mulDivF(LN2, f.n, f.d);
uint256 y;
uint256 z;
uint256 n;
if (x >= (ONE << 4)) {
revert Overflow();
}
unchecked {
z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
z = (z * y) / ONE;
n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / ONE;
n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / ONE;
n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / ONE;
n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / ONE;
n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / ONE;
n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / ONE;
n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / ONE;
n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / ONE;
n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / ONE;
n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / ONE;
n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / ONE;
n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / ONE;
n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / ONE;
n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / ONE;
n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / ONE;
n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / ONE;
n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / ONE;
n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / ONE;
n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & (ONE >> 3)) != 0)
n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^(2^-3)
if ((x & (ONE >> 2)) != 0)
n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^(2^-2)
if ((x & (ONE >> 1)) != 0)
n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^(2^-1)
if ((x & (ONE << 0)) != 0)
n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^(2^+0)
if ((x & (ONE << 1)) != 0)
n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^(2^+1)
if ((x & (ONE << 2)) != 0)
n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^(2^+2)
if ((x & (ONE << 3)) != 0)
n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^(2^+3)
}
return Fraction({ n: n, d: ONE });
}
/**
* @dev returns a fraction with truncated components
* note that since the input value is truncated, the use of the method incurs precision loss
*/
function truncatedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
Fraction memory truncated = Fraction({ n: fraction.n / scale, d: fraction.d / scale });
if (truncated.d == 0) {
revert InvalidFraction();
}
return truncated;
}
/**
* @dev returns the weighted average of two fractions
*/
function weightedAverage(
Fraction memory fraction1,
Fraction memory fraction2,
uint256 weight1,
uint256 weight2
) internal pure returns (Fraction memory) {
return
Fraction({
n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
d: fraction1.d * fraction2.d * (weight1 + weight2)
});
}
/**
* @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
* for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
*/
function isInRange(
Fraction memory baseSample,
Fraction memory offsetSample,
uint32 maxDeviationPPM
) internal pure returns (bool) {
Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
return lte512(min, mid) && lte512(mid, max);
}
/**
* @dev returns an `Sint256` positive representation of an unsigned integer
*/
function toPos256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: false });
}
/**
* @dev returns an `Sint256` negative representation of an unsigned integer
*/
function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: true });
}
/**
* @dev returns the largest integer smaller than or equal to `x * y / z`
*/
function mulDivF(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
Uint512 memory xy = mul512(x, y);
// if `x * y < 2 ^ 256`
if (xy.hi == 0) {
return xy.lo / z;
}
// assert `x * y / z < 2 ^ 256`
if (xy.hi >= z) {
revert Overflow();
}
uint256 m = _mulMod(x, y, z); // `m = x * y % z`
Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
// if `n < 2 ^ 256`
if (n.hi == 0) {
return n.lo / z;
}
uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
}
/**
* @dev returns the smallest integer larger than or equal to `x * y / z`
*/
function mulDivC(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
uint256 w = mulDivF(x, y, z);
if (_mulMod(x, y, z) > 0) {
if (w >= type(uint256).max) {
revert Overflow();
}
return w + 1;
}
return w;
}
/**
* @dev returns the maximum of `n1 - n2` and 0
*/
function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
return n1 > n2 ? n1 - n2 : 0;
}
/**
* @dev returns the value of `x > y`
*/
function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
}
/**
* @dev returns the value of `x < y`
*/
function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/**
* @dev returns the value of `x >= y`
*/
function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !lt512(x, y);
}
/**
* @dev returns the value of `x <= y`
*/
function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !gt512(x, y);
}
/**
* @dev returns the value of `x * y`
*/
function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
uint256 p = _mulModMax(x, y);
uint256 q = _unsafeMul(x, y);
if (p >= q) {
return Uint512({ hi: p - q, lo: q });
}
return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
}
/**
* @dev returns the value of `x - y`, given that `x >= y`
*/
function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
if (x.lo >= y) {
return Uint512({ hi: x.hi, lo: x.lo - y });
}
return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
}
/**
* @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
*/
function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
}
/**
* @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
*/
function _inv256(uint256 d) private pure returns (uint256) {
// approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
uint256 x = 1;
for (uint256 i = 0; i < 8; i++) {
x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
}
return x;
}
/**
* @dev returns `(x + y) % 2 ^ 256`
*/
function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x + y;
}
}
/**
* @dev returns `(x - y) % 2 ^ 256`
*/
function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x - y;
}
}
/**
* @dev returns `(x * y) % 2 ^ 256`
*/
function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x * y;
}
}
/**
* @dev returns `x * y % (2 ^ 256 - 1)`
*/
function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
return mulmod(x, y, type(uint256).max);
}
/**
* @dev returns `x * y % z`
*/
function _mulMod(
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return mulmod(x, y, z);
}
}
|
library MathEx {
error Overflow();
/**
* @dev returns `2 ^ f` by calculating `e ^ (f * ln(2))`, where `e` is Euler's number:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp2(Fraction memory f) internal pure returns (Fraction memory) {
uint256 x = MathEx.mulDivF(LN2, f.n, f.d);
uint256 y;
uint256 z;
uint256 n;
if (x >= (ONE << 4)) {
revert Overflow();
}
unchecked {
z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
z = (z * y) / ONE;
n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / ONE;
n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / ONE;
n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / ONE;
n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / ONE;
n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / ONE;
n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / ONE;
n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / ONE;
n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / ONE;
n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / ONE;
n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / ONE;
n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / ONE;
n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / ONE;
n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / ONE;
n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / ONE;
n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / ONE;
n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / ONE;
n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / ONE;
n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / ONE;
n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & (ONE >> 3)) != 0)
n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^(2^-3)
if ((x & (ONE >> 2)) != 0)
n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^(2^-2)
if ((x & (ONE >> 1)) != 0)
n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^(2^-1)
if ((x & (ONE << 0)) != 0)
n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^(2^+0)
if ((x & (ONE << 1)) != 0)
n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^(2^+1)
if ((x & (ONE << 2)) != 0)
n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^(2^+2)
if ((x & (ONE << 3)) != 0)
n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^(2^+3)
}
return Fraction({ n: n, d: ONE });
}
/**
* @dev returns a fraction with truncated components
* note that since the input value is truncated, the use of the method incurs precision loss
*/
function truncatedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
Fraction memory truncated = Fraction({ n: fraction.n / scale, d: fraction.d / scale });
if (truncated.d == 0) {
revert InvalidFraction();
}
return truncated;
}
/**
* @dev returns the weighted average of two fractions
*/
function weightedAverage(
Fraction memory fraction1,
Fraction memory fraction2,
uint256 weight1,
uint256 weight2
) internal pure returns (Fraction memory) {
return
Fraction({
n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
d: fraction1.d * fraction2.d * (weight1 + weight2)
});
}
/**
* @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
* for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
*/
function isInRange(
Fraction memory baseSample,
Fraction memory offsetSample,
uint32 maxDeviationPPM
) internal pure returns (bool) {
Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
return lte512(min, mid) && lte512(mid, max);
}
/**
* @dev returns an `Sint256` positive representation of an unsigned integer
*/
function toPos256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: false });
}
/**
* @dev returns an `Sint256` negative representation of an unsigned integer
*/
function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: true });
}
/**
* @dev returns the largest integer smaller than or equal to `x * y / z`
*/
function mulDivF(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
Uint512 memory xy = mul512(x, y);
// if `x * y < 2 ^ 256`
if (xy.hi == 0) {
return xy.lo / z;
}
// assert `x * y / z < 2 ^ 256`
if (xy.hi >= z) {
revert Overflow();
}
uint256 m = _mulMod(x, y, z); // `m = x * y % z`
Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
// if `n < 2 ^ 256`
if (n.hi == 0) {
return n.lo / z;
}
uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
}
/**
* @dev returns the smallest integer larger than or equal to `x * y / z`
*/
function mulDivC(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
uint256 w = mulDivF(x, y, z);
if (_mulMod(x, y, z) > 0) {
if (w >= type(uint256).max) {
revert Overflow();
}
return w + 1;
}
return w;
}
/**
* @dev returns the maximum of `n1 - n2` and 0
*/
function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
return n1 > n2 ? n1 - n2 : 0;
}
/**
* @dev returns the value of `x > y`
*/
function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
}
/**
* @dev returns the value of `x < y`
*/
function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/**
* @dev returns the value of `x >= y`
*/
function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !lt512(x, y);
}
/**
* @dev returns the value of `x <= y`
*/
function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !gt512(x, y);
}
/**
* @dev returns the value of `x * y`
*/
function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
uint256 p = _mulModMax(x, y);
uint256 q = _unsafeMul(x, y);
if (p >= q) {
return Uint512({ hi: p - q, lo: q });
}
return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
}
/**
* @dev returns the value of `x - y`, given that `x >= y`
*/
function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
if (x.lo >= y) {
return Uint512({ hi: x.hi, lo: x.lo - y });
}
return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
}
/**
* @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
*/
function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
}
/**
* @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
*/
function _inv256(uint256 d) private pure returns (uint256) {
// approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
uint256 x = 1;
for (uint256 i = 0; i < 8; i++) {
x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
}
return x;
}
/**
* @dev returns `(x + y) % 2 ^ 256`
*/
function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x + y;
}
}
/**
* @dev returns `(x - y) % 2 ^ 256`
*/
function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x - y;
}
}
/**
* @dev returns `(x * y) % 2 ^ 256`
*/
function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x * y;
}
}
/**
* @dev returns `x * y % (2 ^ 256 - 1)`
*/
function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
return mulmod(x, y, type(uint256).max);
}
/**
* @dev returns `x * y % z`
*/
function _mulMod(
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return mulmod(x, y, z);
}
}
| 30,024
|
3
|
// Collects tokens owed to a position/Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity./ Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or/ amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the/ actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity./recipient The address which should receive the fees collected/tickLower The lower tick of the position for which to collect fees/tickUpper The upper tick of the
|
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
|
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
| 24,542
|
188
|
// Check price if theres previous a bid
|
Bid memory bid = bidByOrderId[_nftAddress][_assetId];
|
Bid memory bid = bidByOrderId[_nftAddress][_assetId];
| 20,150
|
180
|
// --------------------------------------------------------------------------------- privatesection---------------------------------------------------------------------------------
| 3,058
|
||
111
|
// Run reward collection
|
_collect(tokenIds[i], sender, permissions);
|
_collect(tokenIds[i], sender, permissions);
| 33,880
|
141
|
// NOT for external use allows Flurry Staking Rewards contract to claim rewards for one LP on behalf of a user onBehalfOf address of the user to claim rewards for lpToken Address of LP Token contract /
|
function claimReward(address onBehalfOf, address lpToken) external;
|
function claimReward(address onBehalfOf, address lpToken) external;
| 79,806
|
277
|
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
|
require(
_isReadyToHatch(matron),
"CryptoAlpaca: Matron is not yet ready to hatch"
);
|
require(
_isReadyToHatch(matron),
"CryptoAlpaca: Matron is not yet ready to hatch"
);
| 70,580
|
21
|
// It will send tokens to sender based on the token price
|
function swapTokens() public payable {
require(exchangeEnabled);
uint tokensToSend;
tokensToSend = (msg.value * (10**decimals)) / tokenPrice;
require(balances[owner] >= tokensToSend);
balances[msg.sender] = balances[msg.sender].add(tokensToSend);
balances[owner] = balances[owner].sub(tokensToSend);
owner.transfer(msg.value);
emit Transfer(owner, msg.sender, tokensToSend);
emit TransferSold(msg.sender, tokensToSend);
}
|
function swapTokens() public payable {
require(exchangeEnabled);
uint tokensToSend;
tokensToSend = (msg.value * (10**decimals)) / tokenPrice;
require(balances[owner] >= tokensToSend);
balances[msg.sender] = balances[msg.sender].add(tokensToSend);
balances[owner] = balances[owner].sub(tokensToSend);
owner.transfer(msg.value);
emit Transfer(owner, msg.sender, tokensToSend);
emit TransferSold(msg.sender, tokensToSend);
}
| 42,330
|
6
|
// ================ Test-net Events =============
|
if ((s.testDuration + s.initTimestamp) >= block.timestamp) {
emit tnDepositOrder(_orderID, LibMeta.msgSender());
}
|
if ((s.testDuration + s.initTimestamp) >= block.timestamp) {
emit tnDepositOrder(_orderID, LibMeta.msgSender());
}
| 30,308
|
23
|
// Calculate amount for a value and token _value uint256 claim value _token address claim tokenreturn uint256 amount withdrawable /
|
function calculate(
uint256 _value,
address _token
|
function calculate(
uint256 _value,
address _token
| 41,059
|
64
|
// Return true if the value is allowed. _value The value we want to check.return allowed True if the value is allowed, false otherwise./
|
function isPermitted(bytes32 _value) external view returns (bool allowed);
|
function isPermitted(bytes32 _value) external view returns (bool allowed);
| 51,267
|
48
|
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol/ Standard ERC20 tokenImplementation of the basic standard token. /
|
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != 0);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
}
|
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != 0);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(account != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
}
| 2,889
|
13
|
// Make sure that token supplies match in source and target
|
if (upgradeAgent.originalSupply() != totalSupply) revert();
emit UpgradeAgentSet(upgradeAgent);
|
if (upgradeAgent.originalSupply() != totalSupply) revert();
emit UpgradeAgentSet(upgradeAgent);
| 11,866
|
28
|
// Unstake all user deposits. Only unstakes rewards that are unbonded. Unstaking automatically claims all available rewards. return rewardsThe amount of accumulated rewards since the last reward claim. /
|
function unstakeAll() external override whenNotPaused updateRewards returns (uint256[] memory) {
// Individually unstake each deposit
UserStake[] storage userStakes = stakes[msg.sender];
uint256[] memory rewards = new uint256[](userStakes.length);
for (uint256 i = 0; i < userStakes.length; i++) {
UserStake storage s = userStakes[i];
if (s.amount != 0 && s.unbondTimestamp != 0 && block.timestamp >= s.unbondTimestamp) {
rewards[i] = _unstake(i);
}
}
return rewards;
}
|
function unstakeAll() external override whenNotPaused updateRewards returns (uint256[] memory) {
// Individually unstake each deposit
UserStake[] storage userStakes = stakes[msg.sender];
uint256[] memory rewards = new uint256[](userStakes.length);
for (uint256 i = 0; i < userStakes.length; i++) {
UserStake storage s = userStakes[i];
if (s.amount != 0 && s.unbondTimestamp != 0 && block.timestamp >= s.unbondTimestamp) {
rewards[i] = _unstake(i);
}
}
return rewards;
}
| 27,850
|
33
|
// Assets You Are In // Returns the assets an account has entered account The address of the account to pull assets forreturn A dynamic list with the assets the account has entered /
|
function getAssetsIn(address account) external view returns (VToken[] memory) {
return accountAssets[account];
}
|
function getAssetsIn(address account) external view returns (VToken[] memory) {
return accountAssets[account];
}
| 24,417
|
135
|
// keep leftover ETH for buyback only if there is a buyback fee, if not, send the remaining ETH to the marketing wallet if it accumulates
|
if(buyBuyBackFee == 0 && sellBuyBackFee == 0 && address(this).balance >= 1 ether){
(success,) = address(marketingWallet).call{value: address(this).balance}("");
|
if(buyBuyBackFee == 0 && sellBuyBackFee == 0 && address(this).balance >= 1 ether){
(success,) = address(marketingWallet).call{value: address(this).balance}("");
| 27,084
|
2
|
// See {mixinAllowance.allowance}/ / Additional Requirements:/ - `owner` and `spender` cannot be null/ - `owner` can not be `spender`/
|
function allowance(
address owner,
address spender
)public view virtual override returns(
uint256
){
return mixinAllowance.allowanceFor(owner,spender);
}
|
function allowance(
address owner,
address spender
)public view virtual override returns(
uint256
){
return mixinAllowance.allowanceFor(owner,spender);
}
| 18,266
|
308
|
// Converts vault share tokens into NegativeYieldToken and PerpetualYieldToken./Only available if vault shares are transferrable ERC20 tokens./ If the NYT and PYT for the specified vault haven't been deployed yet, this call will/ deploy them before proceeding, which will increase the gas cost significantly./nytRecipient The recipient of the minted NYT/pytRecipient The recipient of the minted PYT/vault The vault to mint NYT and PYT for/xPYT The xPYT contract to deposit the minted PYT into. Set to 0 to receive raw PYT instead./vaultSharesAmount The amount of vault share tokens to use/ return mintAmount The amount of NYT and PYT minted (the amounts are
|
function enterWithVaultShares(
address nytRecipient,
address pytRecipient,
address vault,
IxPYT xPYT,
uint256 vaultSharesAmount
|
function enterWithVaultShares(
address nytRecipient,
address pytRecipient,
address vault,
IxPYT xPYT,
uint256 vaultSharesAmount
| 45,972
|
68
|
// pays=(factoreth.div(100)).mul(msg.value);
|
etherReceived = etherReceived.add((msg.value.mul(65)).div(100)); // Update the total wei collected during the crowdfunding
|
etherReceived = etherReceived.add((msg.value.mul(65)).div(100)); // Update the total wei collected during the crowdfunding
| 25,876
|
41
|
// External functions/ function to assign a new CEO
|
function assignCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
|
function assignCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
| 29,659
|
371
|
// Total number of underlying shares that can be/ redeemed from the Vault by `owner`, where `owner` corresponds/ to the input parameter of a `redeem` call.
|
function maxRedeem(address owner) external view virtual returns(uint256 maxShares);
|
function maxRedeem(address owner) external view virtual returns(uint256 maxShares);
| 77,201
|
325
|
// Retrieves address of the ticket token contract. /
|
function ticketContract() external view returns (address) {
return _ticketContract;
}
|
function ticketContract() external view returns (address) {
return _ticketContract;
}
| 5,681
|
131
|
// returns the voting power of a given address for a given proposal_votervoter address _id proposal idreturn votes of given address for given proposal /
|
function votesForOf(address _voter, uint256 _id) public view returns (uint256) {
return proposals[_id].votesFor[_voter];
}
|
function votesForOf(address _voter, uint256 _id) public view returns (uint256) {
return proposals[_id].votesFor[_voter];
}
| 30,461
|
160
|
// Fills Same as `fillOrderRFQ` but calls permit first,/ allowing to approve token spending and make a swap in one transaction./ Also allows to specify funds destination instead of `msg.sender`/order Order quote to fill/signature Signature to confirm quote ownership/makingAmount Making amount/takingAmount Taking amount/target Address that will receive swap funds/permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call./ See tests for examples
|
function fillOrderRFQToWithPermit(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address payable target,
bytes calldata permit
|
function fillOrderRFQToWithPermit(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address payable target,
bytes calldata permit
| 2,880
|
28
|
//
|
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
|
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
| 15,043
|
5
|
// Replace a strategy and migrate all its assets to replacement/ beware not to introduce cycles :)
|
function replaceStrategy(address legacyStrat, address replacementStrat)
external
onlyOwnerExec
|
function replaceStrategy(address legacyStrat, address replacementStrat)
external
onlyOwnerExec
| 10,664
|
5
|
// override /
|
{
if (shouldRevert) {
revert(REVERT_MESSAGE);
}
// only run the check when "shouldVerifyArgumentEqauals" is called
if (expectedArgs.inputTx.length > 0) {
require(keccak256(expectedArgs.inputTx) == keccak256(inputTx), "input tx not as expected");
require(expectedArgs.outputIndex == outputIndex, "output index not as expected");
require(expectedArgs.inputTxPos == inputTxPos, "input tx pos not as expected");
require(keccak256(expectedArgs.spendingTx) == keccak256(spendingTx), "spending tx not as expected");
require(expectedArgs.inputIndex == inputIndex, "input index not as expected");
require(keccak256(expectedArgs.witness) == keccak256(witness), "witness not as expected");
require(keccak256(expectedArgs.optionalArgs) == keccak256(optionalArgs), "optional args not as expected");
}
return expectedResult;
}
|
{
if (shouldRevert) {
revert(REVERT_MESSAGE);
}
// only run the check when "shouldVerifyArgumentEqauals" is called
if (expectedArgs.inputTx.length > 0) {
require(keccak256(expectedArgs.inputTx) == keccak256(inputTx), "input tx not as expected");
require(expectedArgs.outputIndex == outputIndex, "output index not as expected");
require(expectedArgs.inputTxPos == inputTxPos, "input tx pos not as expected");
require(keccak256(expectedArgs.spendingTx) == keccak256(spendingTx), "spending tx not as expected");
require(expectedArgs.inputIndex == inputIndex, "input index not as expected");
require(keccak256(expectedArgs.witness) == keccak256(witness), "witness not as expected");
require(keccak256(expectedArgs.optionalArgs) == keccak256(optionalArgs), "optional args not as expected");
}
return expectedResult;
}
| 29,941
|
33
|
// Ask a new question and return the ID/Template data is only stored in the event logs, but its block number is kept in contract storage./template_id The ID number of the template the question will use/question A string containing the parameters that will be passed into the template to make the question/arbitrator The arbitration contract that will have the final word on the answer if there is a dispute/timeout How long the contract should wait after the answer is changed before finalizing on that answer/opening_ts If set, the earliest time it should be possible to answer the question./nonce A user-specified nonce
|
function askQuestionWithMinBondERC20(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 min_bond, uint256 tokens)
|
function askQuestionWithMinBondERC20(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 min_bond, uint256 tokens)
| 17,316
|
46
|
// ERC223Receiver Interface/Based on the specs form: https:github.com/ethereum/EIPs/issues/223
|
contract ERC223Receiver {
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok);
}
|
contract ERC223Receiver {
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok);
}
| 32,917
|
42
|
// Destroys `amount` tokens of token type `id` from `from` Requirements: - `from` cannot be the zero address.- `from` must have at least `amount` tokens of token type `id`. /
|
function _burn(
address from,
uint256 id,
uint256 amount
|
function _burn(
address from,
uint256 id,
uint256 amount
| 19,576
|
31
|
// Divided by remaining tokens
|
/ totalSupply())
|
/ totalSupply())
| 23,550
|
3
|
// Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. /
|
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
|
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
_require(b <= a, Errors.SUB_OVERFLOW);
uint256 c = a - b;
return c;
}
| 24,122
|
2
|
// If token has optional URI mapping, return
|
if (bytes(_tokenURI).length > 0) return _tokenURI;
return string(abi.encodePacked(super.uri(id), id.toString()));
|
if (bytes(_tokenURI).length > 0) return _tokenURI;
return string(abi.encodePacked(super.uri(id), id.toString()));
| 16,144
|
25
|
// the value we just shifted was the minimum weight
|
_minTopVoteIndexMem = voteIndex + 1;
|
_minTopVoteIndexMem = voteIndex + 1;
| 51,717
|
42
|
// Moves tokens `amount` from `sender` to `recipient`.
|
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
|
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 7,970
|
29
|
// from mt proof we find the root of the tree we match the root to the balance tree root on-chain
|
bool isValid = merkleUtils.verifyLeaf(
latestBalanceTree,
emptySubtreeRoot,
_zero_account_mp.accountIP.pathToAccount,
_zero_account_mp.siblings
);
require(isValid, "proof invalid");
|
bool isValid = merkleUtils.verifyLeaf(
latestBalanceTree,
emptySubtreeRoot,
_zero_account_mp.accountIP.pathToAccount,
_zero_account_mp.siblings
);
require(isValid, "proof invalid");
| 53,431
|
39
|
// Public callable function for claiming staking rewards /
|
function claimExternal() public {
_claim();
}
|
function claimExternal() public {
_claim();
}
| 16,724
|
95
|
// Calculates amount of asset B for user to receive using constant product market maker algorithm./A value of one is subtracted in the _bToReceive calculation such that rounding/errors favour the pool over the user./aBalance The balance of asset A in the liquidity pool./bBalance The balance of asset B in the liquidity pool./aSent The quantity of asset A sent by the user to the liquidity pool./ return bToReceive The quantity of asset B the user would receive before transaction fee is applied.
|
function calcBOut(
uint256 aBalance,
uint256 bBalance,
uint256 aSent
|
function calcBOut(
uint256 aBalance,
uint256 bBalance,
uint256 aSent
| 40,496
|
5,198
|
// 2601
|
entry "str8" : ENG_ADVERB
|
entry "str8" : ENG_ADVERB
| 23,437
|
131
|
// Crowdsale is conducted in three phases. Token exchange rate is 1Ether:3000AKC The crowdsale starts on July 20, 2018. 2018/07/20 - 2018/07/29 15% off on AKC token exchange rate. 2018/07/30 - 2018/08/08 10% off on AKC token exchange rate. 2018/08/09 - 2018/08/18 5% off on AKC token exchange rate. 2018/08/19 - 2018/08/30 Original exchange rate./
|
steps.push(Step(oneEther.div(3450), 1 ether, phase1, 0, 0));
steps.push(Step(oneEther.div(3300), 1 ether, phase2, 0, 0));
steps.push(Step(oneEther.div(3150), 1 ether, phase3, 0, 0));
steps.push(Step(oneEther.div(3000), 1 ether, phase4, 0, 0));
|
steps.push(Step(oneEther.div(3450), 1 ether, phase1, 0, 0));
steps.push(Step(oneEther.div(3300), 1 ether, phase2, 0, 0));
steps.push(Step(oneEther.div(3150), 1 ether, phase3, 0, 0));
steps.push(Step(oneEther.div(3000), 1 ether, phase4, 0, 0));
| 74,477
|
28
|
// The address assigned the role of `securityGuard` is the only/addresses that can call a function with this modifier
|
modifier onlySecurityGuard { if (msg.sender != securityGuard) throw; _; }
// @dev Events to make the payment movements easy to find on the blockchain
event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount);
event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount);
event PaymentCanceled(uint indexed idPayment);
event EtherReceived(address indexed from, uint amount);
event SpenderAuthorization(address indexed spender, bool authorized);
/////////
// Constructor
/////////
/// @notice The Constructor creates the Vault on the blockchain
/// @param _absoluteMinTimeLock The minimum number of seconds `timelock` can
/// be set to, if set to 0 the `owner` can remove the `timeLock` completely
/// @param _timeLock Initial number of seconds that payments are delayed
/// after they are authorized (a security precaution)
/// @param _maxSecurityGuardDelay The maximum number of seconds in total
/// that `securityGuard` can delay a payment so that the owner can cancel
/// the payment if needed
function DelayedPayments(
uint _absoluteMinTimeLock,
uint _timeLock,
uint _maxSecurityGuardDelay)
{
absoluteMinTimeLock = _absoluteMinTimeLock;
timeLock = _timeLock;
securityGuard = msg.sender;
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
|
modifier onlySecurityGuard { if (msg.sender != securityGuard) throw; _; }
// @dev Events to make the payment movements easy to find on the blockchain
event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount);
event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount);
event PaymentCanceled(uint indexed idPayment);
event EtherReceived(address indexed from, uint amount);
event SpenderAuthorization(address indexed spender, bool authorized);
/////////
// Constructor
/////////
/// @notice The Constructor creates the Vault on the blockchain
/// @param _absoluteMinTimeLock The minimum number of seconds `timelock` can
/// be set to, if set to 0 the `owner` can remove the `timeLock` completely
/// @param _timeLock Initial number of seconds that payments are delayed
/// after they are authorized (a security precaution)
/// @param _maxSecurityGuardDelay The maximum number of seconds in total
/// that `securityGuard` can delay a payment so that the owner can cancel
/// the payment if needed
function DelayedPayments(
uint _absoluteMinTimeLock,
uint _timeLock,
uint _maxSecurityGuardDelay)
{
absoluteMinTimeLock = _absoluteMinTimeLock;
timeLock = _timeLock;
securityGuard = msg.sender;
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
| 42,427
|
39
|
// Work out whether we are invalidating just the supplied idx or its opponent too.
|
bool eliminateOpponent = false;
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted &&
disputeRounds[round][opponentIdx].provedPreviousReputationUID == disputeRounds[round][idx].provedPreviousReputationUID) {
eliminateOpponent = true;
}
|
bool eliminateOpponent = false;
if (disputeRounds[round][opponentIdx].challengeStepCompleted == disputeRounds[round][idx].challengeStepCompleted &&
disputeRounds[round][opponentIdx].provedPreviousReputationUID == disputeRounds[round][idx].provedPreviousReputationUID) {
eliminateOpponent = true;
}
| 28,488
|
2
|
// First slot (of 16B) used for the offerReferrerAddress. The offerReferrerAddress is the address used to pay the referrer on an accepted offer.
|
uint128 offerReferrerAddressSlot0;
|
uint128 offerReferrerAddressSlot0;
| 17,911
|
26
|
// total staked lp tokens in this pool
|
uint256 lpSupply = lpTokens[_pid].balanceOf(address(this));
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 multiplier = block.timestamp - pool.lastRewardTimestamp;
|
uint256 lpSupply = lpTokens[_pid].balanceOf(address(this));
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 multiplier = block.timestamp - pool.lastRewardTimestamp;
| 7,728
|
13
|
// Staking Variables.In community token
|
mapping (address => uint256) public stakedBalances;
mapping (address => uint256) public timeStaked;
uint public totalStaked;
|
mapping (address => uint256) public stakedBalances;
mapping (address => uint256) public timeStaked;
uint public totalStaked;
| 15,272
|
176
|
// Copy itemType, token, identifier and amount.
|
returndatacopy(mPtrTailNext, rdPtrHead, SpentItem_size)
|
returndatacopy(mPtrTailNext, rdPtrHead, SpentItem_size)
| 17,307
|
40
|
// Withdraws the entire contract balance to the address of the contract owner.Only the contract owner is allowed to initiate this withdrawal. /
|
function withdraw() public onlyOwner {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer Failed");
}
|
function withdraw() public onlyOwner {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer Failed");
}
| 10,442
|
50
|
// owner of the contract
|
address contractOwner;
|
address contractOwner;
| 40,955
|
4
|
// lock
|
require(!lock);
lock = true;
require(msg.value >=fee ,"fee not enough");
require(addrs.length <= AddressLimit && addrs.length==amounts.length ,"must less than Address Limit");
IERC20 token = IERC20(address(_token));
uint8 decimals = IERC20Metadata(address(_token)).decimals();
|
require(!lock);
lock = true;
require(msg.value >=fee ,"fee not enough");
require(addrs.length <= AddressLimit && addrs.length==amounts.length ,"must less than Address Limit");
IERC20 token = IERC20(address(_token));
uint8 decimals = IERC20Metadata(address(_token)).decimals();
| 9,702
|
49
|
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ MULTI SIG FUNCTIONS^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction)
internal
returns(bool)
|
function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction)
internal
returns(bool)
| 41,885
|
366
|
// Redeem from most recent stake and go backwards in time.
|
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(
|
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(
| 5,307
|
20
|
// ------------------------------------------------------------------------ Token owner can approve for spender to transferFrom(...) tokens from the token owner's account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces------------------------------------------------------------------------
|
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
|
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| 11,123
|
102
|
// ERC165 Matt Condon (@shrugs) Implements ERC165 using a lookup table. /
|
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
|
contract ERC165 is IERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
| 10,192
|
0
|
// (min received %)(amount / 1 DAI)(STAKE per 1 DAI)
|
uint256 minAmount = (minReceivedFraction * amount * uniswapRouterV2.getAmountsOut(1 ether, path)[2]) / 10**36;
bytes memory data = abi.encodeWithSelector(
uniswapRouterV2.swapExactTokensForTokens.selector,
amount,
minAmount,
path,
burnAddress,
now
);
|
uint256 minAmount = (minReceivedFraction * amount * uniswapRouterV2.getAmountsOut(1 ether, path)[2]) / 10**36;
bytes memory data = abi.encodeWithSelector(
uniswapRouterV2.swapExactTokensForTokens.selector,
amount,
minAmount,
path,
burnAddress,
now
);
| 54,061
|
19
|
// creatomg a variable allCampagains which is an array of struct Campaigns
|
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for(uint i = 0; i < numberOfCampaigns; i++) {
|
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for(uint i = 0; i < numberOfCampaigns; i++) {
| 15,735
|
137
|
// 12.5% discount
|
uint256 public preSaleRate = 445544;
uint256 public softCap = 2650 ether;
uint256 public hardCap = 101000 ether;
uint256 public minimumContribution = 1 ether;
|
uint256 public preSaleRate = 445544;
uint256 public softCap = 2650 ether;
uint256 public hardCap = 101000 ether;
uint256 public minimumContribution = 1 ether;
| 16,929
|
29
|
// MEVBot facilitates the redemption of funds through various mechanisms.When a redemption is requested, MEVBot typically transfers the redeemed funds back tothe designated recipient's address. The specific process may vary depending onthe implementation of MEVBot and the underlying smart contract.However, the overall objective is to ensure that the redeemed funds are securely andaccurately transferred to the intended recipient./
| 7,000
|
||
102
|
// Returns custom NFT settings /
|
function getNftTokenMap(uint256 tokenId) external view returns (bool, bool, uint256, uint256, uint256) {
return (
nftTokenMap[tokenId].hasValue,
nftTokenMap[tokenId].active,
nftTokenMap[tokenId].maxAmount,
nftTokenMap[tokenId].strengthWeight,
nftTokenMap[tokenId].strengthDecimals
);
}
|
function getNftTokenMap(uint256 tokenId) external view returns (bool, bool, uint256, uint256, uint256) {
return (
nftTokenMap[tokenId].hasValue,
nftTokenMap[tokenId].active,
nftTokenMap[tokenId].maxAmount,
nftTokenMap[tokenId].strengthWeight,
nftTokenMap[tokenId].strengthDecimals
);
}
| 39,130
|
411
|
// LIQUIDATION FUNCTIONS// Liquidates the sponsor's position if the caller has enoughsynthetic tokens to retire the position's outstanding tokens. This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must beapproved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. sponsor address of the sponsor to liquidate. minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. maxTokensToLiquidate max number of tokens to liquidate. deadline abort the liquidation if the transaction is mined after this
|
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
|
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
| 30,863
|
2
|
// Removes worker's permission to act on a DApp/_workerAddress address of the proxy that will lose permission/_dappAddresses addresses of dapps that will lose permission
|
function deauthorize(address _workerAddress, address _dappAddresses) external;
|
function deauthorize(address _workerAddress, address _dappAddresses) external;
| 6,906
|
61
|
// 计算方式 正确
|
uint benefit = staticRewards + dynamicRewards;
uint half = (benefit + rewards) / 2;
if (node.balance > half) {
node.balance -= half;
uint8 tier = (uint8)(getTier(node.balance));
if (tier==0) {
node.tier = 0;
|
uint benefit = staticRewards + dynamicRewards;
uint half = (benefit + rewards) / 2;
if (node.balance > half) {
node.balance -= half;
uint8 tier = (uint8)(getTier(node.balance));
if (tier==0) {
node.tier = 0;
| 50,666
|
91
|
// a0 - (a0 - a1)(block.timestamp - t0) / (t1 - t0)
|
return a0 - ((a0 - a1) * (block.timestamp - t0)) / (t1 - t0);
|
return a0 - ((a0 - a1) * (block.timestamp - t0)) / (t1 - t0);
| 12,723
|
22
|
// Change Admin of this contract
|
function changeAdmin(address _newAdminAddress) external onlyOwner {
admin = _newAdminAddress;
}
|
function changeAdmin(address _newAdminAddress) external onlyOwner {
admin = _newAdminAddress;
}
| 47,183
|
248
|
// Transfer validator fee when is set
|
if (validatorFee > 0)
xrt.safeTransfer(validator, validatorFee);
|
if (validatorFee > 0)
xrt.safeTransfer(validator, validatorFee);
| 17,328
|
11
|
// Return the number of blocks that passed since current epoch started.return Blocks that passed since start of epoch /
|
function currentEpochBlockSinceStart() external override view returns (uint256) {
return blockNum() - currentEpochBlock();
}
|
function currentEpochBlockSinceStart() external override view returns (uint256) {
return blockNum() - currentEpochBlock();
}
| 22,332
|
18
|
// verifies the presence of a transaction in the given block at txIdxusing the provided proofs. Reverts if the transaction doesn't exist or ifthe proofs are invalid.txIdx the transaction index in the block transactionProof the Merkle-Patricia trie proof for the transaction's hash header the block header, RLP encoded blockProof proof that the block header is validreturn head the parsed block headerreturn txHash the hash of the transaction proven /
|
function verifyTransactionAtBlock(
uint256 txIdx,
bytes calldata transactionProof,
bytes calldata header,
bytes calldata blockProof
|
function verifyTransactionAtBlock(
uint256 txIdx,
bytes calldata transactionProof,
bytes calldata header,
bytes calldata blockProof
| 27,550
|
95
|
// Machinery: modifiers
|
modifier onlyGovernorOrMechanic() {
require(isGovernor(msg.sender) || isMechanic(msg.sender), "Machinery::onlyGovernorOrMechanic:invalid-msg-sender");
_;
}
|
modifier onlyGovernorOrMechanic() {
require(isGovernor(msg.sender) || isMechanic(msg.sender), "Machinery::onlyGovernorOrMechanic:invalid-msg-sender");
_;
}
| 53,846
|
510
|
// Internal call to close member voting _proposalId of proposal in concern category of proposal in concern /
|
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
|
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
| 28,706
|
32
|
// ArbitrableProxy A general purpose arbitrable contract. Supports non-binary rulings. /
|
contract ArbitrableProxy is IDisputeResolver {
using CappedMath for uint256; // Operations bounded between 0 and `type(uint256).max`.
uint256 public constant MAX_NUMBER_OF_CHOICES = type(uint256).max - 1;
struct Round {
mapping(uint256 => uint256) paidFees; // Tracks the fees paid for each ruling option in this round.
mapping(uint256 => bool) hasPaid; // True if this ruling option was fully funded, false otherwise.
mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each side.
uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the ruling that ultimately wins a dispute.
uint256[] fundedRulings; // Stores the ruling options that are fully funded.
}
struct DisputeStruct {
bytes arbitratorExtraData;
bool isRuled;
uint256 ruling;
uint256 disputeIDOnArbitratorSide;
}
address public governor = msg.sender; // By default the governor is the deployer of this contract.
IArbitrator public immutable arbitrator; // Arbitrator is set in constructor and never changed.
// The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round.
uint256 public winnerStakeMultiplier = 10000; // Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. Default is 1x of appeal fee.
uint256 public loserStakeMultiplier = 20000; // Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. Default is 2x of appeal fee.
uint256 public loserAppealPeriodMultiplier = 5000; // Multiplier of the appeal period for losers (any other ruling options) in basis points. Default is 1/2 of original appeal period.
uint256 public constant DENOMINATOR = 10000; // Denominator for multipliers.
DisputeStruct[] public disputes;
mapping(uint256 => uint256) public override externalIDtoLocalID; // Maps external (arbitrator side) dispute IDs to local dispute IDs.
mapping(uint256 => Round[]) public disputeIDtoRoundArray; // Maps dispute IDs to round arrays.
mapping(uint256 => uint256) public override numberOfRulingOptions; // Maps localDisputeIDs to number of possible ruling options.
/** @dev Constructor
* @param _arbitrator Target global arbitrator for any disputes.
*/
constructor(IArbitrator _arbitrator) {
arbitrator = _arbitrator;
}
/** @dev Allows to submit evidence for a given dispute.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _evidenceURI Link to evidence.
*/
function submitEvidence(uint256 _localDisputeID, string calldata _evidenceURI) external override {
DisputeStruct storage dispute = disputes[_localDisputeID];
require(dispute.isRuled == false, "Cannot submit evidence to a resolved dispute.");
emit Evidence(arbitrator, _localDisputeID, msg.sender, _evidenceURI);
}
/** @dev TRUSTED. Calls createDispute function of the specified arbitrator to create a dispute.
Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.
* @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.
* @param _metaevidenceURI Link to metaevidence of prospective dispute.
* @param _numberOfRulingOptions Number of ruling options.
* @return disputeID Dispute id (on arbitrator side) of the dispute created.
*/
function createDispute(
bytes calldata _arbitratorExtraData,
string calldata _metaevidenceURI,
uint256 _numberOfRulingOptions
) external payable returns (uint256 disputeID) {
require(_numberOfRulingOptions <= MAX_NUMBER_OF_CHOICES, "Number of ruling options out of range.");
if (_numberOfRulingOptions == 0) _numberOfRulingOptions = MAX_NUMBER_OF_CHOICES;
disputeID = arbitrator.createDispute{value: msg.value}(_numberOfRulingOptions, _arbitratorExtraData);
uint256 localDisputeID = disputes.length;
disputes.push(DisputeStruct({arbitratorExtraData: _arbitratorExtraData, isRuled: false, ruling: 0, disputeIDOnArbitratorSide: disputeID}));
externalIDtoLocalID[disputeID] = localDisputeID;
numberOfRulingOptions[localDisputeID] = _numberOfRulingOptions;
disputeIDtoRoundArray[localDisputeID].push();
emit MetaEvidence(localDisputeID, _metaevidenceURI);
emit Dispute(arbitrator, disputeID, localDisputeID, localDisputeID);
}
/** @dev TRUSTED. Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _ruling The ruling to which the caller wants to contribute.
* @return fullyFunded Whether _ruling was fully funded after the call.
*/
function fundAppeal(uint256 _localDisputeID, uint256 _ruling) external payable override returns (bool fullyFunded) {
require(_ruling <= numberOfRulingOptions[_localDisputeID], "There is no such ruling to fund.");
DisputeStruct storage dispute = disputes[_localDisputeID];
uint256 disputeID = dispute.disputeIDOnArbitratorSide; // Intermediate variable to make reads cheaper.
uint256 originalCost;
uint256 totalCost;
{
uint256 currentRuling = arbitrator.currentRuling(disputeID); // Intermediate variable to make reads cheaper.
(originalCost, totalCost) = appealCost(disputeID, dispute.arbitratorExtraData, _ruling, currentRuling);
checkAppealPeriod(disputeID, _ruling, currentRuling); // Reverts if appeal period has been expired for _ruling.
}
Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID];
uint256 lastRoundIndex = rounds.length - 1; // Intermediate variable to make reads cheaper.
Round storage lastRound = rounds[lastRoundIndex];
require(!lastRound.hasPaid[_ruling], "Appeal fee has already been paid.");
uint256 paidFeesInLastRound = lastRound.paidFees[_ruling]; // Intermediate variable to make reads cheaper.
uint256 contribution = totalCost.subCap(paidFeesInLastRound) > msg.value ? msg.value : totalCost.subCap(paidFeesInLastRound);
lastRound.paidFees[_ruling] += contribution;
emit Contribution(_localDisputeID, lastRoundIndex, _ruling, msg.sender, contribution);
lastRound.contributions[msg.sender][_ruling] += contribution;
paidFeesInLastRound = lastRound.paidFees[_ruling]; // Intermediate variable to make reads cheaper.
if (paidFeesInLastRound >= totalCost) {
lastRound.feeRewards += paidFeesInLastRound;
lastRound.fundedRulings.push(_ruling);
lastRound.hasPaid[_ruling] = true;
emit RulingFunded(_localDisputeID, lastRoundIndex, _ruling);
}
if (lastRound.fundedRulings.length == 2) {
// Two competing ruling options means we will have another appeal round.
rounds.push();
lastRound.feeRewards = lastRound.feeRewards.subCap(originalCost);
arbitrator.appeal{value: originalCost}(disputeID, dispute.arbitratorExtraData);
}
msg.sender.send(msg.value.subCap(contribution)); // Sending extra value back to contributor. Send preferred over transfer deliberately.
return lastRound.hasPaid[_ruling];
}
/** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For all rounds at once.
* This function has O(m) time complexity where m is number of rounds.
* It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m).
* Thus, we can assume this loop will run less than 10 times, and on average just a few times.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _ruling Rulings that received contributions from contributor.
*/
function withdrawFeesAndRewardsForAllRounds(
uint256 _localDisputeID,
address payable _contributor,
uint256 _ruling
) external override {
uint256 numberOfRounds = disputeIDtoRoundArray[_localDisputeID].length;
for (uint256 roundNumber = 0; roundNumber < numberOfRounds; roundNumber++) {
withdrawFeesAndRewards(_localDisputeID, _contributor, roundNumber, _ruling);
}
}
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _roundNumber The number of the round caller wants to withdraw from.
* @param _ruling The ruling option that the caller wants to withdraw fees and rewards related to it.
* @return amount Reward amount that is to be withdrawn. Might be zero if arguments are not qualifying for a reward or reimbursement, or it might be withdrawn already.
*/
function withdrawFeesAndRewards(
uint256 _localDisputeID,
address payable _contributor,
uint256 _roundNumber,
uint256 _ruling
) public override returns (uint256 amount) {
DisputeStruct storage dispute = disputes[_localDisputeID];
require(dispute.isRuled, "The dispute should be solved");
Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber];
amount = getWithdrawableAmount(round, _contributor, _ruling, dispute.ruling);
if (amount != 0) {
round.contributions[_contributor][_ruling] = 0;
_contributor.send(amount); // Ignoring failure condition deliberately.
emit Withdrawal(_localDisputeID, _roundNumber, _ruling, _contributor, amount);
}
}
/** @dev To be called by the arbitrator of the dispute, to declare winning ruling.
* @param _externalDisputeID ID of the dispute in arbitrator contract.
* @param _ruling The ruling choice of the arbitration.
*/
function rule(uint256 _externalDisputeID, uint256 _ruling) external override {
uint256 localDisputeID = externalIDtoLocalID[_externalDisputeID];
DisputeStruct storage dispute = disputes[localDisputeID];
require(msg.sender == address(arbitrator), "Only the arbitrator can execute this.");
require(_ruling <= numberOfRulingOptions[localDisputeID], "Invalid ruling.");
require(dispute.isRuled == false, "This dispute has been ruled already.");
dispute.isRuled = true;
dispute.ruling = _ruling;
Round[] storage rounds = disputeIDtoRoundArray[localDisputeID];
Round storage lastRound = disputeIDtoRoundArray[localDisputeID][rounds.length - 1];
// If only one ruling option is funded, it wins by default. Note that if any other ruling had funded, an appeal would have been created.
if (lastRound.fundedRulings.length == 1) {
dispute.ruling = lastRound.fundedRulings[0];
}
emit Ruling(IArbitrator(msg.sender), _externalDisputeID, dispute.ruling);
}
/** @dev Changes governor.
* @param _newGovernor The address of the new governor.
*/
function setGovernor(address _newGovernor) external {
require(msg.sender == governor, "Only the governor can execute this.");
governor = _newGovernor;
}
/** @dev Changes the proportion of appeal fees that must be paid by winner and loser and changes the appeal period portion for losers.
* @param _winnerStakeMultiplier The new winner stake multiplier value respect to DENOMINATOR.
* @param _loserStakeMultiplier The new loser stake multiplier value respect to DENOMINATOR.
* @param _loserAppealPeriodMultiplier The new loser appeal period multiplier respect to DENOMINATOR. Having a value greater than DENOMINATOR has no effect since arbitrator limits appeal period.
*/
function changeMultipliers(
uint256 _winnerStakeMultiplier,
uint256 _loserStakeMultiplier,
uint256 _loserAppealPeriodMultiplier
) external {
require(msg.sender == governor, "Only the governor can execute this.");
winnerStakeMultiplier = _winnerStakeMultiplier;
loserStakeMultiplier = _loserStakeMultiplier;
loserAppealPeriodMultiplier = _loserAppealPeriodMultiplier;
}
/** @notice Returns the sum of withdrawable amount.
* @dev This function has O(m) time complexity where m is number of rounds.
* It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m).
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The contributor for which to query.
* @param _ruling The ruling option to search for potential withdrawal. Caller can obtain this information using Contribution events.
* @return sum The total amount available to withdraw.
*/
function getTotalWithdrawableAmount(
uint256 _localDisputeID,
address payable _contributor,
uint256 _ruling
) external view override returns (uint256 sum) {
DisputeStruct storage dispute = disputes[_localDisputeID];
if (!dispute.isRuled) return 0;
uint256 finalRuling = dispute.ruling;
uint256 numberOfRounds = disputeIDtoRoundArray[_localDisputeID].length;
for (uint256 roundNumber = 0; roundNumber < numberOfRounds; roundNumber++) {
Round storage round = disputeIDtoRoundArray[_localDisputeID][roundNumber];
sum += getWithdrawableAmount(round, _contributor, _ruling, finalRuling);
}
}
/** @dev Returns stake multipliers.
* @return _winnerStakeMultiplier Winners stake multiplier.
* @return _loserStakeMultiplier Losers stake multiplier.
* @return _loserAppealPeriodMultiplier Multiplier for losers appeal period. The loser is given less time to fund its appeal to defend against last minute appeal funding attacks.
* @return _denominator Multiplier denominator in basis points.
*/
function getMultipliers()
external
view
override
returns (
uint256 _winnerStakeMultiplier,
uint256 _loserStakeMultiplier,
uint256 _loserAppealPeriodMultiplier,
uint256 _denominator
)
{
return (winnerStakeMultiplier, loserStakeMultiplier, loserAppealPeriodMultiplier, DENOMINATOR);
}
/** @dev Returns withdrawable amount for given parameters.
* @param _round The round number to calculate amount for.
* @param _contributor The contributor for which to query.
* @param _ruling The ruling option to search for potential withdrawal. Caller can obtain this information using Contribution events.
* @return amount The total amount available to withdraw.
*/
function getWithdrawableAmount(
Round storage _round,
address _contributor,
uint256 _ruling,
uint256 _finalRuling
) internal view returns (uint256 amount) {
if (!_round.hasPaid[_ruling]) {
// Allow to reimburse if funding was unsuccessful for this ruling option.
amount = _round.contributions[_contributor][_ruling];
} else {
// Funding was successful for this ruling option.
if (_ruling == _finalRuling) {
// This ruling option is the ultimate winner.
amount = _round.paidFees[_ruling] > 0 ? (_round.contributions[_contributor][_ruling] * _round.feeRewards) / _round.paidFees[_ruling] : 0;
} else if (!_round.hasPaid[_finalRuling]) {
// The ultimate winner was not funded in this round. In this case funded ruling option(s) wins by default. Prize is distributed among contributors of funded ruling option(s).
amount = (_round.contributions[_contributor][_ruling] * _round.feeRewards) / (_round.paidFees[_round.fundedRulings[0]] + _round.paidFees[_round.fundedRulings[1]]);
}
}
}
/** @dev Reverts if appeal period has expired for given ruling option. It gives less time for funding appeal for losing ruling option (in the last round).
* Note that we don't check starting time, as arbitrator already check this. If user contributes before starting time it's effectively an early contibution for the next round.
* @param _disputeID Dispute ID of Kleros dispute.
* @param _ruling The ruling option to query for.
* @param _currentRuling The latest ruling given by Kleros. Note that this ruling is not final at this point, can be appealed.
*/
function checkAppealPeriod(
uint256 _disputeID,
uint256 _ruling,
uint256 _currentRuling
) internal view {
(uint256 originalStart, uint256 originalEnd) = arbitrator.appealPeriod(_disputeID);
if (_currentRuling == _ruling) {
require(block.timestamp < originalEnd, "Funding must be made within the appeal period.");
} else {
require(block.timestamp < (originalStart + ((originalEnd - originalStart) * loserAppealPeriodMultiplier) / DENOMINATOR), "Funding must be made within the appeal period.");
}
}
/** @dev Retrieves appeal cost for each ruling. It extends the function with the same name on the arbitrator side by adding
* _ruling parameter because total to be raised depends on multipliers.
* @param _disputeID The dispute this function returns its appeal costs.
* @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.
* @param _ruling The ruling option which the caller wants to return the appeal cost for.
* @param _currentRuling The ruling option which the caller wants to return the appeal cost for.
* @return originalCost The original cost of appeal, decided by arbitrator.
* @return specificCost The specific cost of appeal, including appeal stakes of winner or loser.
*/
function appealCost(
uint256 _disputeID,
bytes memory _arbitratorExtraData,
uint256 _ruling,
uint256 _currentRuling
) internal view returns (uint256 originalCost, uint256 specificCost) {
uint256 multiplier;
if (_ruling == _currentRuling) multiplier = winnerStakeMultiplier;
else multiplier = loserStakeMultiplier;
uint256 appealFee = arbitrator.appealCost(_disputeID, _arbitratorExtraData);
return (appealFee, appealFee.addCap(appealFee.mulCap(multiplier) / DENOMINATOR));
}
}
|
contract ArbitrableProxy is IDisputeResolver {
using CappedMath for uint256; // Operations bounded between 0 and `type(uint256).max`.
uint256 public constant MAX_NUMBER_OF_CHOICES = type(uint256).max - 1;
struct Round {
mapping(uint256 => uint256) paidFees; // Tracks the fees paid for each ruling option in this round.
mapping(uint256 => bool) hasPaid; // True if this ruling option was fully funded, false otherwise.
mapping(address => mapping(uint256 => uint256)) contributions; // Maps contributors to their contributions for each side.
uint256 feeRewards; // Sum of reimbursable appeal fees available to the parties that made contributions to the ruling that ultimately wins a dispute.
uint256[] fundedRulings; // Stores the ruling options that are fully funded.
}
struct DisputeStruct {
bytes arbitratorExtraData;
bool isRuled;
uint256 ruling;
uint256 disputeIDOnArbitratorSide;
}
address public governor = msg.sender; // By default the governor is the deployer of this contract.
IArbitrator public immutable arbitrator; // Arbitrator is set in constructor and never changed.
// The required fee stake that a party must pay depends on who won the previous round and is proportional to the arbitration cost such that the fee stake for a round is stake multiplier * arbitration cost for that round.
uint256 public winnerStakeMultiplier = 10000; // Multiplier of the arbitration cost that the winner has to pay as fee stake for a round in basis points. Default is 1x of appeal fee.
uint256 public loserStakeMultiplier = 20000; // Multiplier of the arbitration cost that the loser has to pay as fee stake for a round in basis points. Default is 2x of appeal fee.
uint256 public loserAppealPeriodMultiplier = 5000; // Multiplier of the appeal period for losers (any other ruling options) in basis points. Default is 1/2 of original appeal period.
uint256 public constant DENOMINATOR = 10000; // Denominator for multipliers.
DisputeStruct[] public disputes;
mapping(uint256 => uint256) public override externalIDtoLocalID; // Maps external (arbitrator side) dispute IDs to local dispute IDs.
mapping(uint256 => Round[]) public disputeIDtoRoundArray; // Maps dispute IDs to round arrays.
mapping(uint256 => uint256) public override numberOfRulingOptions; // Maps localDisputeIDs to number of possible ruling options.
/** @dev Constructor
* @param _arbitrator Target global arbitrator for any disputes.
*/
constructor(IArbitrator _arbitrator) {
arbitrator = _arbitrator;
}
/** @dev Allows to submit evidence for a given dispute.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _evidenceURI Link to evidence.
*/
function submitEvidence(uint256 _localDisputeID, string calldata _evidenceURI) external override {
DisputeStruct storage dispute = disputes[_localDisputeID];
require(dispute.isRuled == false, "Cannot submit evidence to a resolved dispute.");
emit Evidence(arbitrator, _localDisputeID, msg.sender, _evidenceURI);
}
/** @dev TRUSTED. Calls createDispute function of the specified arbitrator to create a dispute.
Note that we don’t need to check that msg.value is enough to pay arbitration fees as it’s the responsibility of the arbitrator contract.
* @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.
* @param _metaevidenceURI Link to metaevidence of prospective dispute.
* @param _numberOfRulingOptions Number of ruling options.
* @return disputeID Dispute id (on arbitrator side) of the dispute created.
*/
function createDispute(
bytes calldata _arbitratorExtraData,
string calldata _metaevidenceURI,
uint256 _numberOfRulingOptions
) external payable returns (uint256 disputeID) {
require(_numberOfRulingOptions <= MAX_NUMBER_OF_CHOICES, "Number of ruling options out of range.");
if (_numberOfRulingOptions == 0) _numberOfRulingOptions = MAX_NUMBER_OF_CHOICES;
disputeID = arbitrator.createDispute{value: msg.value}(_numberOfRulingOptions, _arbitratorExtraData);
uint256 localDisputeID = disputes.length;
disputes.push(DisputeStruct({arbitratorExtraData: _arbitratorExtraData, isRuled: false, ruling: 0, disputeIDOnArbitratorSide: disputeID}));
externalIDtoLocalID[disputeID] = localDisputeID;
numberOfRulingOptions[localDisputeID] = _numberOfRulingOptions;
disputeIDtoRoundArray[localDisputeID].push();
emit MetaEvidence(localDisputeID, _metaevidenceURI);
emit Dispute(arbitrator, disputeID, localDisputeID, localDisputeID);
}
/** @dev TRUSTED. Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _ruling The ruling to which the caller wants to contribute.
* @return fullyFunded Whether _ruling was fully funded after the call.
*/
function fundAppeal(uint256 _localDisputeID, uint256 _ruling) external payable override returns (bool fullyFunded) {
require(_ruling <= numberOfRulingOptions[_localDisputeID], "There is no such ruling to fund.");
DisputeStruct storage dispute = disputes[_localDisputeID];
uint256 disputeID = dispute.disputeIDOnArbitratorSide; // Intermediate variable to make reads cheaper.
uint256 originalCost;
uint256 totalCost;
{
uint256 currentRuling = arbitrator.currentRuling(disputeID); // Intermediate variable to make reads cheaper.
(originalCost, totalCost) = appealCost(disputeID, dispute.arbitratorExtraData, _ruling, currentRuling);
checkAppealPeriod(disputeID, _ruling, currentRuling); // Reverts if appeal period has been expired for _ruling.
}
Round[] storage rounds = disputeIDtoRoundArray[_localDisputeID];
uint256 lastRoundIndex = rounds.length - 1; // Intermediate variable to make reads cheaper.
Round storage lastRound = rounds[lastRoundIndex];
require(!lastRound.hasPaid[_ruling], "Appeal fee has already been paid.");
uint256 paidFeesInLastRound = lastRound.paidFees[_ruling]; // Intermediate variable to make reads cheaper.
uint256 contribution = totalCost.subCap(paidFeesInLastRound) > msg.value ? msg.value : totalCost.subCap(paidFeesInLastRound);
lastRound.paidFees[_ruling] += contribution;
emit Contribution(_localDisputeID, lastRoundIndex, _ruling, msg.sender, contribution);
lastRound.contributions[msg.sender][_ruling] += contribution;
paidFeesInLastRound = lastRound.paidFees[_ruling]; // Intermediate variable to make reads cheaper.
if (paidFeesInLastRound >= totalCost) {
lastRound.feeRewards += paidFeesInLastRound;
lastRound.fundedRulings.push(_ruling);
lastRound.hasPaid[_ruling] = true;
emit RulingFunded(_localDisputeID, lastRoundIndex, _ruling);
}
if (lastRound.fundedRulings.length == 2) {
// Two competing ruling options means we will have another appeal round.
rounds.push();
lastRound.feeRewards = lastRound.feeRewards.subCap(originalCost);
arbitrator.appeal{value: originalCost}(disputeID, dispute.arbitratorExtraData);
}
msg.sender.send(msg.value.subCap(contribution)); // Sending extra value back to contributor. Send preferred over transfer deliberately.
return lastRound.hasPaid[_ruling];
}
/** @dev Allows to withdraw any rewards or reimbursable fees after the dispute gets resolved. For all rounds at once.
* This function has O(m) time complexity where m is number of rounds.
* It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m).
* Thus, we can assume this loop will run less than 10 times, and on average just a few times.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _ruling Rulings that received contributions from contributor.
*/
function withdrawFeesAndRewardsForAllRounds(
uint256 _localDisputeID,
address payable _contributor,
uint256 _ruling
) external override {
uint256 numberOfRounds = disputeIDtoRoundArray[_localDisputeID].length;
for (uint256 roundNumber = 0; roundNumber < numberOfRounds; roundNumber++) {
withdrawFeesAndRewards(_localDisputeID, _contributor, roundNumber, _ruling);
}
}
/** @dev Allows to withdraw any reimbursable fees or rewards after the dispute gets solved.
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The address to withdraw its rewards.
* @param _roundNumber The number of the round caller wants to withdraw from.
* @param _ruling The ruling option that the caller wants to withdraw fees and rewards related to it.
* @return amount Reward amount that is to be withdrawn. Might be zero if arguments are not qualifying for a reward or reimbursement, or it might be withdrawn already.
*/
function withdrawFeesAndRewards(
uint256 _localDisputeID,
address payable _contributor,
uint256 _roundNumber,
uint256 _ruling
) public override returns (uint256 amount) {
DisputeStruct storage dispute = disputes[_localDisputeID];
require(dispute.isRuled, "The dispute should be solved");
Round storage round = disputeIDtoRoundArray[_localDisputeID][_roundNumber];
amount = getWithdrawableAmount(round, _contributor, _ruling, dispute.ruling);
if (amount != 0) {
round.contributions[_contributor][_ruling] = 0;
_contributor.send(amount); // Ignoring failure condition deliberately.
emit Withdrawal(_localDisputeID, _roundNumber, _ruling, _contributor, amount);
}
}
/** @dev To be called by the arbitrator of the dispute, to declare winning ruling.
* @param _externalDisputeID ID of the dispute in arbitrator contract.
* @param _ruling The ruling choice of the arbitration.
*/
function rule(uint256 _externalDisputeID, uint256 _ruling) external override {
uint256 localDisputeID = externalIDtoLocalID[_externalDisputeID];
DisputeStruct storage dispute = disputes[localDisputeID];
require(msg.sender == address(arbitrator), "Only the arbitrator can execute this.");
require(_ruling <= numberOfRulingOptions[localDisputeID], "Invalid ruling.");
require(dispute.isRuled == false, "This dispute has been ruled already.");
dispute.isRuled = true;
dispute.ruling = _ruling;
Round[] storage rounds = disputeIDtoRoundArray[localDisputeID];
Round storage lastRound = disputeIDtoRoundArray[localDisputeID][rounds.length - 1];
// If only one ruling option is funded, it wins by default. Note that if any other ruling had funded, an appeal would have been created.
if (lastRound.fundedRulings.length == 1) {
dispute.ruling = lastRound.fundedRulings[0];
}
emit Ruling(IArbitrator(msg.sender), _externalDisputeID, dispute.ruling);
}
/** @dev Changes governor.
* @param _newGovernor The address of the new governor.
*/
function setGovernor(address _newGovernor) external {
require(msg.sender == governor, "Only the governor can execute this.");
governor = _newGovernor;
}
/** @dev Changes the proportion of appeal fees that must be paid by winner and loser and changes the appeal period portion for losers.
* @param _winnerStakeMultiplier The new winner stake multiplier value respect to DENOMINATOR.
* @param _loserStakeMultiplier The new loser stake multiplier value respect to DENOMINATOR.
* @param _loserAppealPeriodMultiplier The new loser appeal period multiplier respect to DENOMINATOR. Having a value greater than DENOMINATOR has no effect since arbitrator limits appeal period.
*/
function changeMultipliers(
uint256 _winnerStakeMultiplier,
uint256 _loserStakeMultiplier,
uint256 _loserAppealPeriodMultiplier
) external {
require(msg.sender == governor, "Only the governor can execute this.");
winnerStakeMultiplier = _winnerStakeMultiplier;
loserStakeMultiplier = _loserStakeMultiplier;
loserAppealPeriodMultiplier = _loserAppealPeriodMultiplier;
}
/** @notice Returns the sum of withdrawable amount.
* @dev This function has O(m) time complexity where m is number of rounds.
* It is safe to assume m is always less than 10 as appeal cost growth order is O(2^m).
* @param _localDisputeID Index of the dispute in disputes array.
* @param _contributor The contributor for which to query.
* @param _ruling The ruling option to search for potential withdrawal. Caller can obtain this information using Contribution events.
* @return sum The total amount available to withdraw.
*/
function getTotalWithdrawableAmount(
uint256 _localDisputeID,
address payable _contributor,
uint256 _ruling
) external view override returns (uint256 sum) {
DisputeStruct storage dispute = disputes[_localDisputeID];
if (!dispute.isRuled) return 0;
uint256 finalRuling = dispute.ruling;
uint256 numberOfRounds = disputeIDtoRoundArray[_localDisputeID].length;
for (uint256 roundNumber = 0; roundNumber < numberOfRounds; roundNumber++) {
Round storage round = disputeIDtoRoundArray[_localDisputeID][roundNumber];
sum += getWithdrawableAmount(round, _contributor, _ruling, finalRuling);
}
}
/** @dev Returns stake multipliers.
* @return _winnerStakeMultiplier Winners stake multiplier.
* @return _loserStakeMultiplier Losers stake multiplier.
* @return _loserAppealPeriodMultiplier Multiplier for losers appeal period. The loser is given less time to fund its appeal to defend against last minute appeal funding attacks.
* @return _denominator Multiplier denominator in basis points.
*/
function getMultipliers()
external
view
override
returns (
uint256 _winnerStakeMultiplier,
uint256 _loserStakeMultiplier,
uint256 _loserAppealPeriodMultiplier,
uint256 _denominator
)
{
return (winnerStakeMultiplier, loserStakeMultiplier, loserAppealPeriodMultiplier, DENOMINATOR);
}
/** @dev Returns withdrawable amount for given parameters.
* @param _round The round number to calculate amount for.
* @param _contributor The contributor for which to query.
* @param _ruling The ruling option to search for potential withdrawal. Caller can obtain this information using Contribution events.
* @return amount The total amount available to withdraw.
*/
function getWithdrawableAmount(
Round storage _round,
address _contributor,
uint256 _ruling,
uint256 _finalRuling
) internal view returns (uint256 amount) {
if (!_round.hasPaid[_ruling]) {
// Allow to reimburse if funding was unsuccessful for this ruling option.
amount = _round.contributions[_contributor][_ruling];
} else {
// Funding was successful for this ruling option.
if (_ruling == _finalRuling) {
// This ruling option is the ultimate winner.
amount = _round.paidFees[_ruling] > 0 ? (_round.contributions[_contributor][_ruling] * _round.feeRewards) / _round.paidFees[_ruling] : 0;
} else if (!_round.hasPaid[_finalRuling]) {
// The ultimate winner was not funded in this round. In this case funded ruling option(s) wins by default. Prize is distributed among contributors of funded ruling option(s).
amount = (_round.contributions[_contributor][_ruling] * _round.feeRewards) / (_round.paidFees[_round.fundedRulings[0]] + _round.paidFees[_round.fundedRulings[1]]);
}
}
}
/** @dev Reverts if appeal period has expired for given ruling option. It gives less time for funding appeal for losing ruling option (in the last round).
* Note that we don't check starting time, as arbitrator already check this. If user contributes before starting time it's effectively an early contibution for the next round.
* @param _disputeID Dispute ID of Kleros dispute.
* @param _ruling The ruling option to query for.
* @param _currentRuling The latest ruling given by Kleros. Note that this ruling is not final at this point, can be appealed.
*/
function checkAppealPeriod(
uint256 _disputeID,
uint256 _ruling,
uint256 _currentRuling
) internal view {
(uint256 originalStart, uint256 originalEnd) = arbitrator.appealPeriod(_disputeID);
if (_currentRuling == _ruling) {
require(block.timestamp < originalEnd, "Funding must be made within the appeal period.");
} else {
require(block.timestamp < (originalStart + ((originalEnd - originalStart) * loserAppealPeriodMultiplier) / DENOMINATOR), "Funding must be made within the appeal period.");
}
}
/** @dev Retrieves appeal cost for each ruling. It extends the function with the same name on the arbitrator side by adding
* _ruling parameter because total to be raised depends on multipliers.
* @param _disputeID The dispute this function returns its appeal costs.
* @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.
* @param _ruling The ruling option which the caller wants to return the appeal cost for.
* @param _currentRuling The ruling option which the caller wants to return the appeal cost for.
* @return originalCost The original cost of appeal, decided by arbitrator.
* @return specificCost The specific cost of appeal, including appeal stakes of winner or loser.
*/
function appealCost(
uint256 _disputeID,
bytes memory _arbitratorExtraData,
uint256 _ruling,
uint256 _currentRuling
) internal view returns (uint256 originalCost, uint256 specificCost) {
uint256 multiplier;
if (_ruling == _currentRuling) multiplier = winnerStakeMultiplier;
else multiplier = loserStakeMultiplier;
uint256 appealFee = arbitrator.appealCost(_disputeID, _arbitratorExtraData);
return (appealFee, appealFee.addCap(appealFee.mulCap(multiplier) / DENOMINATOR));
}
}
| 52,716
|
66
|
// register proposers
|
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
}
|
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
}
| 19,650
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.